blob: 6a503ee2d9b50a0d48d6075760e30243e8b0dad6 [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();
505 return move(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
Richard Trieuccd891a2011-09-09 01:45:06 +00001101 ParsedType *ParsedTypes = ArgTypes.release();
1102 Expr **Exprs = ArgExprs.release();
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,
1188 Types, Exprs, NumAssocs, DefaultLoc,
1189 RParenLoc, ContainsUnexpandedParameterPack));
1190
Chris Lattner5f9e2722011-07-23 10:55:15 +00001191 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001192 unsigned DefaultIndex = -1U;
1193 for (unsigned i = 0; i < NumAssocs; ++i) {
1194 if (!Types[i])
1195 DefaultIndex = i;
1196 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1197 Types[i]->getType()))
1198 CompatIndices.push_back(i);
1199 }
1200
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001201 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001202 // type compatible with at most one of the types named in its generic
1203 // association list."
1204 if (CompatIndices.size() > 1) {
1205 // We strip parens here because the controlling expression is typically
1206 // parenthesized in macro definitions.
1207 ControllingExpr = ControllingExpr->IgnoreParens();
1208 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1209 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1210 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001211 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001212 E = CompatIndices.end(); I != E; ++I) {
1213 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1214 diag::note_compat_assoc)
1215 << Types[*I]->getTypeLoc().getSourceRange()
1216 << Types[*I]->getType();
1217 }
1218 return ExprError();
1219 }
1220
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001221 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001222 // its controlling expression shall have type compatible with exactly one of
1223 // the types named in its generic association list."
1224 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1225 // We strip parens here because the controlling expression is typically
1226 // parenthesized in macro definitions.
1227 ControllingExpr = ControllingExpr->IgnoreParens();
1228 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1229 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1230 return ExprError();
1231 }
1232
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001233 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001234 // type name that is compatible with the type of the controlling expression,
1235 // then the result expression of the generic selection is the expression
1236 // in that generic association. Otherwise, the result expression of the
1237 // generic selection is the expression in the default generic association."
1238 unsigned ResultIndex =
1239 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1240
1241 return Owned(new (Context) GenericSelectionExpr(
1242 Context, KeyLoc, ControllingExpr,
1243 Types, Exprs, NumAssocs, DefaultLoc,
1244 RParenLoc, ContainsUnexpandedParameterPack,
1245 ResultIndex));
1246}
1247
Richard Smithdd66be72012-03-08 01:34:56 +00001248/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1249/// location of the token and the offset of the ud-suffix within it.
1250static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1251 unsigned Offset) {
1252 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001253 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001254}
1255
Richard Smith36f5cfe2012-03-09 08:00:36 +00001256/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1257/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1258static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1259 IdentifierInfo *UDSuffix,
1260 SourceLocation UDSuffixLoc,
1261 ArrayRef<Expr*> Args,
1262 SourceLocation LitEndLoc) {
1263 assert(Args.size() <= 2 && "too many arguments for literal operator");
1264
1265 QualType ArgTy[2];
1266 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1267 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1268 if (ArgTy[ArgIdx]->isArrayType())
1269 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1270 }
1271
1272 DeclarationName OpName =
1273 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1274 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1275 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1276
1277 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1278 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1279 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1280 return ExprError();
1281
1282 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1283}
1284
Steve Narofff69936d2007-09-16 03:34:24 +00001285/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001286/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1287/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1288/// multiple tokens. However, the common case is that StringToks points to one
1289/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001290///
John McCall60d7b3a2010-08-24 06:29:42 +00001291ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001292Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1293 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 assert(NumStringToks && "Must have at least one string!");
1295
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001296 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001298 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001299
Chris Lattner5f9e2722011-07-23 10:55:15 +00001300 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 for (unsigned i = 0; i != NumStringToks; ++i)
1302 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001303
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001304 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001305 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001306 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001307 else if (Literal.isUTF16())
1308 StrTy = Context.Char16Ty;
1309 else if (Literal.isUTF32())
1310 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001311 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001312 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001313
Douglas Gregor5cee1192011-07-27 05:40:30 +00001314 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1315 if (Literal.isWide())
1316 Kind = StringLiteral::Wide;
1317 else if (Literal.isUTF8())
1318 Kind = StringLiteral::UTF8;
1319 else if (Literal.isUTF16())
1320 Kind = StringLiteral::UTF16;
1321 else if (Literal.isUTF32())
1322 Kind = StringLiteral::UTF32;
1323
Douglas Gregor77a52232008-09-12 00:47:35 +00001324 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001325 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001326 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001327
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001328 // Get an array type for the string, according to C99 6.4.5. This includes
1329 // the nul terminator character as well as the string length for pascal
1330 // strings.
1331 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001332 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001333 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001336 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1337 Kind, Literal.Pascal, StrTy,
1338 &StringTokLocs[0],
1339 StringTokLocs.size());
1340 if (Literal.getUDSuffix().empty())
1341 return Owned(Lit);
1342
1343 // We're building a user-defined literal.
1344 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001345 SourceLocation UDSuffixLoc =
1346 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1347 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001348
Richard Smith36f5cfe2012-03-09 08:00:36 +00001349 // Make sure we're allowed user-defined literals here.
1350 if (!UDLScope)
1351 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1352
Richard Smith9fcce652012-03-07 08:35:16 +00001353 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1354 // operator "" X (str, len)
1355 QualType SizeType = Context.getSizeType();
1356 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1357 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1358 StringTokLocs[0]);
1359 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001360 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1361 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001362}
1363
John McCall60d7b3a2010-08-24 06:29:42 +00001364ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001365Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001366 SourceLocation Loc,
1367 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001368 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001369 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001370}
1371
John McCall76a40212011-02-09 01:13:10 +00001372/// BuildDeclRefExpr - Build an expression that references a
1373/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001374ExprResult
John McCall76a40212011-02-09 01:13:10 +00001375Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001376 const DeclarationNameInfo &NameInfo,
1377 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001378 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001379 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1380 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1381 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1382 CalleeTarget = IdentifyCUDATarget(Callee);
1383 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1384 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1385 << CalleeTarget << D->getIdentifier() << CallerTarget;
1386 Diag(D->getLocation(), diag::note_previous_decl)
1387 << D->getIdentifier();
1388 return ExprError();
1389 }
1390 }
1391
John McCallf4b88a42012-03-10 09:33:50 +00001392 bool refersToEnclosingScope =
1393 (CurContext != D->getDeclContext() &&
1394 D->getDeclContext()->isFunctionOrMethod());
1395
Eli Friedman5f2987c2012-02-02 03:46:19 +00001396 DeclRefExpr *E = DeclRefExpr::Create(Context,
1397 SS ? SS->getWithLocInContext(Context)
1398 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001399 SourceLocation(),
1400 D, refersToEnclosingScope,
1401 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Eli Friedman5f2987c2012-02-02 03:46:19 +00001403 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001404
1405 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001406 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1407 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001408 E->setObjectKind(OK_BitField);
1409
1410 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001411}
1412
Abramo Bagnara25777432010-08-11 22:01:17 +00001413/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001414/// possibly a list of template arguments.
1415///
1416/// If this produces template arguments, it is permitted to call
1417/// DecomposeTemplateName.
1418///
1419/// This actually loses a lot of source location information for
1420/// non-standard name kinds; we should consider preserving that in
1421/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001422void
1423Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1424 TemplateArgumentListInfo &Buffer,
1425 DeclarationNameInfo &NameInfo,
1426 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001427 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1428 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1429 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1430
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001431 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001432 Id.TemplateId->getTemplateArgs(),
1433 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001434 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001435 TemplateArgsPtr.release();
1436
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();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001800 return move(E);
1801 }
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: {
John McCall755d8492011-04-12 00:42:48 +00002419 const FunctionType *fty = type->castAs<FunctionType>();
2420
2421 // If we're referring to a function with an __unknown_anytype
2422 // result type, make the entire expression __unknown_anytype.
2423 if (fty->getResultType() == Context.UnknownAnyTy) {
2424 type = Context.UnknownAnyTy;
2425 valueKind = VK_RValue;
2426 break;
2427 }
2428
John McCall76a40212011-02-09 01:13:10 +00002429 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002430 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002431 valueKind = VK_LValue;
2432 break;
2433 }
2434
2435 // C99 DR 316 says that, if a function type comes from a
2436 // function definition (without a prototype), that type is only
2437 // used for checking compatibility. Therefore, when referencing
2438 // the function, we pretend that we don't have the full function
2439 // type.
John McCall755d8492011-04-12 00:42:48 +00002440 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2441 isa<FunctionProtoType>(fty))
2442 type = Context.getFunctionNoProtoType(fty->getResultType(),
2443 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002444
2445 // Functions are r-values in C.
2446 valueKind = VK_RValue;
2447 break;
2448 }
2449
2450 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002451 // If we're referring to a method with an __unknown_anytype
2452 // result type, make the entire expression __unknown_anytype.
2453 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002454 if (const FunctionProtoType *proto
2455 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002456 if (proto->getResultType() == Context.UnknownAnyTy) {
2457 type = Context.UnknownAnyTy;
2458 valueKind = VK_RValue;
2459 break;
2460 }
2461
John McCall76a40212011-02-09 01:13:10 +00002462 // C++ methods are l-values if static, r-values if non-static.
2463 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2464 valueKind = VK_LValue;
2465 break;
2466 }
2467 // fallthrough
2468
2469 case Decl::CXXConversion:
2470 case Decl::CXXDestructor:
2471 case Decl::CXXConstructor:
2472 valueKind = VK_RValue;
2473 break;
2474 }
2475
2476 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2477 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002478}
2479
John McCall755d8492011-04-12 00:42:48 +00002480ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002481 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002482
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002484 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002485 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2486 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002487 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002488 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002489 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002490
Chris Lattnerfa28b302008-01-12 08:14:25 +00002491 // Pre-defined identifiers are of type char[x], where x is the length of the
2492 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002493
Anders Carlsson3a082d82009-09-08 18:24:21 +00002494 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002495 if (!currentDecl && getCurBlock())
2496 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002497 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002498 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002499 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002500 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002501
Anders Carlsson773f3972009-09-11 01:22:35 +00002502 QualType ResTy;
2503 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2504 ResTy = Context.DependentTy;
2505 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002506 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002507
Anders Carlsson773f3972009-09-11 01:22:35 +00002508 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002509 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002510 ResTy = Context.WCharTy.withConst();
2511 else
2512 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002513 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2514 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002515 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002516}
2517
Richard Smith36f5cfe2012-03-09 08:00:36 +00002518ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002519 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002520 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002521 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002522 if (Invalid)
2523 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002524
Benjamin Kramerddeea562010-02-27 13:44:12 +00002525 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002526 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002528 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002529
Chris Lattnere8337df2009-12-30 21:19:39 +00002530 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002531 if (Literal.isWide())
2532 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002533 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002534 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002535 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002536 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002537 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002538 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002539 else
2540 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002541
Douglas Gregor5cee1192011-07-27 05:40:30 +00002542 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2543 if (Literal.isWide())
2544 Kind = CharacterLiteral::Wide;
2545 else if (Literal.isUTF16())
2546 Kind = CharacterLiteral::UTF16;
2547 else if (Literal.isUTF32())
2548 Kind = CharacterLiteral::UTF32;
2549
Richard Smithdd66be72012-03-08 01:34:56 +00002550 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2551 Tok.getLocation());
2552
2553 if (Literal.getUDSuffix().empty())
2554 return Owned(Lit);
2555
2556 // We're building a user-defined literal.
2557 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2558 SourceLocation UDSuffixLoc =
2559 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2560
Richard Smith36f5cfe2012-03-09 08:00:36 +00002561 // Make sure we're allowed user-defined literals here.
2562 if (!UDLScope)
2563 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2564
Richard Smithdd66be72012-03-08 01:34:56 +00002565 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2566 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002567 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2568 llvm::makeArrayRef(&Lit, 1),
2569 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002570}
2571
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002572ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2573 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2574 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2575 Context.IntTy, Loc));
2576}
2577
Richard Smithb453ad32012-03-08 08:45:32 +00002578static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2579 QualType Ty, SourceLocation Loc) {
2580 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2581
2582 using llvm::APFloat;
2583 APFloat Val(Format);
2584
2585 APFloat::opStatus result = Literal.GetFloatValue(Val);
2586
2587 // Overflow is always an error, but underflow is only an error if
2588 // we underflowed to zero (APFloat reports denormals as underflow).
2589 if ((result & APFloat::opOverflow) ||
2590 ((result & APFloat::opUnderflow) && Val.isZero())) {
2591 unsigned diagnostic;
2592 SmallString<20> buffer;
2593 if (result & APFloat::opOverflow) {
2594 diagnostic = diag::warn_float_overflow;
2595 APFloat::getLargest(Format).toString(buffer);
2596 } else {
2597 diagnostic = diag::warn_float_underflow;
2598 APFloat::getSmallest(Format).toString(buffer);
2599 }
2600
2601 S.Diag(Loc, diagnostic)
2602 << Ty
2603 << StringRef(buffer.data(), buffer.size());
2604 }
2605
2606 bool isExact = (result == APFloat::opOK);
2607 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2608}
2609
Richard Smith36f5cfe2012-03-09 08:00:36 +00002610ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002611 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002612 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002614 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002615 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 }
Ted Kremenek28396602009-01-13 23:19:12 +00002617
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002618 SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002619 // Add padding so that NumericLiteralParser can overread by one character.
2620 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002622
Reid Spencer5f016e22007-07-11 17:01:13 +00002623 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002624 bool Invalid = false;
2625 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2626 if (Invalid)
2627 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002628
Mike Stump1eb44332009-09-09 15:08:12 +00002629 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 Tok.getLocation(), PP);
2631 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002632 return ExprError();
2633
Richard Smithb453ad32012-03-08 08:45:32 +00002634 if (Literal.hasUDSuffix()) {
2635 // We're building a user-defined literal.
2636 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2637 SourceLocation UDSuffixLoc =
2638 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2639
Richard Smith36f5cfe2012-03-09 08:00:36 +00002640 // Make sure we're allowed user-defined literals here.
2641 if (!UDLScope)
2642 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002643
Richard Smith36f5cfe2012-03-09 08:00:36 +00002644 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002645 if (Literal.isFloatingLiteral()) {
2646 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2647 // long double, the literal is treated as a call of the form
2648 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002649 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002650 } else {
2651 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2652 // unsigned long long, the literal is treated as a call of the form
2653 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002654 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002655 }
2656
Richard Smith36f5cfe2012-03-09 08:00:36 +00002657 DeclarationName OpName =
2658 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2659 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2660 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2661
2662 // Perform literal operator lookup to determine if we're building a raw
2663 // literal or a cooked one.
2664 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2665 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2666 /*AllowRawAndTemplate*/true)) {
2667 case LOLR_Error:
2668 return ExprError();
2669
2670 case LOLR_Cooked: {
2671 Expr *Lit;
2672 if (Literal.isFloatingLiteral()) {
2673 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2674 } else {
2675 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2676 if (Literal.GetIntegerValue(ResultVal))
2677 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2678 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2679 Tok.getLocation());
2680 }
2681 return BuildLiteralOperatorCall(R, OpNameInfo,
2682 llvm::makeArrayRef(&Lit, 1),
2683 Tok.getLocation());
2684 }
2685
2686 case LOLR_Raw: {
2687 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2688 // literal is treated as a call of the form
2689 // operator "" X ("n")
2690 SourceLocation TokLoc = Tok.getLocation();
2691 unsigned Length = Literal.getUDSuffixOffset();
2692 QualType StrTy = Context.getConstantArrayType(
2693 Context.CharTy, llvm::APInt(32, Length + 1),
2694 ArrayType::Normal, 0);
2695 Expr *Lit = StringLiteral::Create(
2696 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2697 /*Pascal*/false, StrTy, &TokLoc, 1);
2698 return BuildLiteralOperatorCall(R, OpNameInfo,
2699 llvm::makeArrayRef(&Lit, 1), TokLoc);
2700 }
2701
2702 case LOLR_Template:
2703 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2704 // template), L is treated as a call fo the form
2705 // operator "" X <'c1', 'c2', ... 'ck'>()
2706 // where n is the source character sequence c1 c2 ... ck.
2707 TemplateArgumentListInfo ExplicitArgs;
2708 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2709 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2710 llvm::APSInt Value(CharBits, CharIsUnsigned);
2711 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2712 Value = ThisTokBegin[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002713 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002714 TemplateArgumentLocInfo ArgInfo;
2715 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2716 }
2717 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2718 Tok.getLocation(), &ExplicitArgs);
2719 }
2720
2721 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002722 }
2723
Chris Lattner5d661452007-08-26 03:42:43 +00002724 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002725
Chris Lattner5d661452007-08-26 03:42:43 +00002726 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002727 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002728 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002729 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002730 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002731 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002732 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002733 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002734
Richard Smithb453ad32012-03-08 08:45:32 +00002735 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002736
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002737 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002738 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002739 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002740 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002741 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002742 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002743 }
2744 }
Chris Lattner5d661452007-08-26 03:42:43 +00002745 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002746 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002747 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002748 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002749
Neil Boothb9449512007-08-29 22:00:19 +00002750 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00002751 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smithebaf0e62011-10-18 20:49:44 +00002752 Diag(Tok.getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002753 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00002754 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002755
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002757 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2758 // The microsoft literal suffix extensions support 128-bit literals, which
2759 // may be wider than [u]intmax_t.
2760 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2761 MaxWidth = 128;
2762 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002763
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 if (Literal.GetIntegerValue(ResultVal)) {
2765 // If this value didn't fit into uintmax_t, warn and force to ull.
2766 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002767 Ty = Context.UnsignedLongLongTy;
2768 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002769 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002770 } else {
2771 // If this value fits into a ULL, try to figure out what else it fits into
2772 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002773
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2775 // be an unsigned int.
2776 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2777
2778 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002779 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002780 if (!Literal.isLong && !Literal.isLongLong) {
2781 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002782 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002783
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 // Does it fit in a unsigned int?
2785 if (ResultVal.isIntN(IntSize)) {
2786 // Does it fit in a signed int?
2787 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002788 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002790 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002791 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002794
Reid Spencer5f016e22007-07-11 17:01:13 +00002795 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002796 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002797 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002798
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 // Does it fit in a unsigned long?
2800 if (ResultVal.isIntN(LongSize)) {
2801 // Does it fit in a signed long?
2802 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002803 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002805 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002806 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002808 }
2809
Stephen Canonb9e05f12012-05-03 22:49:43 +00002810 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002811 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002812 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002813
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 // Does it fit in a unsigned long long?
2815 if (ResultVal.isIntN(LongLongSize)) {
2816 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002817 // To be compatible with MSVC, hex integer literals ending with the
2818 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002819 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002820 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002821 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002823 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002824 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 }
2826 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002827
2828 // If it doesn't fit in unsigned long long, and we're using Microsoft
2829 // extensions, then its a 128-bit integer literal.
2830 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2831 if (Literal.isUnsigned)
2832 Ty = Context.UnsignedInt128Ty;
2833 else
2834 Ty = Context.Int128Ty;
2835 Width = 128;
2836 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002837
Reid Spencer5f016e22007-07-11 17:01:13 +00002838 // If we still couldn't decide a type, we probably have something that
2839 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002840 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002842 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002843 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002845
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002846 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002847 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002849 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002851
Chris Lattner5d661452007-08-26 03:42:43 +00002852 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2853 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002854 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002855 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002856
2857 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002858}
2859
Richard Trieuccd891a2011-09-09 01:45:06 +00002860ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002861 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002862 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002863}
2864
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002865static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2866 SourceLocation Loc,
2867 SourceRange ArgRange) {
2868 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2869 // scalar or vector data type argument..."
2870 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2871 // type (C99 6.2.5p18) or void.
2872 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2873 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2874 << T << ArgRange;
2875 return true;
2876 }
2877
2878 assert((T->isVoidType() || !T->isIncompleteType()) &&
2879 "Scalar types should always be complete");
2880 return false;
2881}
2882
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002883static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2884 SourceLocation Loc,
2885 SourceRange ArgRange,
2886 UnaryExprOrTypeTrait TraitKind) {
2887 // C99 6.5.3.4p1:
2888 if (T->isFunctionType()) {
2889 // alignof(function) is allowed as an extension.
2890 if (TraitKind == UETT_SizeOf)
2891 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2892 return false;
2893 }
2894
2895 // Allow sizeof(void)/alignof(void) as an extension.
2896 if (T->isVoidType()) {
2897 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2898 return false;
2899 }
2900
2901 return true;
2902}
2903
2904static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2905 SourceLocation Loc,
2906 SourceRange ArgRange,
2907 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002908 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2909 // runtime doesn't allow it.
2910 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002911 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2912 << T << (TraitKind == UETT_SizeOf)
2913 << ArgRange;
2914 return true;
2915 }
2916
2917 return false;
2918}
2919
Chandler Carruth9d342d02011-05-26 08:53:10 +00002920/// \brief Check the constrains on expression operands to unary type expression
2921/// and type traits.
2922///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002923/// Completes any types necessary and validates the constraints on the operand
2924/// expression. The logic mostly mirrors the type-based overload, but may modify
2925/// the expression as it completes the type for that expression through template
2926/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002927bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002928 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002929 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002930
2931 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2932 // the result is the size of the referenced type."
2933 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2934 // result shall be the alignment of the referenced type."
2935 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2936 ExprTy = Ref->getPointeeType();
2937
2938 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002939 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2940 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002941
2942 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002943 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2944 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002945 return false;
2946
Richard Trieuccd891a2011-09-09 01:45:06 +00002947 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00002948 diag::err_sizeof_alignof_incomplete_type,
2949 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002950 return true;
2951
2952 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002953 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002954 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2955 ExprTy = Ref->getPointeeType();
2956
Richard Trieuccd891a2011-09-09 01:45:06 +00002957 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2958 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002959 return true;
2960
Nico Webercf739922011-06-15 02:47:03 +00002961 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002962 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002963 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2964 QualType OType = PVD->getOriginalType();
2965 QualType Type = PVD->getType();
2966 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002967 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002968 << Type << OType;
2969 Diag(PVD->getLocation(), diag::note_declared_at);
2970 }
2971 }
2972 }
2973 }
2974
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002975 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002976}
2977
2978/// \brief Check the constraints on operands to unary expression and type
2979/// traits.
2980///
2981/// This will complete any types necessary, and validate the various constraints
2982/// on those operands.
2983///
Reid Spencer5f016e22007-07-11 17:01:13 +00002984/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002985/// C99 6.3.2.1p[2-4] all state:
2986/// Except when it is the operand of the sizeof operator ...
2987///
2988/// C++ [expr.sizeof]p4
2989/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2990/// standard conversions are not applied to the operand of sizeof.
2991///
2992/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002993bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002994 SourceLocation OpLoc,
2995 SourceRange ExprRange,
2996 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002997 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002998 return false;
2999
Sebastian Redl5d484e82009-11-23 17:18:46 +00003000 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3001 // the result is the size of the referenced type."
3002 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3003 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003004 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3005 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003006
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003007 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003008 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003009
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003010 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003011 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003012 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003013 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Richard Trieuccd891a2011-09-09 01:45:06 +00003015 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003016 diag::err_sizeof_alignof_incomplete_type,
3017 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003018 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003019
Richard Trieuccd891a2011-09-09 01:45:06 +00003020 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003021 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003022 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Chris Lattner1efaa952009-04-24 00:30:45 +00003024 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003025}
3026
Chandler Carruth9d342d02011-05-26 08:53:10 +00003027static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003028 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003029
Mike Stump1eb44332009-09-09 15:08:12 +00003030 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003031 if (isa<DeclRefExpr>(E))
3032 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003033
3034 // Cannot know anything else if the expression is dependent.
3035 if (E->isTypeDependent())
3036 return false;
3037
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003038 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003039 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3040 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003041 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003042 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003043
3044 // Alignment of a field access is always okay, so long as it isn't a
3045 // bit-field.
3046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003047 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003048 return false;
3049
Chandler Carruth9d342d02011-05-26 08:53:10 +00003050 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003051}
3052
Chandler Carruth9d342d02011-05-26 08:53:10 +00003053bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003054 E = E->IgnoreParens();
3055
3056 // Cannot know anything else if the expression is dependent.
3057 if (E->isTypeDependent())
3058 return false;
3059
Chandler Carruth9d342d02011-05-26 08:53:10 +00003060 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003061}
3062
Douglas Gregorba498172009-03-13 21:01:28 +00003063/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003064ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003065Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3066 SourceLocation OpLoc,
3067 UnaryExprOrTypeTrait ExprKind,
3068 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003069 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003070 return ExprError();
3071
John McCalla93c9342009-12-07 02:54:59 +00003072 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003073
Douglas Gregorba498172009-03-13 21:01:28 +00003074 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003075 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003076 return ExprError();
3077
3078 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003079 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3080 Context.getSizeType(),
3081 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003082}
3083
3084/// \brief Build a sizeof or alignof expression given an expression
3085/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003086ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003087Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3088 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003089 ExprResult PE = CheckPlaceholderExpr(E);
3090 if (PE.isInvalid())
3091 return ExprError();
3092
3093 E = PE.get();
3094
Douglas Gregorba498172009-03-13 21:01:28 +00003095 // Verify that the operand is valid.
3096 bool isInvalid = false;
3097 if (E->isTypeDependent()) {
3098 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003099 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003100 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003101 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003102 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003103 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003104 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003105 isInvalid = true;
3106 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003107 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003108 }
3109
3110 if (isInvalid)
3111 return ExprError();
3112
Eli Friedman71b8fb52012-01-21 01:01:51 +00003113 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3114 PE = TranformToPotentiallyEvaluated(E);
3115 if (PE.isInvalid()) return ExprError();
3116 E = PE.take();
3117 }
3118
Douglas Gregorba498172009-03-13 21:01:28 +00003119 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003120 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003121 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003122 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003123}
3124
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003125/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3126/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003127/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003128ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003129Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003130 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003131 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003132 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003133 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003134
Richard Trieuccd891a2011-09-09 01:45:06 +00003135 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003136 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003137 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003138 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003139 }
Sebastian Redl05189992008-11-11 17:56:53 +00003140
Douglas Gregorba498172009-03-13 21:01:28 +00003141 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003142 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003143 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003144}
3145
John Wiegley429bb272011-04-08 18:41:53 +00003146static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003147 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003148 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003149 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003150
John McCallf6a16482010-12-04 03:47:34 +00003151 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003152 if (V.get()->getObjectKind() != OK_Ordinary) {
3153 V = S.DefaultLvalueConversion(V.take());
3154 if (V.isInvalid())
3155 return QualType();
3156 }
John McCallf6a16482010-12-04 03:47:34 +00003157
Chris Lattnercc26ed72007-08-26 05:39:26 +00003158 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003159 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003160 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Chris Lattnercc26ed72007-08-26 05:39:26 +00003162 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003163 if (V.get()->getType()->isArithmeticType())
3164 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003165
John McCall2cd11fe2010-10-12 02:09:17 +00003166 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003167 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003168 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003169 if (PR.get() != V.get()) {
3170 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00003171 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003172 }
3173
Chris Lattnercc26ed72007-08-26 05:39:26 +00003174 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003175 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003176 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003177 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003178}
3179
3180
Reid Spencer5f016e22007-07-11 17:01:13 +00003181
John McCall60d7b3a2010-08-24 06:29:42 +00003182ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003183Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003184 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003185 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003186 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003187 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003188 case tok::plusplus: Opc = UO_PostInc; break;
3189 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003190 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003191
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003192 // Since this might is a postfix expression, get rid of ParenListExprs.
3193 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3194 if (Result.isInvalid()) return ExprError();
3195 Input = Result.take();
3196
John McCall9ae2f072010-08-23 23:25:46 +00003197 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003198}
3199
John McCall1503f0d2012-07-31 05:14:30 +00003200/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3201///
3202/// \return true on error
3203static bool checkArithmeticOnObjCPointer(Sema &S,
3204 SourceLocation opLoc,
3205 Expr *op) {
3206 assert(op->getType()->isObjCObjectPointerType());
3207 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3208 return false;
3209
3210 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3211 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3212 << op->getSourceRange();
3213 return true;
3214}
3215
John McCall60d7b3a2010-08-24 06:29:42 +00003216ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003217Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3218 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003219 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003220 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003221 if (Result.isInvalid()) return ExprError();
3222 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003223
John McCall9ae2f072010-08-23 23:25:46 +00003224 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003225
David Blaikie4e4d0842012-03-11 07:00:24 +00003226 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003227 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003228 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003229 Context.DependentTy,
3230 VK_LValue, OK_Ordinary,
3231 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003232 }
3233
David Blaikie4e4d0842012-03-11 07:00:24 +00003234 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003235 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003236 LHSExp->getType()->isEnumeralType() ||
3237 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003238 RHSExp->getType()->isEnumeralType()) &&
3239 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003240 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003241 }
3242
John McCall9ae2f072010-08-23 23:25:46 +00003243 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003244}
3245
John McCall60d7b3a2010-08-24 06:29:42 +00003246ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003247Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003248 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003249 Expr *LHSExp = Base;
3250 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003251
Chris Lattner12d9ff62007-07-16 00:14:47 +00003252 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003253 if (!LHSExp->getType()->getAs<VectorType>()) {
3254 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3255 if (Result.isInvalid())
3256 return ExprError();
3257 LHSExp = Result.take();
3258 }
3259 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3260 if (Result.isInvalid())
3261 return ExprError();
3262 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003263
Chris Lattner12d9ff62007-07-16 00:14:47 +00003264 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003265 ExprValueKind VK = VK_LValue;
3266 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003267
Reid Spencer5f016e22007-07-11 17:01:13 +00003268 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003269 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003270 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003271 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003272 Expr *BaseExpr, *IndexExpr;
3273 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003274 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3275 BaseExpr = LHSExp;
3276 IndexExpr = RHSExp;
3277 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003278 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003279 BaseExpr = LHSExp;
3280 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003281 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003282 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003283 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003284 BaseExpr = LHSExp;
3285 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003286
3287 // Use custom logic if this should be the pseudo-object subscript
3288 // expression.
3289 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3290 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3291
Steve Naroff14108da2009-07-10 23:34:53 +00003292 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003293 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3294 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3295 << ResultType << BaseExpr->getSourceRange();
3296 return ExprError();
3297 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003298 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3299 // Handle the uncommon case of "123[Ptr]".
3300 BaseExpr = RHSExp;
3301 IndexExpr = LHSExp;
3302 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003303 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003304 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003305 // Handle the uncommon case of "123[Ptr]".
3306 BaseExpr = RHSExp;
3307 IndexExpr = LHSExp;
3308 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003309 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3310 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3311 << ResultType << BaseExpr->getSourceRange();
3312 return ExprError();
3313 }
John McCall183700f2009-09-21 23:43:11 +00003314 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003315 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003316 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003317 VK = LHSExp->getValueKind();
3318 if (VK != VK_RValue)
3319 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003320
Chris Lattner12d9ff62007-07-16 00:14:47 +00003321 // FIXME: need to deal with const...
3322 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003323 } else if (LHSTy->isArrayType()) {
3324 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003325 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003326 // wasn't promoted because of the C90 rule that doesn't
3327 // allow promoting non-lvalue arrays. Warn, then
3328 // force the promotion here.
3329 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3330 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003331 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3332 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003333 LHSTy = LHSExp->getType();
3334
3335 BaseExpr = LHSExp;
3336 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003337 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003338 } else if (RHSTy->isArrayType()) {
3339 // Same as previous, except for 123[f().a] case
3340 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3341 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003342 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3343 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003344 RHSTy = RHSExp->getType();
3345
3346 BaseExpr = RHSExp;
3347 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003348 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003349 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003350 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3351 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003352 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003353 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003354 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003355 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3356 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003357
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003358 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003359 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3360 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003361 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3362
Douglas Gregore7450f52009-03-24 19:52:54 +00003363 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003364 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3365 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003366 // incomplete types are not object types.
3367 if (ResultType->isFunctionType()) {
3368 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3369 << ResultType << BaseExpr->getSourceRange();
3370 return ExprError();
3371 }
Mike Stump1eb44332009-09-09 15:08:12 +00003372
David Blaikie4e4d0842012-03-11 07:00:24 +00003373 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003374 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003375 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3376 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003377
3378 // C forbids expressions of unqualified void type from being l-values.
3379 // See IsCForbiddenLValueType.
3380 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003381 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003382 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003383 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003384 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003385
John McCall09431682010-11-18 19:01:18 +00003386 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003387 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003388
Mike Stumpeed9cac2009-02-19 03:04:26 +00003389 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003390 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003391}
3392
John McCall60d7b3a2010-08-24 06:29:42 +00003393ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003394 FunctionDecl *FD,
3395 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003396 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003397 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003398 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003399 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003400 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003401 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003402 return ExprError();
3403 }
3404
3405 if (Param->hasUninstantiatedDefaultArg()) {
3406 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003407
Richard Smithadb1d4c2012-07-22 23:45:10 +00003408 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3409 Param);
3410
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003411 // Instantiate the expression.
3412 MultiLevelTemplateArgumentList ArgList
3413 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003414
Nico Weber08e41a62010-11-29 18:19:25 +00003415 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003416 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003417 InstantiatingTemplate Inst(*this, CallLoc, Param,
3418 ArrayRef<TemplateArgument>(Innermost.first,
3419 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003420 if (Inst)
3421 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003422
Nico Weber08e41a62010-11-29 18:19:25 +00003423 ExprResult Result;
3424 {
3425 // C++ [dcl.fct.default]p5:
3426 // The names in the [default argument] expression are bound, and
3427 // the semantic constraints are checked, at the point where the
3428 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003429 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003430 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003431 Result = SubstExpr(UninstExpr, ArgList);
3432 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003433 if (Result.isInvalid())
3434 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003436 // Check the expression as an initializer for the parameter.
3437 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003438 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003439 InitializationKind Kind
3440 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003441 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003442 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003443
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003444 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3445 Result = InitSeq.Perform(*this, Entity, Kind,
3446 MultiExprArg(*this, &ResultE, 1));
3447 if (Result.isInvalid())
3448 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003449
David Blaikiec1c07252012-04-30 18:21:31 +00003450 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003451 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003452 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003453 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003454 }
3455
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003456 // If the default expression creates temporaries, we need to
3457 // push them to the current stack of expression temporaries so they'll
3458 // be properly destroyed.
3459 // FIXME: We should really be rebuilding the default argument with new
3460 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003461 // We don't need to do that with block decls, though, because
3462 // blocks in default argument expression can never capture anything.
3463 if (isa<ExprWithCleanups>(Param->getInit())) {
3464 // Set the "needs cleanups" bit regardless of whether there are
3465 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003466 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003467
3468 // Append all the objects to the cleanup list. Right now, this
3469 // should always be a no-op, because blocks in default argument
3470 // expressions should never be able to capture anything.
3471 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3472 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003473 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003474
3475 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003476 // Just mark all of the declarations in this potentially-evaluated expression
3477 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003478 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3479 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003480 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003481}
3482
Richard Smith831421f2012-06-25 20:30:08 +00003483
3484Sema::VariadicCallType
3485Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3486 Expr *Fn) {
3487 if (Proto && Proto->isVariadic()) {
3488 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3489 return VariadicConstructor;
3490 else if (Fn && Fn->getType()->isBlockPointerType())
3491 return VariadicBlock;
3492 else if (FDecl) {
3493 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3494 if (Method->isInstance())
3495 return VariadicMethod;
3496 }
3497 return VariadicFunction;
3498 }
3499 return VariadicDoesNotApply;
3500}
3501
Douglas Gregor88a35142008-12-22 05:46:06 +00003502/// ConvertArgumentsForCall - Converts the arguments specified in
3503/// Args/NumArgs to the parameter types of the function FDecl with
3504/// function prototype Proto. Call is the call expression itself, and
3505/// Fn is the function expression. For a C++ member function, this
3506/// routine does not attempt to convert the object argument. Returns
3507/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003508bool
3509Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003510 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003511 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003512 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003513 SourceLocation RParenLoc,
3514 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003515 // Bail out early if calling a builtin with custom typechecking.
3516 // We don't need to do this in the
3517 if (FDecl)
3518 if (unsigned ID = FDecl->getBuiltinID())
3519 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3520 return false;
3521
Mike Stumpeed9cac2009-02-19 03:04:26 +00003522 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003523 // assignment, to the types of the corresponding parameter, ...
3524 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003525 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003526 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003527 unsigned FnKind = Fn->getType()->isBlockPointerType()
3528 ? 1 /* block */
3529 : (IsExecConfig ? 3 /* kernel function (exec config) */
3530 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003531
Douglas Gregor88a35142008-12-22 05:46:06 +00003532 // If too few arguments are available (and we don't have default
3533 // arguments for the remaining parameters), don't make the call.
3534 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003535 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003536 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3537 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3538 ? diag::err_typecheck_call_too_few_args_one
3539 : diag::err_typecheck_call_too_few_args_at_least_one)
3540 << FnKind
3541 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3542 else
3543 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3544 ? diag::err_typecheck_call_too_few_args
3545 : diag::err_typecheck_call_too_few_args_at_least)
3546 << FnKind
3547 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003548
3549 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003550 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003551 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3552 << FDecl;
3553
3554 return true;
3555 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003556 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003557 }
3558
3559 // If too many are passed and not variadic, error on the extras and drop
3560 // them.
3561 if (NumArgs > NumArgsInProto) {
3562 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003563 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3564 Diag(Args[NumArgsInProto]->getLocStart(),
3565 MinArgs == NumArgsInProto
3566 ? diag::err_typecheck_call_too_many_args_one
3567 : diag::err_typecheck_call_too_many_args_at_most_one)
3568 << FnKind
3569 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3570 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3571 Args[NumArgs-1]->getLocEnd());
3572 else
3573 Diag(Args[NumArgsInProto]->getLocStart(),
3574 MinArgs == NumArgsInProto
3575 ? diag::err_typecheck_call_too_many_args
3576 : diag::err_typecheck_call_too_many_args_at_most)
3577 << FnKind
3578 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3579 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3580 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003581
3582 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003583 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003584 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3585 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003586
Douglas Gregor88a35142008-12-22 05:46:06 +00003587 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003588 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003589 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003590 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003591 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003592 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003593 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3594
Daniel Dunbar96a00142012-03-09 18:35:03 +00003595 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003596 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003597 if (Invalid)
3598 return true;
3599 unsigned TotalNumArgs = AllArgs.size();
3600 for (unsigned i = 0; i < TotalNumArgs; ++i)
3601 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003602
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003603 return false;
3604}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003605
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003606bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3607 FunctionDecl *FDecl,
3608 const FunctionProtoType *Proto,
3609 unsigned FirstProtoArg,
3610 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003611 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003612 VariadicCallType CallType,
3613 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003614 unsigned NumArgsInProto = Proto->getNumArgs();
3615 unsigned NumArgsToCheck = NumArgs;
3616 bool Invalid = false;
3617 if (NumArgs != NumArgsInProto)
3618 // Use default arguments for missing arguments
3619 NumArgsToCheck = NumArgsInProto;
3620 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003621 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003622 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003623 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003624
Douglas Gregor88a35142008-12-22 05:46:06 +00003625 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003626 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003627 if (ArgIx < NumArgs) {
3628 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003629
Daniel Dunbar96a00142012-03-09 18:35:03 +00003630 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003631 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003632 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003633 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003634
Douglas Gregora188ff22009-12-22 16:09:06 +00003635 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003636 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003637 if (FDecl && i < FDecl->getNumParams())
3638 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003639
John McCall5acb0c92011-10-17 18:40:02 +00003640 // Strip the unbridged-cast placeholder expression off, if applicable.
3641 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3642 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3643 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3644 Arg = stripARCUnbridgedCast(Arg);
3645
Douglas Gregora188ff22009-12-22 16:09:06 +00003646 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003647 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003648 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3649 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003650 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003651 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003652 Owned(Arg),
3653 /*TopLevelOfInitList=*/false,
3654 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003655 if (ArgE.isInvalid())
3656 return true;
3657
3658 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003659 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003660 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003661
John McCall60d7b3a2010-08-24 06:29:42 +00003662 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003663 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003664 if (ArgExpr.isInvalid())
3665 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003666
Anders Carlsson56c5e332009-08-25 03:49:14 +00003667 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003668 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003669
3670 // Check for array bounds violations for each argument to the call. This
3671 // check only triggers warnings when the argument isn't a more complex Expr
3672 // with its own checking, such as a BinaryOperator.
3673 CheckArrayAccess(Arg);
3674
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003675 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3676 CheckStaticArrayArgument(CallLoc, Param, Arg);
3677
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003678 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003679 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003680
Douglas Gregor88a35142008-12-22 05:46:06 +00003681 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003682 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003683 // Assume that extern "C" functions with variadic arguments that
3684 // return __unknown_anytype aren't *really* variadic.
3685 if (Proto->getResultType() == Context.UnknownAnyTy &&
3686 FDecl && FDecl->isExternC()) {
3687 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3688 ExprResult arg;
3689 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3690 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3691 else
3692 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3693 Invalid |= arg.isInvalid();
3694 AllArgs.push_back(arg.take());
3695 }
3696
3697 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3698 } else {
3699 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003700 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3701 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003702 Invalid |= Arg.isInvalid();
3703 AllArgs.push_back(Arg.take());
3704 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003705 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003706
3707 // Check for array bounds violations.
3708 for (unsigned i = ArgIx; i != NumArgs; ++i)
3709 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003710 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003711 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003712}
3713
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003714static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3715 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3716 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3717 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3718 << ATL->getLocalSourceRange();
3719}
3720
3721/// CheckStaticArrayArgument - If the given argument corresponds to a static
3722/// array parameter, check that it is non-null, and that if it is formed by
3723/// array-to-pointer decay, the underlying array is sufficiently large.
3724///
3725/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3726/// array type derivation, then for each call to the function, the value of the
3727/// corresponding actual argument shall provide access to the first element of
3728/// an array with at least as many elements as specified by the size expression.
3729void
3730Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3731 ParmVarDecl *Param,
3732 const Expr *ArgExpr) {
3733 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003734 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003735 return;
3736
3737 QualType OrigTy = Param->getOriginalType();
3738
3739 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3740 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3741 return;
3742
3743 if (ArgExpr->isNullPointerConstant(Context,
3744 Expr::NPC_NeverValueDependent)) {
3745 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3746 DiagnoseCalleeStaticArrayParam(*this, Param);
3747 return;
3748 }
3749
3750 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3751 if (!CAT)
3752 return;
3753
3754 const ConstantArrayType *ArgCAT =
3755 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3756 if (!ArgCAT)
3757 return;
3758
3759 if (ArgCAT->getSize().ult(CAT->getSize())) {
3760 Diag(CallLoc, diag::warn_static_array_too_small)
3761 << ArgExpr->getSourceRange()
3762 << (unsigned) ArgCAT->getSize().getZExtValue()
3763 << (unsigned) CAT->getSize().getZExtValue();
3764 DiagnoseCalleeStaticArrayParam(*this, Param);
3765 }
3766}
3767
John McCall755d8492011-04-12 00:42:48 +00003768/// Given a function expression of unknown-any type, try to rebuild it
3769/// to have a function type.
3770static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3771
Steve Narofff69936d2007-09-16 03:34:24 +00003772/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003773/// This provides the location of the left/right parens and a list of comma
3774/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003775ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003776Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003777 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003778 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003779 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003780
3781 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003782 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003783 if (Result.isInvalid()) return ExprError();
3784 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Richard Trieuccd891a2011-09-09 01:45:06 +00003786 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003787
David Blaikie4e4d0842012-03-11 07:00:24 +00003788 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003789 // If this is a pseudo-destructor expression, build the call immediately.
3790 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3791 if (NumArgs > 0) {
3792 // Pseudo-destructor calls should not have any arguments.
3793 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003794 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003795 SourceRange(Args[0]->getLocStart(),
3796 Args[NumArgs-1]->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003797 }
Mike Stump1eb44332009-09-09 15:08:12 +00003798
Douglas Gregora71d8192009-09-04 17:36:40 +00003799 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003800 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003801 }
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Douglas Gregor17330012009-02-04 15:01:18 +00003803 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003804 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003805 // FIXME: Will need to cache the results of name lookup (including ADL) in
3806 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003807 bool Dependent = false;
3808 if (Fn->isTypeDependent())
3809 Dependent = true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003810 else if (Expr::hasAnyTypeDependentArguments(
3811 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregor17330012009-02-04 15:01:18 +00003812 Dependent = true;
3813
Peter Collingbournee08ce652011-02-09 21:07:24 +00003814 if (Dependent) {
3815 if (ExecConfig) {
3816 return Owned(new (Context) CUDAKernelCallExpr(
3817 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3818 Context.DependentTy, VK_RValue, RParenLoc));
3819 } else {
3820 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3821 Context.DependentTy, VK_RValue,
3822 RParenLoc));
3823 }
3824 }
Douglas Gregor17330012009-02-04 15:01:18 +00003825
3826 // Determine whether this is a call to an object (C++ [over.call.object]).
3827 if (Fn->getType()->isRecordType())
3828 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003829 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003830
John McCall755d8492011-04-12 00:42:48 +00003831 if (Fn->getType() == Context.UnknownAnyTy) {
3832 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3833 if (result.isInvalid()) return ExprError();
3834 Fn = result.take();
3835 }
3836
John McCall864c0412011-04-26 20:42:42 +00003837 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003838 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003839 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003840 }
John McCall864c0412011-04-26 20:42:42 +00003841 }
John McCall129e2df2009-11-30 22:42:35 +00003842
John McCall864c0412011-04-26 20:42:42 +00003843 // Check for overloaded calls. This can happen even in C due to extensions.
3844 if (Fn->getType() == Context.OverloadTy) {
3845 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3846
Douglas Gregoree697e62011-10-13 18:10:35 +00003847 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003848 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003849 OverloadExpr *ovl = find.Expression;
3850 if (isa<UnresolvedLookupExpr>(ovl)) {
3851 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3852 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3853 RParenLoc, ExecConfig);
3854 } else {
John McCallaa81e162009-12-01 22:10:20 +00003855 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003856 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003857 }
3858 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003859 }
3860
Douglas Gregorfa047642009-02-04 00:32:51 +00003861 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003862 if (Fn->getType() == Context.UnknownAnyTy) {
3863 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3864 if (result.isInvalid()) return ExprError();
3865 Fn = result.take();
3866 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003867
Eli Friedmanefa42f72009-12-26 03:35:45 +00003868 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003869
John McCall3b4294e2009-12-16 12:17:52 +00003870 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003871 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3872 if (UnOp->getOpcode() == UO_AddrOf)
3873 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3874
John McCall3b4294e2009-12-16 12:17:52 +00003875 if (isa<DeclRefExpr>(NakedFn))
3876 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003877 else if (isa<MemberExpr>(NakedFn))
3878 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003879
Peter Collingbournee08ce652011-02-09 21:07:24 +00003880 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003881 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003882}
3883
3884ExprResult
3885Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003886 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003887 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3888 if (!ConfigDecl)
3889 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3890 << "cudaConfigureCall");
3891 QualType ConfigQTy = ConfigDecl->getType();
3892
3893 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003894 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003895 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003896
Peter Collingbourne1f240762011-10-02 23:49:29 +00003897 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3898 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003899}
3900
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003901/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3902///
3903/// __builtin_astype( value, dst type )
3904///
Richard Trieuccd891a2011-09-09 01:45:06 +00003905ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003906 SourceLocation BuiltinLoc,
3907 SourceLocation RParenLoc) {
3908 ExprValueKind VK = VK_RValue;
3909 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003910 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3911 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003912 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3913 return ExprError(Diag(BuiltinLoc,
3914 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003915 << DstTy
3916 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003917 << E->getSourceRange());
3918 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003919 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003920}
3921
John McCall3b4294e2009-12-16 12:17:52 +00003922/// BuildResolvedCallExpr - Build a call to a resolved expression,
3923/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003924/// unary-convert to an expression of function-pointer or
3925/// block-pointer type.
3926///
3927/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003928ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003929Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3930 SourceLocation LParenLoc,
3931 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003932 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003933 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003934 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3935
Chris Lattner04421082008-04-08 04:40:51 +00003936 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003937 ExprResult Result = UsualUnaryConversions(Fn);
3938 if (Result.isInvalid())
3939 return ExprError();
3940 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003941
Chris Lattner925e60d2007-12-28 05:29:59 +00003942 // Make the call expr early, before semantic checks. This guarantees cleanup
3943 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003944 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00003945 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00003946 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3947 cast<CallExpr>(Config),
3948 Args, NumArgs,
3949 Context.BoolTy,
3950 VK_RValue,
3951 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00003952 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00003953 TheCall = new (Context) CallExpr(Context, Fn,
3954 Args, NumArgs,
3955 Context.BoolTy,
3956 VK_RValue,
3957 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003958
John McCall8e10f3b2011-02-26 05:39:39 +00003959 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3960
3961 // Bail out early if calling a builtin with custom typechecking.
3962 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3963 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3964
John McCall1de4d4e2011-04-07 08:22:57 +00003965 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003966 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003967 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003968 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3969 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003970 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003971 if (FuncT == 0)
3972 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3973 << Fn->getType() << Fn->getSourceRange());
3974 } else if (const BlockPointerType *BPT =
3975 Fn->getType()->getAs<BlockPointerType>()) {
3976 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3977 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003978 // Handle calls to expressions of unknown-any type.
3979 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003980 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003981 if (rewrite.isInvalid()) return ExprError();
3982 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003983 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003984 goto retry;
3985 }
3986
Sebastian Redl0eb23302009-01-19 00:08:26 +00003987 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3988 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003989 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003990
David Blaikie4e4d0842012-03-11 07:00:24 +00003991 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003992 if (Config) {
3993 // CUDA: Kernel calls must be to global functions
3994 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3995 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3996 << FDecl->getName() << Fn->getSourceRange());
3997
3998 // CUDA: Kernel function must have 'void' return type
3999 if (!FuncT->getResultType()->isVoidType())
4000 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4001 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004002 } else {
4003 // CUDA: Calls to global functions must be configured
4004 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4005 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4006 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004007 }
4008 }
4009
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004010 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004011 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004012 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004013 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004014 return ExprError();
4015
Chris Lattner925e60d2007-12-28 05:29:59 +00004016 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004017 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004018 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004019
Richard Smith831421f2012-06-25 20:30:08 +00004020 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4021 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004022 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004023 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004024 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004025 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004026 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004027
Douglas Gregor74734d52009-04-02 15:37:10 +00004028 if (FDecl) {
4029 // Check if we have too few/too many template arguments, based
4030 // on our knowledge of the function definition.
4031 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004032 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004033 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004034 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004035 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4036 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004037 }
Douglas Gregor46542412010-10-25 20:39:23 +00004038
4039 // If the function we're calling isn't a function prototype, but we have
4040 // a function prototype from a prior declaratiom, use that prototype.
4041 if (!FDecl->hasPrototype())
4042 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004043 }
4044
Steve Naroffb291ab62007-08-28 23:30:39 +00004045 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004046 for (unsigned i = 0; i != NumArgs; i++) {
4047 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004048
4049 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004050 InitializedEntity Entity
4051 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004052 Proto->getArgType(i),
4053 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004054 ExprResult ArgE = PerformCopyInitialization(Entity,
4055 SourceLocation(),
4056 Owned(Arg));
4057 if (ArgE.isInvalid())
4058 return true;
4059
4060 Arg = ArgE.takeAs<Expr>();
4061
4062 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004063 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4064
4065 if (ArgE.isInvalid())
4066 return true;
4067
4068 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004069 }
4070
Daniel Dunbar96a00142012-03-09 18:35:03 +00004071 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004072 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004073 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004074 return ExprError();
4075
Chris Lattner925e60d2007-12-28 05:29:59 +00004076 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004077 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004078 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004079
Douglas Gregor88a35142008-12-22 05:46:06 +00004080 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4081 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004082 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4083 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004084
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004085 // Check for sentinels
4086 if (NDecl)
4087 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004088
Chris Lattner59907c42007-08-10 20:18:51 +00004089 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004090 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004091 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004092 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004093
John McCall8e10f3b2011-02-26 05:39:39 +00004094 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004095 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004096 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004097 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004098 return ExprError();
4099 }
Chris Lattner59907c42007-08-10 20:18:51 +00004100
John McCall9ae2f072010-08-23 23:25:46 +00004101 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004102}
4103
John McCall60d7b3a2010-08-24 06:29:42 +00004104ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004105Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004106 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004107 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004108 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004109 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004110
4111 TypeSourceInfo *TInfo;
4112 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4113 if (!TInfo)
4114 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4115
John McCall9ae2f072010-08-23 23:25:46 +00004116 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004117}
4118
John McCall60d7b3a2010-08-24 06:29:42 +00004119ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004120Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004121 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004122 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004123
Eli Friedman6223c222008-05-20 05:22:08 +00004124 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004125 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004126 diag::err_illegal_decl_array_incomplete_type,
4127 SourceRange(LParenLoc,
4128 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004129 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004130 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004131 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004132 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004133 } else if (!literalType->isDependentType() &&
4134 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004135 diag::err_typecheck_decl_incomplete_type,
4136 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004137 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004138
Douglas Gregor99a2e602009-12-16 01:38:02 +00004139 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004140 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004141 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004142 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004143 SourceRange(LParenLoc, RParenLoc),
4144 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004145 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004146 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00004147 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004148 &literalType);
4149 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004150 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004151 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004152
Chris Lattner371f2582008-12-04 23:50:19 +00004153 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004154 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004155 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004156 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004157 }
Eli Friedman08544622009-12-22 02:35:53 +00004158
John McCallf89e55a2010-11-18 06:31:45 +00004159 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004160 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004161
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004162 return MaybeBindToTemporary(
4163 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004164 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004165}
4166
John McCall60d7b3a2010-08-24 06:29:42 +00004167ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004168Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004169 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004170 unsigned NumInit = InitArgList.size();
4171 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004172
John McCall3c3b7f92011-10-25 17:37:35 +00004173 // Immediately handle non-overload placeholders. Overloads can be
4174 // resolved contextually, but everything else here can't.
4175 for (unsigned I = 0; I != NumInit; ++I) {
John McCall32509f12011-11-15 01:35:18 +00004176 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00004177 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4178
4179 // Ignore failures; dropping the entire initializer list because
4180 // of one failure would be terrible for indexing/etc.
4181 if (result.isInvalid()) continue;
4182
4183 InitList[I] = result.take();
4184 }
4185 }
4186
Steve Naroff08d92e42007-09-15 18:49:24 +00004187 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004188 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004189
Ted Kremenek709210f2010-04-13 23:39:13 +00004190 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4191 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004192 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004193 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004194}
4195
John McCalldc05b112011-09-10 01:16:55 +00004196/// Do an explicit extend of the given block pointer if we're in ARC.
4197static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4198 assert(E.get()->getType()->isBlockPointerType());
4199 assert(E.get()->isRValue());
4200
4201 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004202 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004203
4204 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004205 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004206 /*base path*/ 0, VK_RValue);
4207 S.ExprNeedsCleanups = true;
4208}
4209
4210/// Prepare a conversion of the given expression to an ObjC object
4211/// pointer type.
4212CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4213 QualType type = E.get()->getType();
4214 if (type->isObjCObjectPointerType()) {
4215 return CK_BitCast;
4216 } else if (type->isBlockPointerType()) {
4217 maybeExtendBlockObject(*this, E);
4218 return CK_BlockPointerToObjCPointerCast;
4219 } else {
4220 assert(type->isPointerType());
4221 return CK_CPointerToObjCPointerCast;
4222 }
4223}
4224
John McCallf3ea8cf2010-11-14 08:17:51 +00004225/// Prepares for a scalar cast, performing all the necessary stages
4226/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004227CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004228 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4229 // Also, callers should have filtered out the invalid cases with
4230 // pointers. Everything else should be possible.
4231
John Wiegley429bb272011-04-08 18:41:53 +00004232 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004233 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004234 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004235
John McCall1d9b3b22011-09-09 05:25:32 +00004236 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004237 case Type::STK_MemberPointer:
4238 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004239
John McCall1d9b3b22011-09-09 05:25:32 +00004240 case Type::STK_CPointer:
4241 case Type::STK_BlockPointer:
4242 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004243 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004244 case Type::STK_CPointer:
4245 return CK_BitCast;
4246 case Type::STK_BlockPointer:
4247 return (SrcKind == Type::STK_BlockPointer
4248 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4249 case Type::STK_ObjCObjectPointer:
4250 if (SrcKind == Type::STK_ObjCObjectPointer)
4251 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004252 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004253 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004254 maybeExtendBlockObject(*this, Src);
4255 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004256 case Type::STK_Bool:
4257 return CK_PointerToBoolean;
4258 case Type::STK_Integral:
4259 return CK_PointerToIntegral;
4260 case Type::STK_Floating:
4261 case Type::STK_FloatingComplex:
4262 case Type::STK_IntegralComplex:
4263 case Type::STK_MemberPointer:
4264 llvm_unreachable("illegal cast from pointer");
4265 }
David Blaikie7530c032012-01-17 06:56:22 +00004266 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004267
John McCalldaa8e4e2010-11-15 09:13:47 +00004268 case Type::STK_Bool: // casting from bool is like casting from an integer
4269 case Type::STK_Integral:
4270 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004271 case Type::STK_CPointer:
4272 case Type::STK_ObjCObjectPointer:
4273 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004274 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004275 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004276 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004277 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004278 case Type::STK_Bool:
4279 return CK_IntegralToBoolean;
4280 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004281 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004282 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004283 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004284 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004285 Src = ImpCastExprToType(Src.take(),
4286 DestTy->castAs<ComplexType>()->getElementType(),
4287 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004288 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004289 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004290 Src = ImpCastExprToType(Src.take(),
4291 DestTy->castAs<ComplexType>()->getElementType(),
4292 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004293 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004294 case Type::STK_MemberPointer:
4295 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004296 }
David Blaikie7530c032012-01-17 06:56:22 +00004297 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004298
John McCalldaa8e4e2010-11-15 09:13:47 +00004299 case Type::STK_Floating:
4300 switch (DestTy->getScalarTypeKind()) {
4301 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004302 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004303 case Type::STK_Bool:
4304 return CK_FloatingToBoolean;
4305 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004306 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004307 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004308 Src = ImpCastExprToType(Src.take(),
4309 DestTy->castAs<ComplexType>()->getElementType(),
4310 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004311 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004312 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004313 Src = ImpCastExprToType(Src.take(),
4314 DestTy->castAs<ComplexType>()->getElementType(),
4315 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004316 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004317 case Type::STK_CPointer:
4318 case Type::STK_ObjCObjectPointer:
4319 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004320 llvm_unreachable("valid float->pointer cast?");
4321 case Type::STK_MemberPointer:
4322 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004323 }
David Blaikie7530c032012-01-17 06:56:22 +00004324 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004325
John McCalldaa8e4e2010-11-15 09:13:47 +00004326 case Type::STK_FloatingComplex:
4327 switch (DestTy->getScalarTypeKind()) {
4328 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004329 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004330 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004331 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004332 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004333 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4334 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004335 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004336 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004337 return CK_FloatingCast;
4338 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004339 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004340 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004341 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004342 Src = ImpCastExprToType(Src.take(),
4343 SrcTy->castAs<ComplexType>()->getElementType(),
4344 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004345 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004346 case Type::STK_CPointer:
4347 case Type::STK_ObjCObjectPointer:
4348 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004349 llvm_unreachable("valid complex float->pointer cast?");
4350 case Type::STK_MemberPointer:
4351 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004352 }
David Blaikie7530c032012-01-17 06:56:22 +00004353 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004354
John McCalldaa8e4e2010-11-15 09:13:47 +00004355 case Type::STK_IntegralComplex:
4356 switch (DestTy->getScalarTypeKind()) {
4357 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004358 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004359 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004360 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004361 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004362 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4363 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004364 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004365 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004366 return CK_IntegralCast;
4367 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004368 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004369 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004370 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004371 Src = ImpCastExprToType(Src.take(),
4372 SrcTy->castAs<ComplexType>()->getElementType(),
4373 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004374 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004375 case Type::STK_CPointer:
4376 case Type::STK_ObjCObjectPointer:
4377 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004378 llvm_unreachable("valid complex int->pointer cast?");
4379 case Type::STK_MemberPointer:
4380 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004381 }
David Blaikie7530c032012-01-17 06:56:22 +00004382 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004383 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004384
John McCallf3ea8cf2010-11-14 08:17:51 +00004385 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004386}
4387
Anders Carlssonc3516322009-10-16 02:48:28 +00004388bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004389 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004390 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004391
Anders Carlssona64db8f2007-11-27 05:51:55 +00004392 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004393 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004394 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004395 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004396 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004397 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004398 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004399 } else
4400 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004401 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004402 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004403
John McCall2de56d12010-08-25 11:45:40 +00004404 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004405 return false;
4406}
4407
John Wiegley429bb272011-04-08 18:41:53 +00004408ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4409 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004410 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004411
Anders Carlsson16a89042009-10-16 05:23:41 +00004412 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004413
Nate Begeman9b10da62009-06-27 22:05:55 +00004414 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4415 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004416 // In OpenCL, casts between vectors of different types are not allowed.
4417 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004418 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004419 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004420 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004421 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004422 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004423 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004424 return ExprError();
4425 }
John McCall2de56d12010-08-25 11:45:40 +00004426 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004427 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004428 }
4429
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004430 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004431 // conversion will take place first from scalar to elt type, and then
4432 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004433 if (SrcTy->isPointerType())
4434 return Diag(R.getBegin(),
4435 diag::err_invalid_conversion_between_vector_and_scalar)
4436 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004437
4438 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004439 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004440 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004441 if (CastExprRes.isInvalid())
4442 return ExprError();
4443 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004444
John McCall2de56d12010-08-25 11:45:40 +00004445 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004446 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004447}
4448
John McCall60d7b3a2010-08-24 06:29:42 +00004449ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004450Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4451 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004452 SourceLocation RParenLoc, Expr *CastExpr) {
4453 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004454 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004455
Richard Trieuccd891a2011-09-09 01:45:06 +00004456 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004457 if (D.isInvalidType())
4458 return ExprError();
4459
David Blaikie4e4d0842012-03-11 07:00:24 +00004460 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004461 // Check that there are no default arguments (C++ only).
4462 CheckExtraCXXDefaultArguments(D);
4463 }
4464
John McCalle82247a2011-10-01 05:17:03 +00004465 checkUnusedDeclAttributes(D);
4466
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004467 QualType castType = castTInfo->getType();
4468 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004469
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004470 bool isVectorLiteral = false;
4471
4472 // Check for an altivec or OpenCL literal,
4473 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004474 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4475 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004476 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004477 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004478 if (PLE && PLE->getNumExprs() == 0) {
4479 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4480 return ExprError();
4481 }
4482 if (PE || PLE->getNumExprs() == 1) {
4483 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4484 if (!E->getType()->isVectorType())
4485 isVectorLiteral = true;
4486 }
4487 else
4488 isVectorLiteral = true;
4489 }
4490
4491 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4492 // then handle it as such.
4493 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004494 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004495
Nate Begeman2ef13e52009-08-10 23:49:36 +00004496 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004497 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4498 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004499 if (isa<ParenListExpr>(CastExpr)) {
4500 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004501 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004502 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004503 }
John McCallb042fdf2010-01-15 18:56:44 +00004504
Richard Trieuccd891a2011-09-09 01:45:06 +00004505 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004506}
4507
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004508ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4509 SourceLocation RParenLoc, Expr *E,
4510 TypeSourceInfo *TInfo) {
4511 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4512 "Expected paren or paren list expression");
4513
4514 Expr **exprs;
4515 unsigned numExprs;
4516 Expr *subExpr;
4517 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4518 exprs = PE->getExprs();
4519 numExprs = PE->getNumExprs();
4520 } else {
4521 subExpr = cast<ParenExpr>(E)->getSubExpr();
4522 exprs = &subExpr;
4523 numExprs = 1;
4524 }
4525
4526 QualType Ty = TInfo->getType();
4527 assert(Ty->isVectorType() && "Expected vector type");
4528
Chris Lattner5f9e2722011-07-23 10:55:15 +00004529 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004530 const VectorType *VTy = Ty->getAs<VectorType>();
4531 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4532
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004533 // '(...)' form of vector initialization in AltiVec: the number of
4534 // initializers must be one or must match the size of the vector.
4535 // If a single value is specified in the initializer then it will be
4536 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004537 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004538 // The number of initializers must be one or must match the size of the
4539 // vector. If a single value is specified in the initializer then it will
4540 // be replicated to all the components of the vector
4541 if (numExprs == 1) {
4542 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004543 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4544 if (Literal.isInvalid())
4545 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004546 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004547 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004548 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4549 }
4550 else if (numExprs < numElems) {
4551 Diag(E->getExprLoc(),
4552 diag::err_incorrect_number_of_vector_initializers);
4553 return ExprError();
4554 }
4555 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004556 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004557 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004558 else {
4559 // For OpenCL, when the number of initializers is a single value,
4560 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004561 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004562 VTy->getVectorKind() == VectorType::GenericVector &&
4563 numExprs == 1) {
4564 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004565 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4566 if (Literal.isInvalid())
4567 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004568 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004569 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004570 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4571 }
4572
Benjamin Kramer14c59822012-02-14 12:06:21 +00004573 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004574 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004575 // FIXME: This means that pretty-printing the final AST will produce curly
4576 // braces instead of the original commas.
4577 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4578 &initExprs[0],
4579 initExprs.size(), RParenLoc);
4580 initE->setType(Ty);
4581 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4582}
4583
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004584/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4585/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004586ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004587Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4588 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004589 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004590 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004591
John McCall60d7b3a2010-08-24 06:29:42 +00004592 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Nate Begeman2ef13e52009-08-10 23:49:36 +00004594 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004595 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4596 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004597
John McCall9ae2f072010-08-23 23:25:46 +00004598 if (Result.isInvalid()) return ExprError();
4599
4600 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004601}
4602
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004603ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4604 SourceLocation R,
4605 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004606 unsigned nexprs = Val.size();
4607 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004608 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004609 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004610 return Owned(expr);
4611}
4612
Chandler Carruth82214a82011-02-18 23:54:50 +00004613/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004614/// constant and the other is not a pointer. Returns true if a diagnostic is
4615/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004616bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004617 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004618 Expr *NullExpr = LHSExpr;
4619 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004620 Expr::NullPointerConstantKind NullKind =
4621 NullExpr->isNullPointerConstant(Context,
4622 Expr::NPC_ValueDependentIsNotNull);
4623
4624 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004625 NullExpr = RHSExpr;
4626 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004627 NullKind =
4628 NullExpr->isNullPointerConstant(Context,
4629 Expr::NPC_ValueDependentIsNotNull);
4630 }
4631
4632 if (NullKind == Expr::NPCK_NotNull)
4633 return false;
4634
David Blaikie50800fc2012-08-08 17:33:31 +00004635 if (NullKind == Expr::NPCK_ZeroExpression)
4636 return false;
4637
4638 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004639 // In this case, check to make sure that we got here from a "NULL"
4640 // string in the source code.
4641 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004642 SourceLocation loc = NullExpr->getExprLoc();
4643 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004644 return false;
4645 }
4646
4647 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4648 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4649 << NonPointerExpr->getType() << DiagType
4650 << NonPointerExpr->getSourceRange();
4651 return true;
4652}
4653
Richard Trieu26f96072011-09-02 01:51:02 +00004654/// \brief Return false if the condition expression is valid, true otherwise.
4655static bool checkCondition(Sema &S, Expr *Cond) {
4656 QualType CondTy = Cond->getType();
4657
4658 // C99 6.5.15p2
4659 if (CondTy->isScalarType()) return false;
4660
4661 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004662 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004663 return false;
4664
4665 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004666 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004667 diag::err_typecheck_cond_expect_scalar :
4668 diag::err_typecheck_cond_expect_scalar_or_vector)
4669 << CondTy;
4670 return true;
4671}
4672
4673/// \brief Return false if the two expressions can be converted to a vector,
4674/// true otherwise
4675static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4676 ExprResult &RHS,
4677 QualType CondTy) {
4678 // Both operands should be of scalar type.
4679 if (!LHS.get()->getType()->isScalarType()) {
4680 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4681 << CondTy;
4682 return true;
4683 }
4684 if (!RHS.get()->getType()->isScalarType()) {
4685 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4686 << CondTy;
4687 return true;
4688 }
4689
4690 // Implicity convert these scalars to the type of the condition.
4691 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4692 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4693 return false;
4694}
4695
4696/// \brief Handle when one or both operands are void type.
4697static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4698 ExprResult &RHS) {
4699 Expr *LHSExpr = LHS.get();
4700 Expr *RHSExpr = RHS.get();
4701
4702 if (!LHSExpr->getType()->isVoidType())
4703 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4704 << RHSExpr->getSourceRange();
4705 if (!RHSExpr->getType()->isVoidType())
4706 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4707 << LHSExpr->getSourceRange();
4708 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4709 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4710 return S.Context.VoidTy;
4711}
4712
4713/// \brief Return false if the NullExpr can be promoted to PointerTy,
4714/// true otherwise.
4715static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4716 QualType PointerTy) {
4717 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4718 !NullExpr.get()->isNullPointerConstant(S.Context,
4719 Expr::NPC_ValueDependentIsNull))
4720 return true;
4721
4722 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4723 return false;
4724}
4725
4726/// \brief Checks compatibility between two pointers and return the resulting
4727/// type.
4728static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4729 ExprResult &RHS,
4730 SourceLocation Loc) {
4731 QualType LHSTy = LHS.get()->getType();
4732 QualType RHSTy = RHS.get()->getType();
4733
4734 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4735 // Two identical pointers types are always compatible.
4736 return LHSTy;
4737 }
4738
4739 QualType lhptee, rhptee;
4740
4741 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004742 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4743 lhptee = LHSBTy->getPointeeType();
4744 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004745 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004746 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4747 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004748 }
4749
Eli Friedmanae916a12012-04-05 22:30:04 +00004750 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4751 // differently qualified versions of compatible types, the result type is
4752 // a pointer to an appropriately qualified version of the composite
4753 // type.
4754
4755 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4756 // clause doesn't make sense for our extensions. E.g. address space 2 should
4757 // be incompatible with address space 3: they may live on different devices or
4758 // anything.
4759 Qualifiers lhQual = lhptee.getQualifiers();
4760 Qualifiers rhQual = rhptee.getQualifiers();
4761
4762 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4763 lhQual.removeCVRQualifiers();
4764 rhQual.removeCVRQualifiers();
4765
4766 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4767 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4768
4769 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4770
4771 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004772 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4773 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4774 << RHS.get()->getSourceRange();
4775 // In this situation, we assume void* type. No especially good
4776 // reason, but this is what gcc does, and we do have to pick
4777 // to get a consistent AST.
4778 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4779 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4780 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4781 return incompatTy;
4782 }
4783
4784 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004785 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4786 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004787
Eli Friedmanae916a12012-04-05 22:30:04 +00004788 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4789 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4790 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004791}
4792
4793/// \brief Return the resulting type when the operands are both block pointers.
4794static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4795 ExprResult &LHS,
4796 ExprResult &RHS,
4797 SourceLocation Loc) {
4798 QualType LHSTy = LHS.get()->getType();
4799 QualType RHSTy = RHS.get()->getType();
4800
4801 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4802 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4803 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4804 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4805 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4806 return destType;
4807 }
4808 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4809 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4810 << RHS.get()->getSourceRange();
4811 return QualType();
4812 }
4813
4814 // We have 2 block pointer types.
4815 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4816}
4817
4818/// \brief Return the resulting type when the operands are both pointers.
4819static QualType
4820checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4821 ExprResult &RHS,
4822 SourceLocation Loc) {
4823 // get the pointer types
4824 QualType LHSTy = LHS.get()->getType();
4825 QualType RHSTy = RHS.get()->getType();
4826
4827 // get the "pointed to" types
4828 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4829 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4830
4831 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4832 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4833 // Figure out necessary qualifiers (C99 6.5.15p6)
4834 QualType destPointee
4835 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4836 QualType destType = S.Context.getPointerType(destPointee);
4837 // Add qualifiers if necessary.
4838 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4839 // Promote to void*.
4840 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4841 return destType;
4842 }
4843 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4844 QualType destPointee
4845 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4846 QualType destType = S.Context.getPointerType(destPointee);
4847 // Add qualifiers if necessary.
4848 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4849 // Promote to void*.
4850 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4851 return destType;
4852 }
4853
4854 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4855}
4856
4857/// \brief Return false if the first expression is not an integer and the second
4858/// expression is not a pointer, true otherwise.
4859static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4860 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004861 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004862 if (!PointerExpr->getType()->isPointerType() ||
4863 !Int.get()->getType()->isIntegerType())
4864 return false;
4865
Richard Trieuccd891a2011-09-09 01:45:06 +00004866 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4867 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004868
4869 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4870 << Expr1->getType() << Expr2->getType()
4871 << Expr1->getSourceRange() << Expr2->getSourceRange();
4872 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4873 CK_IntegralToPointer);
4874 return true;
4875}
4876
Richard Trieu33fc7572011-09-06 20:06:39 +00004877/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4878/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004879/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004880QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4881 ExprResult &RHS, ExprValueKind &VK,
4882 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004883 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004884
Richard Trieu33fc7572011-09-06 20:06:39 +00004885 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4886 if (!LHSResult.isUsable()) return QualType();
4887 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004888
Richard Trieu33fc7572011-09-06 20:06:39 +00004889 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4890 if (!RHSResult.isUsable()) return QualType();
4891 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004892
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004893 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004894 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004895 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004896
4897 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004898 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004899
John Wiegley429bb272011-04-08 18:41:53 +00004900 Cond = UsualUnaryConversions(Cond.take());
4901 if (Cond.isInvalid())
4902 return QualType();
4903 LHS = UsualUnaryConversions(LHS.take());
4904 if (LHS.isInvalid())
4905 return QualType();
4906 RHS = UsualUnaryConversions(RHS.take());
4907 if (RHS.isInvalid())
4908 return QualType();
4909
4910 QualType CondTy = Cond.get()->getType();
4911 QualType LHSTy = LHS.get()->getType();
4912 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004913
Reid Spencer5f016e22007-07-11 17:01:13 +00004914 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004915 if (checkCondition(*this, Cond.get()))
4916 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004917
Chris Lattner70d67a92008-01-06 22:42:25 +00004918 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004919 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004920 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004921
Nate Begeman6155d732010-09-20 22:41:17 +00004922 // OpenCL: If the condition is a vector, and both operands are scalar,
4923 // attempt to implicity convert them to the vector type to act like the
4924 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004925 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004926 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004927 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004928
Chris Lattner70d67a92008-01-06 22:42:25 +00004929 // If both operands have arithmetic type, do the usual arithmetic conversions
4930 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004931 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4932 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004933 if (LHS.isInvalid() || RHS.isInvalid())
4934 return QualType();
4935 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004936 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004937
Chris Lattner70d67a92008-01-06 22:42:25 +00004938 // If both operands are the same structure or union type, the result is that
4939 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004940 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4941 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004942 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004943 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004944 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004945 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004946 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004947 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004948
Chris Lattner70d67a92008-01-06 22:42:25 +00004949 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004950 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004951 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004952 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004953 }
Richard Trieu26f96072011-09-02 01:51:02 +00004954
Steve Naroffb6d54e52008-01-08 01:11:38 +00004955 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4956 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004957 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4958 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004959
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004960 // All objective-c pointer type analysis is done here.
4961 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4962 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004963 if (LHS.isInvalid() || RHS.isInvalid())
4964 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004965 if (!compositeType.isNull())
4966 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004967
4968
Steve Naroff7154a772009-07-01 14:36:47 +00004969 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004970 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4971 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4972 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004973
Steve Naroff7154a772009-07-01 14:36:47 +00004974 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004975 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4976 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4977 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004978
John McCall404cd162010-11-13 01:35:44 +00004979 // GCC compatibility: soften pointer/integer mismatch. Note that
4980 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004981 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4982 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004983 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004984 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4985 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004986 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004987
Chandler Carruth82214a82011-02-18 23:54:50 +00004988 // Emit a better diagnostic if one of the expressions is a null pointer
4989 // constant and the other is not a pointer type. In this case, the user most
4990 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004991 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004992 return QualType();
4993
Chris Lattner70d67a92008-01-06 22:42:25 +00004994 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004995 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004996 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4997 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004998 return QualType();
4999}
5000
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005001/// FindCompositeObjCPointerType - Helper method to find composite type of
5002/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005003QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005004 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005005 QualType LHSTy = LHS.get()->getType();
5006 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005007
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005008 // Handle things like Class and struct objc_class*. Here we case the result
5009 // to the pseudo-builtin, because that will be implicitly cast back to the
5010 // redefinition type if an attempt is made to access its fields.
5011 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005012 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005013 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005014 return LHSTy;
5015 }
5016 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005017 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005018 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005019 return RHSTy;
5020 }
5021 // And the same for struct objc_object* / id
5022 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005023 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005024 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005025 return LHSTy;
5026 }
5027 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005028 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005029 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005030 return RHSTy;
5031 }
5032 // And the same for struct objc_selector* / SEL
5033 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005034 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005035 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005036 return LHSTy;
5037 }
5038 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005039 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005040 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005041 return RHSTy;
5042 }
5043 // Check constraints for Objective-C object pointers types.
5044 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005045
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005046 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5047 // Two identical object pointer types are always compatible.
5048 return LHSTy;
5049 }
John McCall1d9b3b22011-09-09 05:25:32 +00005050 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5051 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005052 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005053
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005054 // If both operands are interfaces and either operand can be
5055 // assigned to the other, use that type as the composite
5056 // type. This allows
5057 // xxx ? (A*) a : (B*) b
5058 // where B is a subclass of A.
5059 //
5060 // Additionally, as for assignment, if either type is 'id'
5061 // allow silent coercion. Finally, if the types are
5062 // incompatible then make sure to use 'id' as the composite
5063 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005064
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005065 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5066 // It could return the composite type.
5067 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5068 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5069 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5070 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5071 } else if ((LHSTy->isObjCQualifiedIdType() ||
5072 RHSTy->isObjCQualifiedIdType()) &&
5073 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5074 // Need to handle "id<xx>" explicitly.
5075 // GCC allows qualified id and any Objective-C type to devolve to
5076 // id. Currently localizing to here until clear this should be
5077 // part of ObjCQualifiedIdTypesAreCompatible.
5078 compositeType = Context.getObjCIdType();
5079 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5080 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005081 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005082 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5083 ;
5084 else {
5085 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5086 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005087 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005088 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005089 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5090 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005091 return incompatTy;
5092 }
5093 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005094 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5095 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005096 return compositeType;
5097 }
5098 // Check Objective-C object pointer types and 'void *'
5099 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005100 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005101 // ARC forbids the implicit conversion of object pointers to 'void *',
5102 // so these types are not compatible.
5103 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5104 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5105 LHS = RHS = true;
5106 return QualType();
5107 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005108 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5109 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5110 QualType destPointee
5111 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5112 QualType destType = Context.getPointerType(destPointee);
5113 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005114 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005115 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005116 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005117 return destType;
5118 }
5119 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005120 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005121 // ARC forbids the implicit conversion of object pointers to 'void *',
5122 // so these types are not compatible.
5123 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5124 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5125 LHS = RHS = true;
5126 return QualType();
5127 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005128 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5129 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5130 QualType destPointee
5131 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5132 QualType destType = Context.getPointerType(destPointee);
5133 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005134 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005135 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005136 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005137 return destType;
5138 }
5139 return QualType();
5140}
5141
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005142/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005143/// ParenRange in parentheses.
5144static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005145 const PartialDiagnostic &Note,
5146 SourceRange ParenRange) {
5147 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5148 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5149 EndLoc.isValid()) {
5150 Self.Diag(Loc, Note)
5151 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5152 << FixItHint::CreateInsertion(EndLoc, ")");
5153 } else {
5154 // We can't display the parentheses, so just show the bare note.
5155 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005156 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005157}
5158
5159static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5160 return Opc >= BO_Mul && Opc <= BO_Shr;
5161}
5162
Hans Wennborg2f072b42011-06-09 17:06:51 +00005163/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5164/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005165/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5166/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005167static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005168 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005169 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5170 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005171 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005172 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005173
5174 // Built-in binary operator.
5175 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5176 if (IsArithmeticOp(OP->getOpcode())) {
5177 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005178 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005179 return true;
5180 }
5181 }
5182
5183 // Overloaded operator.
5184 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5185 if (Call->getNumArgs() != 2)
5186 return false;
5187
5188 // Make sure this is really a binary operator that is safe to pass into
5189 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5190 OverloadedOperatorKind OO = Call->getOperator();
5191 if (OO < OO_Plus || OO > OO_Arrow)
5192 return false;
5193
5194 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5195 if (IsArithmeticOp(OpKind)) {
5196 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005197 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005198 return true;
5199 }
5200 }
5201
5202 return false;
5203}
5204
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005205static bool IsLogicOp(BinaryOperatorKind Opc) {
5206 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5207}
5208
Hans Wennborg2f072b42011-06-09 17:06:51 +00005209/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5210/// or is a logical expression such as (x==y) which has int type, but is
5211/// commonly interpreted as boolean.
5212static bool ExprLooksBoolean(Expr *E) {
5213 E = E->IgnoreParenImpCasts();
5214
5215 if (E->getType()->isBooleanType())
5216 return true;
5217 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5218 return IsLogicOp(OP->getOpcode());
5219 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5220 return OP->getOpcode() == UO_LNot;
5221
5222 return false;
5223}
5224
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005225/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5226/// and binary operator are mixed in a way that suggests the programmer assumed
5227/// the conditional operator has higher precedence, for example:
5228/// "int x = a + someBinaryCondition ? 1 : 2".
5229static void DiagnoseConditionalPrecedence(Sema &Self,
5230 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005231 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005232 Expr *LHSExpr,
5233 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005234 BinaryOperatorKind CondOpcode;
5235 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005236
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005237 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005238 return;
5239 if (!ExprLooksBoolean(CondRHS))
5240 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005241
Hans Wennborg2f072b42011-06-09 17:06:51 +00005242 // The condition is an arithmetic binary expression, with a right-
5243 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005244
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005245 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005246 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005247 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005248
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005249 SuggestParentheses(Self, OpLoc,
5250 Self.PDiag(diag::note_precedence_conditional_silence)
5251 << BinaryOperator::getOpcodeStr(CondOpcode),
5252 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005253
5254 SuggestParentheses(Self, OpLoc,
5255 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005256 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005257}
5258
Steve Narofff69936d2007-09-16 03:34:24 +00005259/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005260/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005261ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005262 SourceLocation ColonLoc,
5263 Expr *CondExpr, Expr *LHSExpr,
5264 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005265 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5266 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005267 OpaqueValueExpr *opaqueValue = 0;
5268 Expr *commonExpr = 0;
5269 if (LHSExpr == 0) {
5270 commonExpr = CondExpr;
5271
5272 // We usually want to apply unary conversions *before* saving, except
5273 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005274 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005275 && !commonExpr->isTypeDependent()
5276 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5277 && commonExpr->isGLValue()
5278 && commonExpr->isOrdinaryOrBitFieldObject()
5279 && RHSExpr->isOrdinaryOrBitFieldObject()
5280 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005281 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5282 if (commonRes.isInvalid())
5283 return ExprError();
5284 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005285 }
5286
5287 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5288 commonExpr->getType(),
5289 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005290 commonExpr->getObjectKind(),
5291 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005292 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005293 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005294
John McCallf89e55a2010-11-18 06:31:45 +00005295 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005296 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005297 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5298 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005299 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005300 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5301 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005302 return ExprError();
5303
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005304 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5305 RHS.get());
5306
John McCall56ca35d2011-02-17 10:25:35 +00005307 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005308 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5309 LHS.take(), ColonLoc,
5310 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005311
5312 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005313 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005314 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5315 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005316}
5317
John McCalle4be87e2011-01-31 23:13:11 +00005318// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005319// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005320// routine is it effectively iqnores the qualifiers on the top level pointee.
5321// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5322// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005323static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005324checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5325 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5326 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005327
Reid Spencer5f016e22007-07-11 17:01:13 +00005328 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005329 const Type *lhptee, *rhptee;
5330 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005331 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5332 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005333
John McCalle4be87e2011-01-31 23:13:11 +00005334 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005335
5336 // C99 6.5.16.1p1: This following citation is common to constraints
5337 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5338 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005339 Qualifiers lq;
5340
John McCallf85e1932011-06-15 23:02:42 +00005341 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5342 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5343 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5344 // Ignore lifetime for further calculation.
5345 lhq.removeObjCLifetime();
5346 rhq.removeObjCLifetime();
5347 }
5348
John McCall86c05f32011-02-01 00:10:29 +00005349 if (!lhq.compatiblyIncludes(rhq)) {
5350 // Treat address-space mismatches as fatal. TODO: address subspaces
5351 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5352 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5353
John McCallf85e1932011-06-15 23:02:42 +00005354 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005355 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005356 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005357 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005358 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005359 && (lhptee->isVoidType() || rhptee->isVoidType()))
5360 ; // keep old
5361
John McCallf85e1932011-06-15 23:02:42 +00005362 // Treat lifetime mismatches as fatal.
5363 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5364 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5365
John McCall86c05f32011-02-01 00:10:29 +00005366 // For GCC compatibility, other qualifier mismatches are treated
5367 // as still compatible in C.
5368 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5369 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005370
Mike Stumpeed9cac2009-02-19 03:04:26 +00005371 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5372 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005373 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005374 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005375 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005376 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005377
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005378 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005379 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005380 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005381 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005382
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005383 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005384 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005385 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005386
5387 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005388 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005389 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005390 }
John McCall86c05f32011-02-01 00:10:29 +00005391
Mike Stumpeed9cac2009-02-19 03:04:26 +00005392 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005393 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005394 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5395 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005396 // Check if the pointee types are compatible ignoring the sign.
5397 // We explicitly check for char so that we catch "char" vs
5398 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005399 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005400 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005401 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005402 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005403
Chris Lattner6a2b9262009-10-17 20:33:28 +00005404 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005405 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005406 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005407 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005408
John McCall86c05f32011-02-01 00:10:29 +00005409 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005410 // Types are compatible ignoring the sign. Qualifier incompatibility
5411 // takes priority over sign incompatibility because the sign
5412 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005413 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005414 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005415
John McCalle4be87e2011-01-31 23:13:11 +00005416 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005417 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005418
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005419 // If we are a multi-level pointer, it's possible that our issue is simply
5420 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5421 // the eventual target type is the same and the pointers have the same
5422 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005423 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005424 do {
John McCall86c05f32011-02-01 00:10:29 +00005425 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5426 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005427 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005428
John McCall86c05f32011-02-01 00:10:29 +00005429 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005430 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005431 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005432
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005433 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005434 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005435 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005436 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005437 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5438 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005439 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005440}
5441
John McCalle4be87e2011-01-31 23:13:11 +00005442/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005443/// block pointer types are compatible or whether a block and normal pointer
5444/// are compatible. It is more restrict than comparing two function pointer
5445// types.
John McCalle4be87e2011-01-31 23:13:11 +00005446static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005447checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5448 QualType RHSType) {
5449 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5450 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005451
Steve Naroff1c7d0672008-09-04 15:10:53 +00005452 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005453
Steve Naroff1c7d0672008-09-04 15:10:53 +00005454 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005455 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5456 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005457
John McCalle4be87e2011-01-31 23:13:11 +00005458 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005459 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005460 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005461
John McCalle4be87e2011-01-31 23:13:11 +00005462 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005463
Steve Naroff1c7d0672008-09-04 15:10:53 +00005464 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005465 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5466 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005467
Richard Trieu1da27a12011-09-06 20:21:22 +00005468 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005469 return Sema::IncompatibleBlockPointer;
5470
Steve Naroff1c7d0672008-09-04 15:10:53 +00005471 return ConvTy;
5472}
5473
John McCalle4be87e2011-01-31 23:13:11 +00005474/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005475/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005476static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005477checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5478 QualType RHSType) {
5479 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5480 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005481
Richard Trieu1da27a12011-09-06 20:21:22 +00005482 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005483 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005484 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5485 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005486 return Sema::IncompatiblePointer;
5487 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005488 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005489 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005490 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5491 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005492 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005493 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005494 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005495 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5496 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005497
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005498 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5499 // make an exception for id<P>
5500 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005501 return Sema::CompatiblePointerDiscardsQualifiers;
5502
Richard Trieu1da27a12011-09-06 20:21:22 +00005503 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005504 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005505 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005506 return Sema::IncompatibleObjCQualifiedId;
5507 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005508}
5509
John McCall1c23e912010-11-16 02:32:08 +00005510Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005511Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005512 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005513 // Fake up an opaque expression. We don't actually care about what
5514 // cast operations are required, so if CheckAssignmentConstraints
5515 // adds casts to this they'll be wasted, but fortunately that doesn't
5516 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005517 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5518 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005519 CastKind K = CK_Invalid;
5520
Richard Trieu1da27a12011-09-06 20:21:22 +00005521 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005522}
5523
Mike Stumpeed9cac2009-02-19 03:04:26 +00005524/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5525/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005526/// pointers. Here are some objectionable examples that GCC considers warnings:
5527///
5528/// int a, *pint;
5529/// short *pshort;
5530/// struct foo *pfoo;
5531///
5532/// pint = pshort; // warning: assignment from incompatible pointer type
5533/// a = pint; // warning: assignment makes integer from pointer without a cast
5534/// pint = a; // warning: assignment makes pointer from integer without a cast
5535/// pint = pfoo; // warning: assignment from incompatible pointer type
5536///
5537/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005538/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005539///
John McCalldaa8e4e2010-11-15 09:13:47 +00005540/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005541Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005542Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005543 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005544 QualType RHSType = RHS.get()->getType();
5545 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005546
Chris Lattnerfc144e22008-01-04 23:18:45 +00005547 // Get canonical types. We're not formatting these types, just comparing
5548 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005549 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5550 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005551
Eli Friedmanb001de72011-10-06 23:00:33 +00005552
John McCallb6cfa242011-01-31 22:28:28 +00005553 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005554 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005555 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005556 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005557 }
5558
Eli Friedman860a3192012-06-16 02:19:17 +00005559 // If we have an atomic type, try a non-atomic assignment, then just add an
5560 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005561 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005562 Sema::AssignConvertType result =
5563 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5564 if (result != Compatible)
5565 return result;
5566 if (Kind != CK_NoOp)
5567 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5568 Kind = CK_NonAtomicToAtomic;
5569 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005570 }
5571
Douglas Gregor9d293df2008-10-28 00:22:11 +00005572 // If the left-hand side is a reference type, then we are in a
5573 // (rare!) case where we've allowed the use of references in C,
5574 // e.g., as a parameter type in a built-in function. In this case,
5575 // just make sure that the type referenced is compatible with the
5576 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005577 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005578 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005579 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5580 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005581 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005582 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005583 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005584 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005585 }
John McCallb6cfa242011-01-31 22:28:28 +00005586
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005587 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5588 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005589 if (LHSType->isExtVectorType()) {
5590 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005591 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005592 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005593 // CK_VectorSplat does T -> vector T, so first cast to the
5594 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005595 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5596 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005597 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005598 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005599 }
5600 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005601 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005602 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005603 }
Mike Stump1eb44332009-09-09 15:08:12 +00005604
John McCallb6cfa242011-01-31 22:28:28 +00005605 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005606 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5607 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005608 // Allow assignments of an AltiVec vector type to an equivalent GCC
5609 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005610 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005611 Kind = CK_BitCast;
5612 return Compatible;
5613 }
5614
Douglas Gregor255210e2010-08-06 10:14:59 +00005615 // If we are allowing lax vector conversions, and LHS and RHS are both
5616 // vectors, the total size only needs to be the same. This is a bitcast;
5617 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005618 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005619 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005620 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005621 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005622 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005623 }
5624 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005625 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005626
John McCallb6cfa242011-01-31 22:28:28 +00005627 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005628 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005629 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005630 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005631 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005632 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005633
John McCallb6cfa242011-01-31 22:28:28 +00005634 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005635 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005636 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005637 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005638 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005639 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005640 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005641
John McCallb6cfa242011-01-31 22:28:28 +00005642 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005643 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005644 Kind = CK_IntegralToPointer; // FIXME: null?
5645 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005646 }
John McCallb6cfa242011-01-31 22:28:28 +00005647
5648 // C pointers are not compatible with ObjC object pointers,
5649 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005650 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005651 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005652 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005653 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005654 return Compatible;
5655 }
5656
5657 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005658 if (RHSType->isObjCClassType() &&
5659 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005660 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005661 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005662 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005663 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005664
John McCallb6cfa242011-01-31 22:28:28 +00005665 Kind = CK_BitCast;
5666 return IncompatiblePointer;
5667 }
5668
5669 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005670 if (RHSType->getAs<BlockPointerType>()) {
5671 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005672 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005673 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005674 }
Steve Naroffb4406862008-09-29 18:10:17 +00005675 }
John McCallb6cfa242011-01-31 22:28:28 +00005676
Steve Naroff1c7d0672008-09-04 15:10:53 +00005677 return Incompatible;
5678 }
5679
John McCallb6cfa242011-01-31 22:28:28 +00005680 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005681 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005682 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005683 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005684 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005685 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005686 }
5687
5688 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005689 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005690 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005691 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005692 }
5693
John McCallb6cfa242011-01-31 22:28:28 +00005694 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005695 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005696 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005697 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005698 }
Steve Naroffb4406862008-09-29 18:10:17 +00005699
John McCallb6cfa242011-01-31 22:28:28 +00005700 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005701 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005702 if (RHSPT->getPointeeType()->isVoidType()) {
5703 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005704 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005705 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005706
Chris Lattnerfc144e22008-01-04 23:18:45 +00005707 return Incompatible;
5708 }
5709
John McCallb6cfa242011-01-31 22:28:28 +00005710 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005711 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005712 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005713 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005714 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005715 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005716 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005717 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005718 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005719 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005720 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005721 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005722 }
5723
5724 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005725 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005726 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005727 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005728 }
5729
John McCallb6cfa242011-01-31 22:28:28 +00005730 // In general, C pointers are not compatible with ObjC object pointers,
5731 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005732 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005733 Kind = CK_CPointerToObjCPointerCast;
5734
John McCallb6cfa242011-01-31 22:28:28 +00005735 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005736 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005737 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005738 }
5739
5740 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005741 if (LHSType->isObjCClassType() &&
5742 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005743 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005744 return Compatible;
5745 }
5746
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005747 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005748 }
John McCallb6cfa242011-01-31 22:28:28 +00005749
5750 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005751 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005752 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005753 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005754 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005755 }
5756
Steve Naroff14108da2009-07-10 23:34:53 +00005757 return Incompatible;
5758 }
John McCallb6cfa242011-01-31 22:28:28 +00005759
5760 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005761 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005762 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005763 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005764 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005765 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005766 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005767
John McCallb6cfa242011-01-31 22:28:28 +00005768 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005769 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005770 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005771 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005772 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005773
Chris Lattnerfc144e22008-01-04 23:18:45 +00005774 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005775 }
John McCallb6cfa242011-01-31 22:28:28 +00005776
5777 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005778 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005779 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005780 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005781 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005782 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005783 }
Steve Naroff14108da2009-07-10 23:34:53 +00005784
John McCallb6cfa242011-01-31 22:28:28 +00005785 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005786 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005787 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005788 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005789 }
5790
Steve Naroff14108da2009-07-10 23:34:53 +00005791 return Incompatible;
5792 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005793
John McCallb6cfa242011-01-31 22:28:28 +00005794 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005795 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5796 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005797 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005798 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005799 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005800 }
John McCallb6cfa242011-01-31 22:28:28 +00005801
Reid Spencer5f016e22007-07-11 17:01:13 +00005802 return Incompatible;
5803}
5804
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005805/// \brief Constructs a transparent union from an expression that is
5806/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005807static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5808 ExprResult &EResult, QualType UnionType,
5809 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005810 // Build an initializer list that designates the appropriate member
5811 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005812 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005813 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005814 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005815 SourceLocation());
5816 Initializer->setType(UnionType);
5817 Initializer->setInitializedFieldInUnion(Field);
5818
5819 // Build a compound literal constructing a value of the transparent
5820 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005821 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005822 EResult = S.Owned(
5823 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5824 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005825}
5826
5827Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005828Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005829 ExprResult &RHS) {
5830 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005831
Mike Stump1eb44332009-09-09 15:08:12 +00005832 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005833 // transparent_union GCC extension.
5834 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005835 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005836 return Incompatible;
5837
5838 // The field to initialize within the transparent union.
5839 RecordDecl *UD = UT->getDecl();
5840 FieldDecl *InitField = 0;
5841 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005842 for (RecordDecl::field_iterator it = UD->field_begin(),
5843 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005844 it != itend; ++it) {
5845 if (it->getType()->isPointerType()) {
5846 // If the transparent union contains a pointer type, we allow:
5847 // 1) void pointer
5848 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005849 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005850 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005851 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005852 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005853 break;
5854 }
Mike Stump1eb44332009-09-09 15:08:12 +00005855
Richard Trieuf7720da2011-09-06 20:40:12 +00005856 if (RHS.get()->isNullPointerConstant(Context,
5857 Expr::NPC_ValueDependentIsNull)) {
5858 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5859 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005860 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005861 break;
5862 }
5863 }
5864
John McCalldaa8e4e2010-11-15 09:13:47 +00005865 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005866 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005867 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005868 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005869 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005870 break;
5871 }
5872 }
5873
5874 if (!InitField)
5875 return Incompatible;
5876
Richard Trieuf7720da2011-09-06 20:40:12 +00005877 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005878 return Compatible;
5879}
5880
Chris Lattner5cf216b2008-01-04 18:04:52 +00005881Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005882Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5883 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005884 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005885 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005886 // C++ 5.17p3: If the left operand is not of class type, the
5887 // expression is implicitly converted (C++ 4) to the
5888 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005889 ExprResult Res;
5890 if (Diagnose) {
5891 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5892 AA_Assigning);
5893 } else {
5894 ImplicitConversionSequence ICS =
5895 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5896 /*SuppressUserConversions=*/false,
5897 /*AllowExplicit=*/false,
5898 /*InOverloadResolution=*/false,
5899 /*CStyle=*/false,
5900 /*AllowObjCWritebackConversion=*/false);
5901 if (ICS.isFailure())
5902 return Incompatible;
5903 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5904 ICS, AA_Assigning);
5905 }
John Wiegley429bb272011-04-08 18:41:53 +00005906 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005907 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005908 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005909 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005910 !CheckObjCARCUnavailableWeakConversion(LHSType,
5911 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005912 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005913 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005914 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005915 }
5916
5917 // FIXME: Currently, we fall through and treat C++ classes like C
5918 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005919 // FIXME: We also fall through for atomics; not sure what should
5920 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005921 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005922
Steve Naroff529a4ad2007-11-27 17:58:44 +00005923 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5924 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005925 if ((LHSType->isPointerType() ||
5926 LHSType->isObjCObjectPointerType() ||
5927 LHSType->isBlockPointerType())
5928 && RHS.get()->isNullPointerConstant(Context,
5929 Expr::NPC_ValueDependentIsNull)) {
5930 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005931 return Compatible;
5932 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005933
Chris Lattner943140e2007-10-16 02:55:40 +00005934 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005935 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005936 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005937 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005938 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005939 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005940 if (!LHSType->isReferenceType()) {
5941 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5942 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005943 return Incompatible;
5944 }
Steve Narofff1120de2007-08-24 22:33:52 +00005945
John McCalldaa8e4e2010-11-15 09:13:47 +00005946 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005947 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005948 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005949
Steve Narofff1120de2007-08-24 22:33:52 +00005950 // C99 6.5.16.1p2: The value of the right operand is converted to the
5951 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005952 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5953 // so that we can use references in built-in functions even in C.
5954 // The getNonReferenceType() call makes sure that the resulting expression
5955 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005956 if (result != Incompatible && RHS.get()->getType() != LHSType)
5957 RHS = ImpCastExprToType(RHS.take(),
5958 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005959 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005960}
5961
Richard Trieuf7720da2011-09-06 20:40:12 +00005962QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5963 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005964 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005965 << LHS.get()->getType() << RHS.get()->getType()
5966 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005967 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005968}
5969
Richard Trieu08062aa2011-09-06 21:01:04 +00005970QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005971 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005972 if (!IsCompAssign) {
5973 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5974 if (LHS.isInvalid())
5975 return QualType();
5976 }
5977 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5978 if (RHS.isInvalid())
5979 return QualType();
5980
Mike Stumpeed9cac2009-02-19 03:04:26 +00005981 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005982 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005983 QualType LHSType =
5984 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5985 QualType RHSType =
5986 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005987
Nate Begemanbe2341d2008-07-14 18:02:46 +00005988 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005989 if (LHSType == RHSType)
5990 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005991
Douglas Gregor255210e2010-08-06 10:14:59 +00005992 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005993 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5994 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5995 if (LHSType->isExtVectorType()) {
5996 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5997 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005998 }
5999
Richard Trieuccd891a2011-09-09 01:45:06 +00006000 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006001 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6002 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006003 }
6004
David Blaikie4e4d0842012-03-11 07:00:24 +00006005 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006006 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006007 // If we are allowing lax vector conversions, and LHS and RHS are both
6008 // vectors, the total size only needs to be the same. This is a
6009 // bitcast; no bits are changed but the result type is different.
6010 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006011 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6012 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006013 }
6014
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006015 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6016 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6017 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006018 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006019 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006020 std::swap(RHS, LHS);
6021 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006022 }
Mike Stump1eb44332009-09-09 15:08:12 +00006023
Nate Begemandde25982009-06-28 19:12:57 +00006024 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006025 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006026 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006027 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6028 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006029 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006030 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006031 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006032 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6033 if (swapped) std::swap(RHS, LHS);
6034 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006035 }
6036 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006037 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6038 RHSType->isRealFloatingType()) {
6039 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006040 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006041 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006042 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006043 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6044 if (swapped) std::swap(RHS, LHS);
6045 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006046 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006047 }
6048 }
Mike Stump1eb44332009-09-09 15:08:12 +00006049
Nate Begemandde25982009-06-28 19:12:57 +00006050 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006051 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006052 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006053 << LHS.get()->getType() << RHS.get()->getType()
6054 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006055 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006056}
6057
Richard Trieu481037f2011-09-16 00:53:10 +00006058// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6059// expression. These are mainly cases where the null pointer is used as an
6060// integer instead of a pointer.
6061static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6062 SourceLocation Loc, bool IsCompare) {
6063 // The canonical way to check for a GNU null is with isNullPointerConstant,
6064 // but we use a bit of a hack here for speed; this is a relatively
6065 // hot path, and isNullPointerConstant is slow.
6066 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6067 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6068
6069 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6070
6071 // Avoid analyzing cases where the result will either be invalid (and
6072 // diagnosed as such) or entirely valid and not something to warn about.
6073 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6074 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6075 return;
6076
6077 // Comparison operations would not make sense with a null pointer no matter
6078 // what the other expression is.
6079 if (!IsCompare) {
6080 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6081 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6082 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6083 return;
6084 }
6085
6086 // The rest of the operations only make sense with a null pointer
6087 // if the other expression is a pointer.
6088 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6089 NonNullType->canDecayToPointerType())
6090 return;
6091
6092 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6093 << LHSNull /* LHS is NULL */ << NonNullType
6094 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6095}
6096
Richard Trieu08062aa2011-09-06 21:01:04 +00006097QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006098 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006099 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006100 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6101
Richard Trieu08062aa2011-09-06 21:01:04 +00006102 if (LHS.get()->getType()->isVectorType() ||
6103 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006104 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006105
Richard Trieuccd891a2011-09-09 01:45:06 +00006106 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006107 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006108 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006109
David Chisnall7a7ee302012-01-16 17:27:18 +00006110
Eli Friedman860a3192012-06-16 02:19:17 +00006111 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006112 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006113
Chris Lattner7ef655a2010-01-12 21:23:57 +00006114 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006115 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006116 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006117 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006118 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6119 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006120
Chris Lattner7ef655a2010-01-12 21:23:57 +00006121 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006122}
6123
Chris Lattner7ef655a2010-01-12 21:23:57 +00006124QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006125 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006126 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6127
Richard Trieu08062aa2011-09-06 21:01:04 +00006128 if (LHS.get()->getType()->isVectorType() ||
6129 RHS.get()->getType()->isVectorType()) {
6130 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6131 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006132 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006133 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006134 }
Steve Naroff90045e82007-07-13 23:32:42 +00006135
Richard Trieuccd891a2011-09-09 01:45:06 +00006136 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006137 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006138 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006139
Eli Friedman860a3192012-06-16 02:19:17 +00006140 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006141 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006142
Chris Lattner7ef655a2010-01-12 21:23:57 +00006143 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006144 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006145 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006146 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6147 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006148
Chris Lattner7ef655a2010-01-12 21:23:57 +00006149 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006150}
6151
Chandler Carruth13b21be2011-06-27 08:02:19 +00006152/// \brief Diagnose invalid arithmetic on two void pointers.
6153static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006154 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006155 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006156 ? diag::err_typecheck_pointer_arith_void_type
6157 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006158 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6159 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006160}
6161
6162/// \brief Diagnose invalid arithmetic on a void pointer.
6163static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6164 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006165 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006166 ? diag::err_typecheck_pointer_arith_void_type
6167 : diag::ext_gnu_void_ptr)
6168 << 0 /* one pointer */ << Pointer->getSourceRange();
6169}
6170
6171/// \brief Diagnose invalid arithmetic on two function pointers.
6172static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6173 Expr *LHS, Expr *RHS) {
6174 assert(LHS->getType()->isAnyPointerType());
6175 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006176 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006177 ? diag::err_typecheck_pointer_arith_function_type
6178 : diag::ext_gnu_ptr_func_arith)
6179 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6180 // We only show the second type if it differs from the first.
6181 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6182 RHS->getType())
6183 << RHS->getType()->getPointeeType()
6184 << LHS->getSourceRange() << RHS->getSourceRange();
6185}
6186
6187/// \brief Diagnose invalid arithmetic on a function pointer.
6188static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6189 Expr *Pointer) {
6190 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006191 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006192 ? diag::err_typecheck_pointer_arith_function_type
6193 : diag::ext_gnu_ptr_func_arith)
6194 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6195 << 0 /* one pointer, so only one type */
6196 << Pointer->getSourceRange();
6197}
6198
Richard Trieud9f19342011-09-12 18:08:02 +00006199/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006200///
6201/// \returns True if pointer has incomplete type
6202static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6203 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006204 assert(Operand->getType()->isAnyPointerType() &&
6205 !Operand->getType()->isDependentType());
6206 QualType PointeeTy = Operand->getType()->getPointeeType();
6207 return S.RequireCompleteType(Loc, PointeeTy,
6208 diag::err_typecheck_arithmetic_incomplete_type,
6209 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006210}
6211
Chandler Carruth13b21be2011-06-27 08:02:19 +00006212/// \brief Check the validity of an arithmetic pointer operand.
6213///
6214/// If the operand has pointer type, this code will check for pointer types
6215/// which are invalid in arithmetic operations. These will be diagnosed
6216/// appropriately, including whether or not the use is supported as an
6217/// extension.
6218///
6219/// \returns True when the operand is valid to use (even if as an extension).
6220static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6221 Expr *Operand) {
6222 if (!Operand->getType()->isAnyPointerType()) return true;
6223
6224 QualType PointeeTy = Operand->getType()->getPointeeType();
6225 if (PointeeTy->isVoidType()) {
6226 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006227 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006228 }
6229 if (PointeeTy->isFunctionType()) {
6230 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006231 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006232 }
6233
Richard Trieu097ecd22011-09-02 02:15:37 +00006234 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006235
6236 return true;
6237}
6238
6239/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6240/// operands.
6241///
6242/// This routine will diagnose any invalid arithmetic on pointer operands much
6243/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6244/// for emitting a single diagnostic even for operations where both LHS and RHS
6245/// are (potentially problematic) pointers.
6246///
6247/// \returns True when the operand is valid to use (even if as an extension).
6248static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006249 Expr *LHSExpr, Expr *RHSExpr) {
6250 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6251 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006252 if (!isLHSPointer && !isRHSPointer) return true;
6253
6254 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006255 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6256 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006257
6258 // Check for arithmetic on pointers to incomplete types.
6259 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6260 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6261 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006262 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6263 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6264 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006265
David Blaikie4e4d0842012-03-11 07:00:24 +00006266 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006267 }
6268
6269 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6270 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6271 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006272 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6273 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6274 RHSExpr);
6275 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006276
David Blaikie4e4d0842012-03-11 07:00:24 +00006277 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006278 }
6279
John McCall1503f0d2012-07-31 05:14:30 +00006280 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6281 return false;
6282 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6283 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006284
Chandler Carruth13b21be2011-06-27 08:02:19 +00006285 return true;
6286}
6287
Nico Weber1cb2d742012-03-02 22:01:22 +00006288/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6289/// literal.
6290static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6291 Expr *LHSExpr, Expr *RHSExpr) {
6292 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6293 Expr* IndexExpr = RHSExpr;
6294 if (!StrExpr) {
6295 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6296 IndexExpr = LHSExpr;
6297 }
6298
6299 bool IsStringPlusInt = StrExpr &&
6300 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6301 if (!IsStringPlusInt)
6302 return;
6303
6304 llvm::APSInt index;
6305 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6306 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6307 if (index.isNonNegative() &&
6308 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6309 index.isUnsigned()))
6310 return;
6311 }
6312
6313 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6314 Self.Diag(OpLoc, diag::warn_string_plus_int)
6315 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6316
6317 // Only print a fixit for "str" + int, not for int + "str".
6318 if (IndexExpr == RHSExpr) {
6319 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6320 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6321 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6322 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6323 << FixItHint::CreateInsertion(EndLoc, "]");
6324 } else
6325 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6326}
6327
Richard Trieud9f19342011-09-12 18:08:02 +00006328/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006329static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006330 Expr *LHSExpr, Expr *RHSExpr) {
6331 assert(LHSExpr->getType()->isAnyPointerType());
6332 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006333 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006334 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6335 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006336}
6337
Chris Lattner7ef655a2010-01-12 21:23:57 +00006338QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006339 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6340 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006341 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6342
Richard Trieudef75842011-09-06 21:13:51 +00006343 if (LHS.get()->getType()->isVectorType() ||
6344 RHS.get()->getType()->isVectorType()) {
6345 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006346 if (CompLHSTy) *CompLHSTy = compType;
6347 return compType;
6348 }
Steve Naroff49b45262007-07-13 16:58:59 +00006349
Richard Trieudef75842011-09-06 21:13:51 +00006350 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6351 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006352 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006353
Nico Weber1cb2d742012-03-02 22:01:22 +00006354 // Diagnose "string literal" '+' int.
6355 if (Opc == BO_Add)
6356 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6357
Reid Spencer5f016e22007-07-11 17:01:13 +00006358 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006359 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006360 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006361 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006362 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006363
John McCall1503f0d2012-07-31 05:14:30 +00006364 // Type-checking. Ultimately the pointer's going to be in PExp;
6365 // note that we bias towards the LHS being the pointer.
6366 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006367
John McCall1503f0d2012-07-31 05:14:30 +00006368 bool isObjCPointer;
6369 if (PExp->getType()->isPointerType()) {
6370 isObjCPointer = false;
6371 } else if (PExp->getType()->isObjCObjectPointerType()) {
6372 isObjCPointer = true;
6373 } else {
6374 std::swap(PExp, IExp);
6375 if (PExp->getType()->isPointerType()) {
6376 isObjCPointer = false;
6377 } else if (PExp->getType()->isObjCObjectPointerType()) {
6378 isObjCPointer = true;
6379 } else {
6380 return InvalidOperands(Loc, LHS, RHS);
6381 }
6382 }
6383 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006384
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006385 if (!IExp->getType()->isIntegerType())
6386 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006387
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006388 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6389 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006390
John McCall1503f0d2012-07-31 05:14:30 +00006391 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006392 return QualType();
6393
6394 // Check array bounds for pointer arithemtic
6395 CheckArrayAccess(PExp, IExp);
6396
6397 if (CompLHSTy) {
6398 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6399 if (LHSTy.isNull()) {
6400 LHSTy = LHS.get()->getType();
6401 if (LHSTy->isPromotableIntegerType())
6402 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006403 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006404 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006405 }
6406
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006407 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006408}
6409
Chris Lattnereca7be62008-04-07 05:30:13 +00006410// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006411QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006412 SourceLocation Loc,
6413 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006414 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6415
Richard Trieudef75842011-09-06 21:13:51 +00006416 if (LHS.get()->getType()->isVectorType() ||
6417 RHS.get()->getType()->isVectorType()) {
6418 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006419 if (CompLHSTy) *CompLHSTy = compType;
6420 return compType;
6421 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006422
Richard Trieudef75842011-09-06 21:13:51 +00006423 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6424 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006425 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006426
Chris Lattner6e4ab612007-12-09 21:53:25 +00006427 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006428
Chris Lattner6e4ab612007-12-09 21:53:25 +00006429 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006430 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006431 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006432 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006433 }
Mike Stump1eb44332009-09-09 15:08:12 +00006434
Chris Lattner6e4ab612007-12-09 21:53:25 +00006435 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006436 if (LHS.get()->getType()->isAnyPointerType()) {
6437 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006438
Chris Lattnerb5f15622009-04-24 23:50:08 +00006439 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006440 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6441 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006442 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006443
Chris Lattner6e4ab612007-12-09 21:53:25 +00006444 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006445 if (RHS.get()->getType()->isIntegerType()) {
6446 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006447 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006448
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006449 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006450 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6451 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006452
Richard Trieudef75842011-09-06 21:13:51 +00006453 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6454 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006455 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006456
Chris Lattner6e4ab612007-12-09 21:53:25 +00006457 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006458 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006459 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006460 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006461
David Blaikie4e4d0842012-03-11 07:00:24 +00006462 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006463 // Pointee types must be the same: C++ [expr.add]
6464 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006465 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006466 }
6467 } else {
6468 // Pointee types must be compatible C99 6.5.6p3
6469 if (!Context.typesAreCompatible(
6470 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6471 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006472 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006473 return QualType();
6474 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006475 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006476
Chandler Carruth13b21be2011-06-27 08:02:19 +00006477 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006478 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006479 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006480
Richard Trieudef75842011-09-06 21:13:51 +00006481 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006482 return Context.getPointerDiffType();
6483 }
6484 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006485
Richard Trieudef75842011-09-06 21:13:51 +00006486 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006487}
6488
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006489static bool isScopedEnumerationType(QualType T) {
6490 if (const EnumType *ET = dyn_cast<EnumType>(T))
6491 return ET->getDecl()->isScoped();
6492 return false;
6493}
6494
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006495static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006496 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006497 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006498 llvm::APSInt Right;
6499 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006500 if (RHS.get()->isValueDependent() ||
6501 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006502 return;
6503
6504 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006505 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006506 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006507 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006508 return;
6509 }
6510 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006511 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006512 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006513 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006514 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006515 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006516 return;
6517 }
6518 if (Opc != BO_Shl)
6519 return;
6520
6521 // When left shifting an ICE which is signed, we can check for overflow which
6522 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6523 // integers have defined behavior modulo one more than the maximum value
6524 // representable in the result type, so never warn for those.
6525 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006526 if (LHS.get()->isValueDependent() ||
6527 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6528 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006529 return;
6530 llvm::APInt ResultBits =
6531 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6532 if (LeftBits.uge(ResultBits))
6533 return;
6534 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6535 Result = Result.shl(Right);
6536
Ted Kremenekfa821382011-06-15 00:54:52 +00006537 // Print the bit representation of the signed integer as an unsigned
6538 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006539 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006540 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6541
Chandler Carruth21206d52011-02-23 23:34:11 +00006542 // If we are only missing a sign bit, this is less likely to result in actual
6543 // bugs -- if the result is cast back to an unsigned type, it will have the
6544 // expected value. Thus we place this behind a different warning that can be
6545 // turned off separately if needed.
6546 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006547 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006548 << HexResult.str() << LHSType
6549 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006550 return;
6551 }
6552
6553 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006554 << HexResult.str() << Result.getMinSignedBits() << LHSType
6555 << Left.getBitWidth() << LHS.get()->getSourceRange()
6556 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006557}
6558
Chris Lattnereca7be62008-04-07 05:30:13 +00006559// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006560QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006561 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006562 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006563 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6564
Chris Lattnerca5eede2007-12-12 05:47:28 +00006565 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006566 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6567 !RHS.get()->getType()->hasIntegerRepresentation())
6568 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006569
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006570 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6571 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006572 if (isScopedEnumerationType(LHS.get()->getType()) ||
6573 isScopedEnumerationType(RHS.get()->getType())) {
6574 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006575 }
6576
Nate Begeman2207d792009-10-25 02:26:48 +00006577 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006578 if (LHS.get()->getType()->isVectorType() ||
6579 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006580 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006581
Chris Lattnerca5eede2007-12-12 05:47:28 +00006582 // Shifts don't perform usual arithmetic conversions, they just do integer
6583 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006584
John McCall1bc80af2010-12-16 19:28:59 +00006585 // For the LHS, do usual unary conversions, but then reset them away
6586 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006587 ExprResult OldLHS = LHS;
6588 LHS = UsualUnaryConversions(LHS.take());
6589 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006590 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006591 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006592 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006593
6594 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006595 RHS = UsualUnaryConversions(RHS.take());
6596 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006597 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006598
Ryan Flynnd0439682009-08-07 16:20:20 +00006599 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006600 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006601
Chris Lattnerca5eede2007-12-12 05:47:28 +00006602 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006603 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006604}
6605
Chandler Carruth99919472010-07-10 12:30:03 +00006606static bool IsWithinTemplateSpecialization(Decl *D) {
6607 if (DeclContext *DC = D->getDeclContext()) {
6608 if (isa<ClassTemplateSpecializationDecl>(DC))
6609 return true;
6610 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6611 return FD->isFunctionTemplateSpecialization();
6612 }
6613 return false;
6614}
6615
Richard Trieue648ac32011-09-02 03:48:46 +00006616/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006617static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6618 ExprResult &RHS) {
6619 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6620 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006621
6622 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6623 if (!LHSEnumType)
6624 return;
6625 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6626 if (!RHSEnumType)
6627 return;
6628
6629 // Ignore anonymous enums.
6630 if (!LHSEnumType->getDecl()->getIdentifier())
6631 return;
6632 if (!RHSEnumType->getDecl()->getIdentifier())
6633 return;
6634
6635 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6636 return;
6637
6638 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6639 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006640 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006641}
6642
Richard Trieu7be1be02011-09-02 02:55:45 +00006643/// \brief Diagnose bad pointer comparisons.
6644static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006645 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006646 bool IsError) {
6647 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006648 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006649 << LHS.get()->getType() << RHS.get()->getType()
6650 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006651}
6652
6653/// \brief Returns false if the pointers are converted to a composite type,
6654/// true otherwise.
6655static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006656 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006657 // C++ [expr.rel]p2:
6658 // [...] Pointer conversions (4.10) and qualification
6659 // conversions (4.4) are performed on pointer operands (or on
6660 // a pointer operand and a null pointer constant) to bring
6661 // them to their composite pointer type. [...]
6662 //
6663 // C++ [expr.eq]p1 uses the same notion for (in)equality
6664 // comparisons of pointers.
6665
6666 // C++ [expr.eq]p2:
6667 // In addition, pointers to members can be compared, or a pointer to
6668 // member and a null pointer constant. Pointer to member conversions
6669 // (4.11) and qualification conversions (4.4) are performed to bring
6670 // them to a common type. If one operand is a null pointer constant,
6671 // the common type is the type of the other operand. Otherwise, the
6672 // common type is a pointer to member type similar (4.4) to the type
6673 // of one of the operands, with a cv-qualification signature (4.4)
6674 // that is the union of the cv-qualification signatures of the operand
6675 // types.
6676
Richard Trieuba261492011-09-06 21:27:33 +00006677 QualType LHSType = LHS.get()->getType();
6678 QualType RHSType = RHS.get()->getType();
6679 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6680 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006681
6682 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006683 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006684 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006685 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006686 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006687 return true;
6688 }
6689
6690 if (NonStandardCompositeType)
6691 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006692 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6693 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006694
Richard Trieuba261492011-09-06 21:27:33 +00006695 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6696 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006697 return false;
6698}
6699
6700static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006701 ExprResult &LHS,
6702 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006703 bool IsError) {
6704 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6705 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006706 << LHS.get()->getType() << RHS.get()->getType()
6707 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006708}
6709
Jordan Rose9f63a452012-06-08 21:14:25 +00006710static bool isObjCObjectLiteral(ExprResult &E) {
6711 switch (E.get()->getStmtClass()) {
6712 case Stmt::ObjCArrayLiteralClass:
6713 case Stmt::ObjCDictionaryLiteralClass:
6714 case Stmt::ObjCStringLiteralClass:
6715 case Stmt::ObjCBoxedExprClass:
6716 return true;
6717 default:
6718 // Note that ObjCBoolLiteral is NOT an object literal!
6719 return false;
6720 }
6721}
6722
Jordan Rose8d872ca2012-07-17 17:46:40 +00006723static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6724 // Get the LHS object's interface type.
6725 QualType Type = LHS->getType();
6726 QualType InterfaceType;
6727 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6728 InterfaceType = PTy->getPointeeType();
6729 if (const ObjCObjectType *iQFaceTy =
6730 InterfaceType->getAsObjCQualifiedInterfaceType())
6731 InterfaceType = iQFaceTy->getBaseType();
6732 } else {
6733 // If this is not actually an Objective-C object, bail out.
6734 return false;
6735 }
6736
6737 // If the RHS isn't an Objective-C object, bail out.
6738 if (!RHS->getType()->isObjCObjectPointerType())
6739 return false;
6740
6741 // Try to find the -isEqual: method.
6742 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6743 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6744 InterfaceType,
6745 /*instance=*/true);
6746 if (!Method) {
6747 if (Type->isObjCIdType()) {
6748 // For 'id', just check the global pool.
6749 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6750 /*receiverId=*/true,
6751 /*warn=*/false);
6752 } else {
6753 // Check protocols.
6754 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6755 cast<ObjCObjectPointerType>(Type),
6756 /*instance=*/true);
6757 }
6758 }
6759
6760 if (!Method)
6761 return false;
6762
6763 QualType T = Method->param_begin()[0]->getType();
6764 if (!T->isObjCObjectPointerType())
6765 return false;
6766
6767 QualType R = Method->getResultType();
6768 if (!R->isScalarType())
6769 return false;
6770
6771 return true;
6772}
6773
6774static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6775 ExprResult &LHS, ExprResult &RHS,
6776 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006777 Expr *Literal;
6778 Expr *Other;
6779 if (isObjCObjectLiteral(LHS)) {
6780 Literal = LHS.get();
6781 Other = RHS.get();
6782 } else {
6783 Literal = RHS.get();
6784 Other = LHS.get();
6785 }
6786
6787 // Don't warn on comparisons against nil.
6788 Other = Other->IgnoreParenCasts();
6789 if (Other->isNullPointerConstant(S.getASTContext(),
6790 Expr::NPC_ValueDependentIsNotNull))
6791 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006792
Jordan Roseeec207f2012-07-17 17:46:44 +00006793 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006794 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006795 enum {
6796 LK_Array,
6797 LK_Dictionary,
6798 LK_Numeric,
6799 LK_Boxed,
6800 LK_String
6801 } LiteralKind;
6802
Jordan Rose9f63a452012-06-08 21:14:25 +00006803 switch (Literal->getStmtClass()) {
6804 case Stmt::ObjCStringLiteralClass:
6805 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006806 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006807 break;
6808 case Stmt::ObjCArrayLiteralClass:
6809 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006810 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006811 break;
6812 case Stmt::ObjCDictionaryLiteralClass:
6813 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006814 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006815 break;
6816 case Stmt::ObjCBoxedExprClass: {
6817 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6818 switch (Inner->getStmtClass()) {
6819 case Stmt::IntegerLiteralClass:
6820 case Stmt::FloatingLiteralClass:
6821 case Stmt::CharacterLiteralClass:
6822 case Stmt::ObjCBoolLiteralExprClass:
6823 case Stmt::CXXBoolLiteralExprClass:
6824 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006825 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006826 break;
6827 case Stmt::ImplicitCastExprClass: {
6828 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6829 // Boolean literals can be represented by implicit casts.
6830 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006831 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006832 break;
6833 }
6834 // FALLTHROUGH
6835 }
6836 default:
6837 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006838 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006839 break;
6840 }
6841 break;
6842 }
6843 default:
6844 llvm_unreachable("Unknown Objective-C object literal kind");
6845 }
6846
Jordan Roseeec207f2012-07-17 17:46:44 +00006847 if (LiteralKind == LK_String)
6848 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6849 << Literal->getSourceRange();
6850 else
6851 S.Diag(Loc, diag::warn_objc_literal_comparison)
6852 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006853
Jordan Rose8d872ca2012-07-17 17:46:40 +00006854 if (BinaryOperator::isEqualityOp(Opc) &&
6855 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6856 SourceLocation Start = LHS.get()->getLocStart();
6857 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6858 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006859
Jordan Rose8d872ca2012-07-17 17:46:40 +00006860 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6861 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6862 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6863 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006864 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006865}
6866
Douglas Gregor0c6db942009-05-04 06:07:12 +00006867// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006868QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006869 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006870 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006871 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6872
John McCall2de56d12010-08-25 11:45:40 +00006873 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006874
Chris Lattner02dd4b12009-12-05 05:40:13 +00006875 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006876 if (LHS.get()->getType()->isVectorType() ||
6877 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006878 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006879
Richard Trieuf1775fb2011-09-06 21:43:51 +00006880 QualType LHSType = LHS.get()->getType();
6881 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006882
Richard Trieuf1775fb2011-09-06 21:43:51 +00006883 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6884 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006885
Richard Trieuf1775fb2011-09-06 21:43:51 +00006886 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006887
Richard Trieuf1775fb2011-09-06 21:43:51 +00006888 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006889 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006890 !LHS.get()->getLocStart().isMacroID() &&
6891 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006892 // For non-floating point types, check for self-comparisons of the form
6893 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6894 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006895 //
6896 // NOTE: Don't warn about comparison expressions resulting from macro
6897 // expansion. Also don't warn about comparisons which are only self
6898 // comparisons within a template specialization. The warnings should catch
6899 // obvious cases in the definition of the template anyways. The idea is to
6900 // warn when the typed comparison operator will always evaluate to the same
6901 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006902 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006903 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006904 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006905 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006906 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006907 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006908 << (Opc == BO_EQ
6909 || Opc == BO_LE
6910 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006911 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006912 !DRL->getDecl()->getType()->isReferenceType() &&
6913 !DRR->getDecl()->getType()->isReferenceType()) {
6914 // what is it always going to eval to?
6915 char always_evals_to;
6916 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006917 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006918 always_evals_to = 0; // false
6919 break;
John McCall2de56d12010-08-25 11:45:40 +00006920 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006921 always_evals_to = 1; // true
6922 break;
6923 default:
6924 // best we can say is 'a constant'
6925 always_evals_to = 2; // e.g. array1 <= array2
6926 break;
6927 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006928 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006929 << 1 // array
6930 << always_evals_to);
6931 }
6932 }
Chandler Carruth99919472010-07-10 12:30:03 +00006933 }
Mike Stump1eb44332009-09-09 15:08:12 +00006934
Chris Lattner55660a72009-03-08 19:39:53 +00006935 if (isa<CastExpr>(LHSStripped))
6936 LHSStripped = LHSStripped->IgnoreParenCasts();
6937 if (isa<CastExpr>(RHSStripped))
6938 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006939
Chris Lattner55660a72009-03-08 19:39:53 +00006940 // Warn about comparisons against a string constant (unless the other
6941 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006942 Expr *literalString = 0;
6943 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006944 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006945 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006946 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006947 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006948 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006949 } else if ((isa<StringLiteral>(RHSStripped) ||
6950 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006951 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006952 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006953 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006954 literalStringStripped = RHSStripped;
6955 }
6956
6957 if (literalString) {
6958 std::string resultComparison;
6959 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006960 case BO_LT: resultComparison = ") < 0"; break;
6961 case BO_GT: resultComparison = ") > 0"; break;
6962 case BO_LE: resultComparison = ") <= 0"; break;
6963 case BO_GE: resultComparison = ") >= 0"; break;
6964 case BO_EQ: resultComparison = ") == 0"; break;
6965 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006966 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006967 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006968
Ted Kremenek351ba912011-02-23 01:52:04 +00006969 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006970 PDiag(diag::warn_stringcompare)
6971 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006972 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006973 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006974 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006975
Douglas Gregord64fdd02010-06-08 19:50:34 +00006976 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006977 if (LHS.get()->getType()->isArithmeticType() &&
6978 RHS.get()->getType()->isArithmeticType()) {
6979 UsualArithmeticConversions(LHS, RHS);
6980 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006981 return QualType();
6982 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006983 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006984 LHS = UsualUnaryConversions(LHS.take());
6985 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006986 return QualType();
6987
Richard Trieuf1775fb2011-09-06 21:43:51 +00006988 RHS = UsualUnaryConversions(RHS.take());
6989 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006990 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006991 }
6992
Richard Trieuf1775fb2011-09-06 21:43:51 +00006993 LHSType = LHS.get()->getType();
6994 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006995
Douglas Gregor447b69e2008-11-19 03:25:36 +00006996 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006997 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006998
Richard Trieuccd891a2011-09-09 01:45:06 +00006999 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007000 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007001 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007002 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007003 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007004 if (LHSType->hasFloatingRepresentation())
7005 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007006
Richard Trieuf1775fb2011-09-06 21:43:51 +00007007 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007008 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007009 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007010
Richard Trieuf1775fb2011-09-06 21:43:51 +00007011 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007012 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007013 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007014 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007015
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007016 // All of the following pointer-related warnings are GCC extensions, except
7017 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007018 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007019 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007020 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007021 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007022 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007023
David Blaikie4e4d0842012-03-11 07:00:24 +00007024 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007025 if (LCanPointeeTy == RCanPointeeTy)
7026 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007027 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007028 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7029 // Valid unless comparison between non-null pointer and function pointer
7030 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007031 // In a SFINAE context, we treat this as a hard error to maintain
7032 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007033 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7034 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007035 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007036 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007037
7038 if (isSFINAEContext())
7039 return QualType();
7040
Richard Trieuf1775fb2011-09-06 21:43:51 +00007041 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007042 return ResultTy;
7043 }
7044 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007045
Richard Trieuf1775fb2011-09-06 21:43:51 +00007046 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007047 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007048 else
7049 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007050 }
Eli Friedman3075e762009-08-23 00:27:47 +00007051 // C99 6.5.9p2 and C99 6.5.8p2
7052 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7053 RCanPointeeTy.getUnqualifiedType())) {
7054 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007055 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007056 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007057 << LHSType << RHSType << LHS.get()->getSourceRange()
7058 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007059 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007060 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007061 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7062 // Valid unless comparison between non-null pointer and function pointer
7063 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007064 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007065 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007066 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007067 } else {
7068 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007069 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007070 }
John McCall34d6f932011-03-11 04:25:25 +00007071 if (LCanPointeeTy != RCanPointeeTy) {
7072 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007073 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007074 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007075 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007076 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007077 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007078 }
Mike Stump1eb44332009-09-09 15:08:12 +00007079
David Blaikie4e4d0842012-03-11 07:00:24 +00007080 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007081 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007082 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007083 return ResultTy;
7084
Mike Stump1eb44332009-09-09 15:08:12 +00007085 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007086 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007087 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007088 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007089 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007090 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7091 RHS = ImpCastExprToType(RHS.take(), LHSType,
7092 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007093 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007094 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007095 return ResultTy;
7096 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007097 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007098 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007099 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007100 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7101 LHS = ImpCastExprToType(LHS.take(), RHSType,
7102 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007103 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007104 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007105 return ResultTy;
7106 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007107
7108 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007109 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007110 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7111 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007112 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007113 else
7114 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007115 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007116
7117 // Handle scoped enumeration types specifically, since they don't promote
7118 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007119 if (LHS.get()->getType()->isEnumeralType() &&
7120 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7121 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007122 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007123 }
Mike Stump1eb44332009-09-09 15:08:12 +00007124
Steve Naroff1c7d0672008-09-04 15:10:53 +00007125 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007126 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007127 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007128 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7129 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007130
Steve Naroff1c7d0672008-09-04 15:10:53 +00007131 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007132 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007133 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007134 << LHSType << RHSType << LHS.get()->getSourceRange()
7135 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007136 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007137 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007138 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007139 }
John Wiegley429bb272011-04-08 18:41:53 +00007140
Steve Naroff59f53942008-09-28 01:11:11 +00007141 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007142 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007143 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7144 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007145 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007146 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007147 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007148 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007149 ->getPointeeType()->isVoidType())))
7150 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007151 << LHSType << RHSType << LHS.get()->getSourceRange()
7152 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007153 }
John McCall34d6f932011-03-11 04:25:25 +00007154 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007155 LHS = ImpCastExprToType(LHS.take(), RHSType,
7156 RHSType->isPointerType() ? CK_BitCast
7157 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007158 else
John McCall1d9b3b22011-09-09 05:25:32 +00007159 RHS = ImpCastExprToType(RHS.take(), LHSType,
7160 LHSType->isPointerType() ? CK_BitCast
7161 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007162 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007163 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007164
Richard Trieuf1775fb2011-09-06 21:43:51 +00007165 if (LHSType->isObjCObjectPointerType() ||
7166 RHSType->isObjCObjectPointerType()) {
7167 const PointerType *LPT = LHSType->getAs<PointerType>();
7168 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007169 if (LPT || RPT) {
7170 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7171 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007172
Steve Naroffa8069f12008-11-17 19:49:16 +00007173 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007174 !Context.typesAreCompatible(LHSType, RHSType)) {
7175 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007176 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007177 }
John McCall34d6f932011-03-11 04:25:25 +00007178 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007179 LHS = ImpCastExprToType(LHS.take(), RHSType,
7180 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007181 else
John McCall1d9b3b22011-09-09 05:25:32 +00007182 RHS = ImpCastExprToType(RHS.take(), LHSType,
7183 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007184 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007185 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007186 if (LHSType->isObjCObjectPointerType() &&
7187 RHSType->isObjCObjectPointerType()) {
7188 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7189 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007190 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007191 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007192 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007193
John McCall34d6f932011-03-11 04:25:25 +00007194 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007195 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007196 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007197 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007198 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007199 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007200 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007201 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7202 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007203 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007204 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00007205 if ((LHSIsNull && LHSType->isIntegerType()) ||
7206 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007207 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007208 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007209 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007210 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007211 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007212 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7213 isError = true;
7214 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007215 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007216
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007217 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007218 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007219 << LHSType << RHSType << LHS.get()->getSourceRange()
7220 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007221 if (isError)
7222 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007223 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007224
Richard Trieuf1775fb2011-09-06 21:43:51 +00007225 if (LHSType->isIntegerType())
7226 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007227 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007228 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007229 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007230 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007231 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007232 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007233
Steve Naroff39218df2008-09-04 16:56:14 +00007234 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007235 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007236 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7237 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007238 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007239 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007240 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007241 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7242 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007243 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007244 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007245
Richard Trieuf1775fb2011-09-06 21:43:51 +00007246 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007247}
7248
Tanya Lattner4f692c22012-01-16 21:02:28 +00007249
7250// Return a signed type that is of identical size and number of elements.
7251// For floating point vectors, return an integer type of identical size
7252// and number of elements.
7253QualType Sema::GetSignedVectorType(QualType V) {
7254 const VectorType *VTy = V->getAs<VectorType>();
7255 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7256 if (TypeSize == Context.getTypeSize(Context.CharTy))
7257 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7258 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7259 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7260 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7261 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7262 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7263 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7264 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7265 "Unhandled vector element size in vector compare");
7266 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7267}
7268
Nate Begemanbe2341d2008-07-14 18:02:46 +00007269/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007270/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007271/// like a scalar comparison, a vector comparison produces a vector of integer
7272/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007273QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007274 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007275 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007276 // Check to make sure we're operating on vectors of the same type and width,
7277 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007278 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007279 if (vType.isNull())
7280 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007281
Richard Trieu9f60dee2011-09-07 01:19:57 +00007282 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007283
Anton Yartsev7870b132011-03-27 15:36:07 +00007284 // If AltiVec, the comparison results in a numeric type, i.e.
7285 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007286 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007287 return Context.getLogicalOperationType();
7288
Nate Begemanbe2341d2008-07-14 18:02:46 +00007289 // For non-floating point types, check for self-comparisons of the form
7290 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7291 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007292 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007293 if (DeclRefExpr* DRL
7294 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7295 if (DeclRefExpr* DRR
7296 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007297 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007298 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007299 PDiag(diag::warn_comparison_always)
7300 << 0 // self-
7301 << 2 // "a constant"
7302 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007303 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007304
Nate Begemanbe2341d2008-07-14 18:02:46 +00007305 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007306 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007307 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007308 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007309 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007310
7311 // Return a signed type for the vector.
7312 return GetSignedVectorType(LHSType);
7313}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007314
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007315QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7316 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007317 // Ensure that either both operands are of the same vector type, or
7318 // one operand is of a vector type and the other is of its element type.
7319 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7320 if (vType.isNull() || vType->isFloatingType())
7321 return InvalidOperands(Loc, LHS, RHS);
7322
7323 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007324}
7325
Reid Spencer5f016e22007-07-11 17:01:13 +00007326inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007327 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007328 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7329
Richard Trieu9f60dee2011-09-07 01:19:57 +00007330 if (LHS.get()->getType()->isVectorType() ||
7331 RHS.get()->getType()->isVectorType()) {
7332 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7333 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007334 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007335
Richard Trieu9f60dee2011-09-07 01:19:57 +00007336 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007337 }
Steve Naroff90045e82007-07-13 23:32:42 +00007338
Richard Trieu9f60dee2011-09-07 01:19:57 +00007339 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7340 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007341 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007342 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007343 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007344 LHS = LHSResult.take();
7345 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007346
Eli Friedman860a3192012-06-16 02:19:17 +00007347 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007348 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007349 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007350}
7351
7352inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007353 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007354
Tanya Lattner4f692c22012-01-16 21:02:28 +00007355 // Check vector operands differently.
7356 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7357 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7358
Chris Lattner90a8f272010-07-13 19:41:32 +00007359 // Diagnose cases where the user write a logical and/or but probably meant a
7360 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7361 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007362 if (LHS.get()->getType()->isIntegerType() &&
7363 !LHS.get()->getType()->isBooleanType() &&
7364 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007365 // Don't warn in macros or template instantiations.
7366 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007367 // If the RHS can be constant folded, and if it constant folds to something
7368 // that isn't 0 or 1 (which indicate a potential logical operation that
7369 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007370 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007371 llvm::APSInt Result;
7372 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007373 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007374 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007375 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007376 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007377 << (Opc == BO_LAnd ? "&&" : "||");
7378 // Suggest replacing the logical operator with the bitwise version
7379 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7380 << (Opc == BO_LAnd ? "&" : "|")
7381 << FixItHint::CreateReplacement(SourceRange(
7382 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007383 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007384 Opc == BO_LAnd ? "&" : "|");
7385 if (Opc == BO_LAnd)
7386 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7387 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7388 << FixItHint::CreateRemoval(
7389 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007390 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007391 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007392 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007393 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007394 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007395 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007396
David Blaikie4e4d0842012-03-11 07:00:24 +00007397 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007398 LHS = UsualUnaryConversions(LHS.take());
7399 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007400 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007401
Richard Trieu9f60dee2011-09-07 01:19:57 +00007402 RHS = UsualUnaryConversions(RHS.take());
7403 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007404 return QualType();
7405
Richard Trieu9f60dee2011-09-07 01:19:57 +00007406 if (!LHS.get()->getType()->isScalarType() ||
7407 !RHS.get()->getType()->isScalarType())
7408 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007409
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007410 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007411 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007412
John McCall75f7c0f2010-06-04 00:29:51 +00007413 // The following is safe because we only use this method for
7414 // non-overloadable operands.
7415
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007416 // C++ [expr.log.and]p1
7417 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007418 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007419 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7420 if (LHSRes.isInvalid())
7421 return InvalidOperands(Loc, LHS, RHS);
7422 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00007423
Richard Trieu9f60dee2011-09-07 01:19:57 +00007424 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7425 if (RHSRes.isInvalid())
7426 return InvalidOperands(Loc, LHS, RHS);
7427 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007428
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007429 // C++ [expr.log.and]p2
7430 // C++ [expr.log.or]p2
7431 // The result is a bool.
7432 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007433}
7434
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007435/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7436/// is a read-only property; return true if so. A readonly property expression
7437/// depends on various declarations and thus must be treated specially.
7438///
Mike Stump1eb44332009-09-09 15:08:12 +00007439static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007440 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7441 if (!PropExpr) return false;
7442 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007443
John McCall3c3b7f92011-10-25 17:37:35 +00007444 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7445 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007446 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007447 PropExpr->getBase()->getType();
7448
John McCall3c3b7f92011-10-25 17:37:35 +00007449 if (const ObjCObjectPointerType *OPT =
7450 BaseType->getAsObjCInterfacePointerType())
7451 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7452 if (S.isPropertyReadonly(PDecl, IFace))
7453 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007454 return false;
7455}
7456
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007457static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007458 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7459 if (!ME) return false;
7460 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7461 ObjCMessageExpr *Base =
7462 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7463 if (!Base) return false;
7464 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007465}
7466
John McCall78dae242012-03-13 00:37:01 +00007467/// Is the given expression (which must be 'const') a reference to a
7468/// variable which was originally non-const, but which has become
7469/// 'const' due to being captured within a block?
7470enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7471static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7472 assert(E->isLValue() && E->getType().isConstQualified());
7473 E = E->IgnoreParens();
7474
7475 // Must be a reference to a declaration from an enclosing scope.
7476 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7477 if (!DRE) return NCCK_None;
7478 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7479
7480 // The declaration must be a variable which is not declared 'const'.
7481 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7482 if (!var) return NCCK_None;
7483 if (var->getType().isConstQualified()) return NCCK_None;
7484 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7485
7486 // Decide whether the first capture was for a block or a lambda.
7487 DeclContext *DC = S.CurContext;
7488 while (DC->getParent() != var->getDeclContext())
7489 DC = DC->getParent();
7490 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7491}
7492
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007493/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7494/// emit an error and return true. If so, return false.
7495static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007496 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007497 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007498 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007499 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007500 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7501 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007502 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7503 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007504 if (IsLV == Expr::MLV_Valid)
7505 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007506
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007507 unsigned Diag = 0;
7508 bool NeedType = false;
7509 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007510 case Expr::MLV_ConstQualified:
7511 Diag = diag::err_typecheck_assign_const;
7512
John McCall78dae242012-03-13 00:37:01 +00007513 // Use a specialized diagnostic when we're assigning to an object
7514 // from an enclosing function or block.
7515 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7516 if (NCCK == NCCK_Block)
7517 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7518 else
7519 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7520 break;
7521 }
7522
John McCall7acddac2011-06-17 06:42:21 +00007523 // In ARC, use some specialized diagnostics for occasions where we
7524 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007525 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007526 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7527 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7528 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7529
John McCall7acddac2011-06-17 06:42:21 +00007530 // Use the normal diagnostic if it's pseudo-__strong but the
7531 // user actually wrote 'const'.
7532 if (var->isARCPseudoStrong() &&
7533 (!var->getTypeSourceInfo() ||
7534 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7535 // There are two pseudo-strong cases:
7536 // - self
John McCallf85e1932011-06-15 23:02:42 +00007537 ObjCMethodDecl *method = S.getCurMethodDecl();
7538 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007539 Diag = method->isClassMethod()
7540 ? diag::err_typecheck_arc_assign_self_class_method
7541 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007542
7543 // - fast enumeration variables
7544 else
John McCallf85e1932011-06-15 23:02:42 +00007545 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007546
John McCallf85e1932011-06-15 23:02:42 +00007547 SourceRange Assign;
7548 if (Loc != OrigLoc)
7549 Assign = SourceRange(OrigLoc, OrigLoc);
7550 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7551 // We need to preserve the AST regardless, so migration tool
7552 // can do its job.
7553 return false;
7554 }
7555 }
7556 }
7557
7558 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007559 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007560 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007561 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7562 NeedType = true;
7563 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007564 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007565 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7566 NeedType = true;
7567 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007568 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007569 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7570 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007571 case Expr::MLV_Valid:
7572 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007573 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007574 case Expr::MLV_MemberFunction:
7575 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007576 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7577 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007578 case Expr::MLV_IncompleteType:
7579 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007580 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007581 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007582 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007583 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7584 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007585 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007586 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007587 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007588 case Expr::MLV_InvalidMessageExpression:
7589 Diag = diag::error_readonly_message_assignment;
7590 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007591 case Expr::MLV_SubObjCPropertySetting:
7592 Diag = diag::error_no_subobject_property_setting;
7593 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007594 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007595
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007596 SourceRange Assign;
7597 if (Loc != OrigLoc)
7598 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007599 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007600 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007601 else
Mike Stump1eb44332009-09-09 15:08:12 +00007602 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007603 return true;
7604}
7605
Nico Weber7c81b432012-07-03 02:03:06 +00007606static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7607 SourceLocation Loc,
7608 Sema &Sema) {
7609 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007610 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7611 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7612 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7613 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007614 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007615 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007616
Nico Weber7c81b432012-07-03 02:03:06 +00007617 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007618 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7619 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7620 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7621 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7622 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7623 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007624 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007625 }
7626}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007627
7628// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007629QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007630 SourceLocation Loc,
7631 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007632 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7633
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007634 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007635 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007636 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007637
Richard Trieu268942b2011-09-07 01:33:52 +00007638 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007639 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7640 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007641 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007642 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007643 Expr *RHSCheck = RHS.get();
7644
Nico Weber7c81b432012-07-03 02:03:06 +00007645 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007646
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007647 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007648 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007649 if (RHS.isInvalid())
7650 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007651 // Special case of NSObject attributes on c-style pointer types.
7652 if (ConvTy == IncompatiblePointer &&
7653 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007654 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007655 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007656 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007657 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007658
John McCallf89e55a2010-11-18 06:31:45 +00007659 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007660 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007661 Diag(Loc, diag::err_objc_object_assignment)
7662 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007663
Chris Lattner2c156472008-08-21 18:04:13 +00007664 // If the RHS is a unary plus or minus, check to see if they = and + are
7665 // right next to each other. If so, the user may have typo'd "x =+ 4"
7666 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007667 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7668 RHSCheck = ICE->getSubExpr();
7669 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007670 if ((UO->getOpcode() == UO_Plus ||
7671 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007672 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007673 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007674 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007675 // And there is a space or other character before the subexpr of the
7676 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007677 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007678 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007679 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007680 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007681 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007682 }
Chris Lattner2c156472008-08-21 18:04:13 +00007683 }
John McCallf85e1932011-06-15 23:02:42 +00007684
7685 if (ConvTy == Compatible) {
7686 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007687 checkRetainCycles(LHSExpr, RHS.get());
David Blaikie4e4d0842012-03-11 07:00:24 +00007688 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007689 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007690 }
Chris Lattner2c156472008-08-21 18:04:13 +00007691 } else {
7692 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007693 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007694 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007695
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007696 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007697 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007698 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007699
Richard Trieu268942b2011-09-07 01:33:52 +00007700 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007701
Reid Spencer5f016e22007-07-11 17:01:13 +00007702 // C99 6.5.16p3: The type of an assignment expression is the type of the
7703 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007704 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007705 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7706 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007707 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007708 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007709 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007710 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007711}
7712
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007713// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007714static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007715 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007716 LHS = S.CheckPlaceholderExpr(LHS.take());
7717 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007718 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007719 return QualType();
7720
John McCallcf2e5062010-10-12 07:14:40 +00007721 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7722 // operands, but not unary promotions.
7723 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007724
John McCallf6a16482010-12-04 03:47:34 +00007725 // So we treat the LHS as a ignored value, and in C++ we allow the
7726 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007727 LHS = S.IgnoredValueConversions(LHS.take());
7728 if (LHS.isInvalid())
7729 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007730
Eli Friedmana6115062012-05-24 00:47:05 +00007731 S.DiagnoseUnusedExprResult(LHS.get());
7732
David Blaikie4e4d0842012-03-11 07:00:24 +00007733 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007734 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7735 if (RHS.isInvalid())
7736 return QualType();
7737 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007738 S.RequireCompleteType(Loc, RHS.get()->getType(),
7739 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007740 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007741
John Wiegley429bb272011-04-08 18:41:53 +00007742 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007743}
7744
Steve Naroff49b45262007-07-13 16:58:59 +00007745/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7746/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007747static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7748 ExprValueKind &VK,
7749 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007750 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007751 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007752 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007753
Chris Lattner3528d352008-11-21 07:05:48 +00007754 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007755 // Atomic types can be used for increment / decrement where the non-atomic
7756 // versions can, so ignore the _Atomic() specifier for the purpose of
7757 // checking.
7758 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7759 ResType = ResAtomicType->getValueType();
7760
Chris Lattner3528d352008-11-21 07:05:48 +00007761 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007762
David Blaikie4e4d0842012-03-11 07:00:24 +00007763 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007764 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007765 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007766 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007767 return QualType();
7768 }
7769 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007770 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007771 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007772 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007773 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007774 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007775 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007776 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007777 } else if (ResType->isObjCObjectPointerType()) {
7778 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7779 // Otherwise, we just need a complete type.
7780 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7781 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7782 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007783 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007784 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007785 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007786 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007787 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007788 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007789 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007790 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007791 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007792 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007793 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007794 } else {
John McCall09431682010-11-18 19:01:18 +00007795 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007796 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007797 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007798 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007799 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007800 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007801 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007802 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007803 // In C++, a prefix increment is the same type as the operand. Otherwise
7804 // (in C or with postfix), the increment is the unqualified type of the
7805 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007806 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007807 VK = VK_LValue;
7808 return ResType;
7809 } else {
7810 VK = VK_RValue;
7811 return ResType.getUnqualifiedType();
7812 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007813}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007814
7815
Anders Carlsson369dee42008-02-01 07:15:58 +00007816/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007817/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007818/// where the declaration is needed for type checking. We only need to
7819/// handle cases when the expression references a function designator
7820/// or is an lvalue. Here are some examples:
7821/// - &(x) => x
7822/// - &*****f => f for f a function designator.
7823/// - &s.xx => s
7824/// - &s.zz[1].yy -> s, if zz is an array
7825/// - *(x + 1) -> x, if x is an array
7826/// - &"123"[2] -> 0
7827/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007828static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007829 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007830 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007831 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007832 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007833 // If this is an arrow operator, the address is an offset from
7834 // the base's value, so the object the base refers to is
7835 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007836 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007837 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007838 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007839 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007840 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007841 // FIXME: This code shouldn't be necessary! We should catch the implicit
7842 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007843 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7844 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7845 if (ICE->getSubExpr()->getType()->isArrayType())
7846 return getPrimaryDecl(ICE->getSubExpr());
7847 }
7848 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007849 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007850 case Stmt::UnaryOperatorClass: {
7851 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007852
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007853 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007854 case UO_Real:
7855 case UO_Imag:
7856 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007857 return getPrimaryDecl(UO->getSubExpr());
7858 default:
7859 return 0;
7860 }
7861 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007862 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007863 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007864 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007865 // If the result of an implicit cast is an l-value, we care about
7866 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007867 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007868 default:
7869 return 0;
7870 }
7871}
7872
Richard Trieu5520f232011-09-07 21:46:33 +00007873namespace {
7874 enum {
7875 AO_Bit_Field = 0,
7876 AO_Vector_Element = 1,
7877 AO_Property_Expansion = 2,
7878 AO_Register_Variable = 3,
7879 AO_No_Error = 4
7880 };
7881}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007882/// \brief Diagnose invalid operand for address of operations.
7883///
7884/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007885static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7886 Expr *E, unsigned Type) {
7887 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7888}
7889
Reid Spencer5f016e22007-07-11 17:01:13 +00007890/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007891/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007892/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007893/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007894/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007895/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007896/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007897static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007898 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007899 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7900 if (PTy->getKind() == BuiltinType::Overload) {
7901 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7902 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7903 << OrigOp.get()->getSourceRange();
7904 return QualType();
7905 }
7906
7907 return S.Context.OverloadTy;
7908 }
7909
7910 if (PTy->getKind() == BuiltinType::UnknownAny)
7911 return S.Context.UnknownAnyTy;
7912
7913 if (PTy->getKind() == BuiltinType::BoundMember) {
7914 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7915 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007916 return QualType();
7917 }
John McCall3c3b7f92011-10-25 17:37:35 +00007918
7919 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7920 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007921 }
John McCall9c72c602010-08-27 09:08:28 +00007922
John McCall3c3b7f92011-10-25 17:37:35 +00007923 if (OrigOp.get()->isTypeDependent())
7924 return S.Context.DependentTy;
7925
7926 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007927
John McCall9c72c602010-08-27 09:08:28 +00007928 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007929 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007930
David Blaikie4e4d0842012-03-11 07:00:24 +00007931 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007932 // Implement C99-only parts of addressof rules.
7933 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007934 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007935 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7936 // (assuming the deref expression is valid).
7937 return uOp->getSubExpr()->getType();
7938 }
7939 // Technically, there should be a check for array subscript
7940 // expressions here, but the result of one is always an lvalue anyway.
7941 }
John McCall5808ce42011-02-03 08:15:49 +00007942 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007943 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007944 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007945
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007946 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007947 bool sfinae = S.isSFINAEContext();
7948 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7949 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007950 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007951 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007952 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007953 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007954 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007955 } else if (lval == Expr::LV_MemberFunction) {
7956 // If it's an instance method, make a member pointer.
7957 // The expression must have exactly the form &A::foo.
7958
7959 // If the underlying expression isn't a decl ref, give up.
7960 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007961 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007962 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007963 return QualType();
7964 }
7965 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7966 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7967
7968 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007969 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007970 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007971 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007972
7973 // The method was named without a qualifier.
7974 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007975 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007976 << op->getSourceRange();
7977 }
7978
John McCall09431682010-11-18 19:01:18 +00007979 return S.Context.getMemberPointerType(op->getType(),
7980 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007981 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007982 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007983 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007984 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007985 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007986 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007987 AddressOfError = AO_Property_Expansion;
7988 } else {
7989 // FIXME: emit more specific diag...
7990 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7991 << op->getSourceRange();
7992 return QualType();
7993 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007994 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007995 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007996 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007997 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007998 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007999 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008000 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008001 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008002 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008003 // with the register storage-class specifier.
8004 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008005 // in C++ it is not error to take address of a register
8006 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008007 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008008 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008009 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008010 }
John McCallba135432009-11-21 08:51:07 +00008011 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008012 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008013 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008014 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008015 // Could be a pointer to member, though, if there is an explicit
8016 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008017 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008018 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008019 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008020 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008021 S.Diag(OpLoc,
8022 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008023 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008024 return QualType();
8025 }
Mike Stump1eb44332009-09-09 15:08:12 +00008026
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008027 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8028 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008029 return S.Context.getMemberPointerType(op->getType(),
8030 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008031 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008032 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008033 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008034 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008035 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008036
Richard Trieu5520f232011-09-07 21:46:33 +00008037 if (AddressOfError != AO_No_Error) {
8038 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8039 return QualType();
8040 }
8041
Eli Friedman441cf102009-05-16 23:27:50 +00008042 if (lval == Expr::LV_IncompleteVoidType) {
8043 // Taking the address of a void variable is technically illegal, but we
8044 // allow it in cases which are otherwise valid.
8045 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008046 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008047 }
8048
Reid Spencer5f016e22007-07-11 17:01:13 +00008049 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008050 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008051 return S.Context.getObjCObjectPointerType(op->getType());
8052 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008053}
8054
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008055/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008056static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8057 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008058 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008059 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008060
John Wiegley429bb272011-04-08 18:41:53 +00008061 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8062 if (ConvResult.isInvalid())
8063 return QualType();
8064 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008065 QualType OpTy = Op->getType();
8066 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008067
8068 if (isa<CXXReinterpretCastExpr>(Op)) {
8069 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8070 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8071 Op->getSourceRange());
8072 }
8073
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008074 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8075 // is an incomplete type or void. It would be possible to warn about
8076 // dereferencing a void pointer, but it's completely well-defined, and such a
8077 // warning is unlikely to catch any mistakes.
8078 if (const PointerType *PT = OpTy->getAs<PointerType>())
8079 Result = PT->getPointeeType();
8080 else if (const ObjCObjectPointerType *OPT =
8081 OpTy->getAs<ObjCObjectPointerType>())
8082 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008083 else {
John McCallfb8721c2011-04-10 19:13:55 +00008084 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008085 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008086 if (PR.take() != Op)
8087 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008088 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008089
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008090 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008091 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008092 << OpTy << Op->getSourceRange();
8093 return QualType();
8094 }
John McCall09431682010-11-18 19:01:18 +00008095
8096 // Dereferences are usually l-values...
8097 VK = VK_LValue;
8098
8099 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008100 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008101 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008102
8103 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008104}
8105
John McCall2de56d12010-08-25 11:45:40 +00008106static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008107 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008108 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008109 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008110 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008111 case tok::periodstar: Opc = BO_PtrMemD; break;
8112 case tok::arrowstar: Opc = BO_PtrMemI; break;
8113 case tok::star: Opc = BO_Mul; break;
8114 case tok::slash: Opc = BO_Div; break;
8115 case tok::percent: Opc = BO_Rem; break;
8116 case tok::plus: Opc = BO_Add; break;
8117 case tok::minus: Opc = BO_Sub; break;
8118 case tok::lessless: Opc = BO_Shl; break;
8119 case tok::greatergreater: Opc = BO_Shr; break;
8120 case tok::lessequal: Opc = BO_LE; break;
8121 case tok::less: Opc = BO_LT; break;
8122 case tok::greaterequal: Opc = BO_GE; break;
8123 case tok::greater: Opc = BO_GT; break;
8124 case tok::exclaimequal: Opc = BO_NE; break;
8125 case tok::equalequal: Opc = BO_EQ; break;
8126 case tok::amp: Opc = BO_And; break;
8127 case tok::caret: Opc = BO_Xor; break;
8128 case tok::pipe: Opc = BO_Or; break;
8129 case tok::ampamp: Opc = BO_LAnd; break;
8130 case tok::pipepipe: Opc = BO_LOr; break;
8131 case tok::equal: Opc = BO_Assign; break;
8132 case tok::starequal: Opc = BO_MulAssign; break;
8133 case tok::slashequal: Opc = BO_DivAssign; break;
8134 case tok::percentequal: Opc = BO_RemAssign; break;
8135 case tok::plusequal: Opc = BO_AddAssign; break;
8136 case tok::minusequal: Opc = BO_SubAssign; break;
8137 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8138 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8139 case tok::ampequal: Opc = BO_AndAssign; break;
8140 case tok::caretequal: Opc = BO_XorAssign; break;
8141 case tok::pipeequal: Opc = BO_OrAssign; break;
8142 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008143 }
8144 return Opc;
8145}
8146
John McCall2de56d12010-08-25 11:45:40 +00008147static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008148 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008149 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008150 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008151 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008152 case tok::plusplus: Opc = UO_PreInc; break;
8153 case tok::minusminus: Opc = UO_PreDec; break;
8154 case tok::amp: Opc = UO_AddrOf; break;
8155 case tok::star: Opc = UO_Deref; break;
8156 case tok::plus: Opc = UO_Plus; break;
8157 case tok::minus: Opc = UO_Minus; break;
8158 case tok::tilde: Opc = UO_Not; break;
8159 case tok::exclaim: Opc = UO_LNot; break;
8160 case tok::kw___real: Opc = UO_Real; break;
8161 case tok::kw___imag: Opc = UO_Imag; break;
8162 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008163 }
8164 return Opc;
8165}
8166
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008167/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8168/// This warning is only emitted for builtin assignment operations. It is also
8169/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008170static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008171 SourceLocation OpLoc) {
8172 if (!S.ActiveTemplateInstantiations.empty())
8173 return;
8174 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8175 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008176 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8177 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8178 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8179 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8180 if (!LHSDeclRef || !RHSDeclRef ||
8181 LHSDeclRef->getLocation().isMacroID() ||
8182 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008183 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008184 const ValueDecl *LHSDecl =
8185 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8186 const ValueDecl *RHSDecl =
8187 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8188 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008189 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008190 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008191 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008192 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008193 if (RefTy->getPointeeType().isVolatileQualified())
8194 return;
8195
8196 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008197 << LHSDeclRef->getType()
8198 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008199}
8200
Douglas Gregoreaebc752008-11-06 23:29:22 +00008201/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8202/// operator @p Opc at location @c TokLoc. This routine only supports
8203/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008204ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008205 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008206 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008207 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008208 // The syntax only allows initializer lists on the RHS of assignment,
8209 // so we don't need to worry about accepting invalid code for
8210 // non-assignment operators.
8211 // C++11 5.17p9:
8212 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8213 // of x = {} is x = T().
8214 InitializationKind Kind =
8215 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8216 InitializedEntity Entity =
8217 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8218 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8219 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8220 MultiExprArg(&RHSExpr, 1));
8221 if (Init.isInvalid())
8222 return Init;
8223 RHSExpr = Init.take();
8224 }
8225
Richard Trieu78ea78b2011-09-07 01:49:20 +00008226 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008227 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008228 // The following two variables are used for compound assignment operators
8229 QualType CompLHSTy; // Type of LHS after promotions for computation
8230 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008231 ExprValueKind VK = VK_RValue;
8232 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008233
8234 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008235 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008236 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008237 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008238 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8239 VK = LHS.get()->getValueKind();
8240 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008241 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008242 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008243 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008244 break;
John McCall2de56d12010-08-25 11:45:40 +00008245 case BO_PtrMemD:
8246 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008247 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008248 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008249 break;
John McCall2de56d12010-08-25 11:45:40 +00008250 case BO_Mul:
8251 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008252 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008253 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008254 break;
John McCall2de56d12010-08-25 11:45:40 +00008255 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008256 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008257 break;
John McCall2de56d12010-08-25 11:45:40 +00008258 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008259 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008260 break;
John McCall2de56d12010-08-25 11:45:40 +00008261 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008262 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008263 break;
John McCall2de56d12010-08-25 11:45:40 +00008264 case BO_Shl:
8265 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008266 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008267 break;
John McCall2de56d12010-08-25 11:45:40 +00008268 case BO_LE:
8269 case BO_LT:
8270 case BO_GE:
8271 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008272 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008273 break;
John McCall2de56d12010-08-25 11:45:40 +00008274 case BO_EQ:
8275 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008276 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008277 break;
John McCall2de56d12010-08-25 11:45:40 +00008278 case BO_And:
8279 case BO_Xor:
8280 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008281 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008282 break;
John McCall2de56d12010-08-25 11:45:40 +00008283 case BO_LAnd:
8284 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008285 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008286 break;
John McCall2de56d12010-08-25 11:45:40 +00008287 case BO_MulAssign:
8288 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008289 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008290 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008291 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008292 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8293 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008294 break;
John McCall2de56d12010-08-25 11:45:40 +00008295 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008296 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008297 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008298 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8299 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008300 break;
John McCall2de56d12010-08-25 11:45:40 +00008301 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008302 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008303 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8304 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008305 break;
John McCall2de56d12010-08-25 11:45:40 +00008306 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008307 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8308 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8309 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008310 break;
John McCall2de56d12010-08-25 11:45:40 +00008311 case BO_ShlAssign:
8312 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008313 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008314 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008315 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8316 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008317 break;
John McCall2de56d12010-08-25 11:45:40 +00008318 case BO_AndAssign:
8319 case BO_XorAssign:
8320 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008321 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008322 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008323 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8324 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008325 break;
John McCall2de56d12010-08-25 11:45:40 +00008326 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008327 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008328 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008329 VK = RHS.get()->getValueKind();
8330 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008331 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008332 break;
8333 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008334 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008335 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008336
8337 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008338 CheckArrayAccess(LHS.get());
8339 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008340
Eli Friedmanab3a8522009-03-28 01:22:36 +00008341 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008342 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008343 ResultTy, VK, OK, OpLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00008344 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008345 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008346 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008347 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008348 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008349 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008350 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008351 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008352}
8353
Sebastian Redlaee3c932009-10-27 12:10:02 +00008354/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8355/// operators are mixed in a way that suggests that the programmer forgot that
8356/// comparison operators have higher precedence. The most typical example of
8357/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008358static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008359 SourceLocation OpLoc, Expr *LHSExpr,
8360 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008361 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008362 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8363 RHSopc = static_cast<BinOp::Opcode>(-1);
8364 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8365 LHSopc = BO->getOpcode();
8366 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8367 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008368
8369 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008370 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008371 return;
8372
8373 // Bitwise operations are sometimes used as eager logical ops.
8374 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008375 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8376 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008377 return;
8378
Richard Trieu78ea78b2011-09-07 01:49:20 +00008379 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8380 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008381 if (!isLeftComp && !isRightComp) return;
8382
Richard Trieu78ea78b2011-09-07 01:49:20 +00008383 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8384 OpLoc)
8385 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8386 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8387 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008388 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008389 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8390 RHSExpr->getLocEnd())
8391 : SourceRange(LHSExpr->getLocStart(),
8392 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008393
8394 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8395 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8396 SuggestParentheses(Self, OpLoc,
8397 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008398 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008399 SuggestParentheses(Self, OpLoc,
8400 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8401 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008402}
8403
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008404/// \brief It accepts a '&' expr that is inside a '|' one.
8405/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8406/// in parentheses.
8407static void
8408EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8409 BinaryOperator *Bop) {
8410 assert(Bop->getOpcode() == BO_And);
8411 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8412 << Bop->getSourceRange() << OpLoc;
8413 SuggestParentheses(Self, Bop->getOperatorLoc(),
8414 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8415 Bop->getSourceRange());
8416}
8417
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008418/// \brief It accepts a '&&' expr that is inside a '||' one.
8419/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8420/// in parentheses.
8421static void
8422EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008423 BinaryOperator *Bop) {
8424 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008425 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8426 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008427 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008428 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008429 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008430}
8431
8432/// \brief Returns true if the given expression can be evaluated as a constant
8433/// 'true'.
8434static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8435 bool Res;
8436 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8437}
8438
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008439/// \brief Returns true if the given expression can be evaluated as a constant
8440/// 'false'.
8441static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8442 bool Res;
8443 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8444}
8445
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008446/// \brief Look for '&&' in the left hand of a '||' expr.
8447static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008448 Expr *LHSExpr, Expr *RHSExpr) {
8449 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008450 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008451 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008452 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008453 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008454 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8455 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8456 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8457 } else if (Bop->getOpcode() == BO_LOr) {
8458 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8459 // If it's "a || b && 1 || c" we didn't warn earlier for
8460 // "a || b && 1", but warn now.
8461 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8462 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8463 }
8464 }
8465 }
8466}
8467
8468/// \brief Look for '&&' in the right hand of a '||' expr.
8469static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008470 Expr *LHSExpr, Expr *RHSExpr) {
8471 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008472 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008473 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008474 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008475 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008476 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8477 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8478 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008479 }
8480 }
8481}
8482
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008483/// \brief Look for '&' in the left or right hand of a '|' expr.
8484static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8485 Expr *OrArg) {
8486 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8487 if (Bop->getOpcode() == BO_And)
8488 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8489 }
8490}
8491
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008492/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008493/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008494static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008495 SourceLocation OpLoc, Expr *LHSExpr,
8496 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008497 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008498 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008499 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008500
8501 // Diagnose "arg1 & arg2 | arg3"
8502 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008503 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8504 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008505 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008506
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008507 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8508 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008509 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008510 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8511 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008512 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008513}
8514
Reid Spencer5f016e22007-07-11 17:01:13 +00008515// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008516ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008517 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008518 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008519 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008520 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8521 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008522
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008523 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008524 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008525
Richard Trieubefece12011-09-07 02:02:10 +00008526 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008527}
8528
John McCall3c3b7f92011-10-25 17:37:35 +00008529/// Build an overloaded binary operator expression in the given scope.
8530static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8531 BinaryOperatorKind Opc,
8532 Expr *LHS, Expr *RHS) {
8533 // Find all of the overloaded operators visible from this
8534 // point. We perform both an operator-name lookup from the local
8535 // scope and an argument-dependent lookup based on the types of
8536 // the arguments.
8537 UnresolvedSet<16> Functions;
8538 OverloadedOperatorKind OverOp
8539 = BinaryOperator::getOverloadedOperator(Opc);
8540 if (Sc && OverOp != OO_None)
8541 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8542 RHS->getType(), Functions);
8543
8544 // Build the (potentially-overloaded, potentially-dependent)
8545 // binary operation.
8546 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8547}
8548
John McCall60d7b3a2010-08-24 06:29:42 +00008549ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008550 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008551 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008552 // We want to end up calling one of checkPseudoObjectAssignment
8553 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8554 // both expressions are overloadable or either is type-dependent),
8555 // or CreateBuiltinBinOp (in any other case). We also want to get
8556 // any placeholder types out of the way.
8557
John McCall3c3b7f92011-10-25 17:37:35 +00008558 // Handle pseudo-objects in the LHS.
8559 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8560 // Assignments with a pseudo-object l-value need special analysis.
8561 if (pty->getKind() == BuiltinType::PseudoObject &&
8562 BinaryOperator::isAssignmentOp(Opc))
8563 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8564
8565 // Don't resolve overloads if the other type is overloadable.
8566 if (pty->getKind() == BuiltinType::Overload) {
8567 // We can't actually test that if we still have a placeholder,
8568 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008569 // code below are valid when the LHS is an overload set. Note
8570 // that an overload set can be dependently-typed, but it never
8571 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008572 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8573 if (resolvedRHS.isInvalid()) return ExprError();
8574 RHSExpr = resolvedRHS.take();
8575
John McCallac516502011-10-28 01:04:34 +00008576 if (RHSExpr->isTypeDependent() ||
8577 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008578 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8579 }
8580
8581 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8582 if (LHS.isInvalid()) return ExprError();
8583 LHSExpr = LHS.take();
8584 }
8585
8586 // Handle pseudo-objects in the RHS.
8587 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8588 // An overload in the RHS can potentially be resolved by the type
8589 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008590 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8591 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8592 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8593
Eli Friedman87884912012-01-17 21:27:43 +00008594 if (LHSExpr->getType()->isOverloadableType())
8595 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8596
John McCall3c3b7f92011-10-25 17:37:35 +00008597 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008598 }
John McCall3c3b7f92011-10-25 17:37:35 +00008599
8600 // Don't resolve overloads if the other type is overloadable.
8601 if (pty->getKind() == BuiltinType::Overload &&
8602 LHSExpr->getType()->isOverloadableType())
8603 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8604
8605 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8606 if (!resolvedRHS.isUsable()) return ExprError();
8607 RHSExpr = resolvedRHS.take();
8608 }
8609
David Blaikie4e4d0842012-03-11 07:00:24 +00008610 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008611 // If either expression is type-dependent, always build an
8612 // overloaded op.
8613 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8614 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008615
John McCallac516502011-10-28 01:04:34 +00008616 // Otherwise, build an overloaded op if either expression has an
8617 // overloadable type.
8618 if (LHSExpr->getType()->isOverloadableType() ||
8619 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008620 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008621 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008622
Douglas Gregoreaebc752008-11-06 23:29:22 +00008623 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008624 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008625}
8626
John McCall60d7b3a2010-08-24 06:29:42 +00008627ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008628 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008629 Expr *InputExpr) {
8630 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008631 ExprValueKind VK = VK_RValue;
8632 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008633 QualType resultType;
8634 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008635 case UO_PreInc:
8636 case UO_PreDec:
8637 case UO_PostInc:
8638 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008639 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008640 Opc == UO_PreInc ||
8641 Opc == UO_PostInc,
8642 Opc == UO_PreInc ||
8643 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008644 break;
John McCall2de56d12010-08-25 11:45:40 +00008645 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008646 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008647 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008648 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008649 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8650 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008651 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008652 }
John McCall2de56d12010-08-25 11:45:40 +00008653 case UO_Plus:
8654 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008655 Input = UsualUnaryConversions(Input.take());
8656 if (Input.isInvalid()) return ExprError();
8657 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008658 if (resultType->isDependentType())
8659 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008660 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8661 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008662 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008663 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008664 resultType->isEnumeralType())
8665 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008666 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008667 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008668 resultType->isPointerType())
8669 break;
8670
Sebastian Redl0eb23302009-01-19 00:08:26 +00008671 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008672 << resultType << Input.get()->getSourceRange());
8673
John McCall2de56d12010-08-25 11:45:40 +00008674 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008675 Input = UsualUnaryConversions(Input.take());
8676 if (Input.isInvalid()) return ExprError();
8677 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008678 if (resultType->isDependentType())
8679 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008680 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8681 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8682 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008683 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008684 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008685 else if (resultType->hasIntegerRepresentation())
8686 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008687 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008688 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008689 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008690 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008691 break;
John Wiegley429bb272011-04-08 18:41:53 +00008692
John McCall2de56d12010-08-25 11:45:40 +00008693 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008694 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008695 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8696 if (Input.isInvalid()) return ExprError();
8697 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008698
8699 // Though we still have to promote half FP to float...
8700 if (resultType->isHalfType()) {
8701 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8702 resultType = Context.FloatTy;
8703 }
8704
Sebastian Redl28507842009-02-26 14:39:58 +00008705 if (resultType->isDependentType())
8706 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008707 if (resultType->isScalarType()) {
8708 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008709 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008710 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8711 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008712 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8713 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008714 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008715 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008716 // Vector logical not returns the signed variant of the operand type.
8717 resultType = GetSignedVectorType(resultType);
8718 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008719 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008720 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008721 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008722 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008723
Reid Spencer5f016e22007-07-11 17:01:13 +00008724 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008725 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008726 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008727 break;
John McCall2de56d12010-08-25 11:45:40 +00008728 case UO_Real:
8729 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008730 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008731 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8732 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008733 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008734 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8735 if (Input.get()->getValueKind() != VK_RValue &&
8736 Input.get()->getObjectKind() == OK_Ordinary)
8737 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008738 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008739 // In C, a volatile scalar is read by __imag. In C++, it is not.
8740 Input = DefaultLvalueConversion(Input.take());
8741 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008742 break;
John McCall2de56d12010-08-25 11:45:40 +00008743 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008744 resultType = Input.get()->getType();
8745 VK = Input.get()->getValueKind();
8746 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008747 break;
8748 }
John Wiegley429bb272011-04-08 18:41:53 +00008749 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008750 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008751
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008752 // Check for array bounds violations in the operand of the UnaryOperator,
8753 // except for the '*' and '&' operators that have to be handled specially
8754 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8755 // that are explicitly defined as valid by the standard).
8756 if (Opc != UO_AddrOf && Opc != UO_Deref)
8757 CheckArrayAccess(Input.get());
8758
John Wiegley429bb272011-04-08 18:41:53 +00008759 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008760 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008761}
8762
Douglas Gregord3d08532011-12-14 21:23:13 +00008763/// \brief Determine whether the given expression is a qualified member
8764/// access expression, of a form that could be turned into a pointer to member
8765/// with the address-of operator.
8766static bool isQualifiedMemberAccess(Expr *E) {
8767 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8768 if (!DRE->getQualifier())
8769 return false;
8770
8771 ValueDecl *VD = DRE->getDecl();
8772 if (!VD->isCXXClassMember())
8773 return false;
8774
8775 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8776 return true;
8777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8778 return Method->isInstance();
8779
8780 return false;
8781 }
8782
8783 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8784 if (!ULE->getQualifier())
8785 return false;
8786
8787 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8788 DEnd = ULE->decls_end();
8789 D != DEnd; ++D) {
8790 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8791 if (Method->isInstance())
8792 return true;
8793 } else {
8794 // Overload set does not contain methods.
8795 break;
8796 }
8797 }
8798
8799 return false;
8800 }
8801
8802 return false;
8803}
8804
John McCall60d7b3a2010-08-24 06:29:42 +00008805ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008806 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008807 // First things first: handle placeholders so that the
8808 // overloaded-operator check considers the right type.
8809 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8810 // Increment and decrement of pseudo-object references.
8811 if (pty->getKind() == BuiltinType::PseudoObject &&
8812 UnaryOperator::isIncrementDecrementOp(Opc))
8813 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8814
8815 // extension is always a builtin operator.
8816 if (Opc == UO_Extension)
8817 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8818
8819 // & gets special logic for several kinds of placeholder.
8820 // The builtin code knows what to do.
8821 if (Opc == UO_AddrOf &&
8822 (pty->getKind() == BuiltinType::Overload ||
8823 pty->getKind() == BuiltinType::UnknownAny ||
8824 pty->getKind() == BuiltinType::BoundMember))
8825 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8826
8827 // Anything else needs to be handled now.
8828 ExprResult Result = CheckPlaceholderExpr(Input);
8829 if (Result.isInvalid()) return ExprError();
8830 Input = Result.take();
8831 }
8832
David Blaikie4e4d0842012-03-11 07:00:24 +00008833 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008834 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8835 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008836 // Find all of the overloaded operators visible from this
8837 // point. We perform both an operator-name lookup from the local
8838 // scope and an argument-dependent lookup based on the types of
8839 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008840 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008841 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008842 if (S && OverOp != OO_None)
8843 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8844 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008845
John McCall9ae2f072010-08-23 23:25:46 +00008846 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008847 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008848
John McCall9ae2f072010-08-23 23:25:46 +00008849 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008850}
8851
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008852// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008853ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008854 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008855 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008856}
8857
Steve Naroff1b273c42007-09-16 14:56:35 +00008858/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008859ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008860 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008861 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008862 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008863 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008864 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008865}
8866
John McCallf85e1932011-06-15 23:02:42 +00008867/// Given the last statement in a statement-expression, check whether
8868/// the result is a producing expression (like a call to an
8869/// ns_returns_retained function) and, if so, rebuild it to hoist the
8870/// release out of the full-expression. Otherwise, return null.
8871/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008872static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008873 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008874 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008875 if (!cleanups) return 0;
8876
8877 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008878 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008879 return 0;
8880
8881 // Splice out the cast. This shouldn't modify any interesting
8882 // features of the statement.
8883 Expr *producer = cast->getSubExpr();
8884 assert(producer->getType() == cast->getType());
8885 assert(producer->getValueKind() == cast->getValueKind());
8886 cleanups->setSubExpr(producer);
8887 return cleanups;
8888}
8889
John McCall73f428c2012-04-04 01:27:53 +00008890void Sema::ActOnStartStmtExpr() {
8891 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8892}
8893
8894void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008895 // Note that function is also called by TreeTransform when leaving a
8896 // StmtExpr scope without rebuilding anything.
8897
John McCall73f428c2012-04-04 01:27:53 +00008898 DiscardCleanupsInEvaluationContext();
8899 PopExpressionEvaluationContext();
8900}
8901
John McCall60d7b3a2010-08-24 06:29:42 +00008902ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008903Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008904 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008905 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8906 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8907
John McCall73f428c2012-04-04 01:27:53 +00008908 if (hasAnyUnrecoverableErrorsInThisFunction())
8909 DiscardCleanupsInEvaluationContext();
8910 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8911 PopExpressionEvaluationContext();
8912
Douglas Gregordd8f5692010-03-10 04:54:39 +00008913 bool isFileScope
8914 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008915 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008916 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008917
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008918 // FIXME: there are a variety of strange constraints to enforce here, for
8919 // example, it is not possible to goto into a stmt expression apparently.
8920 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008921
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008922 // If there are sub stmts in the compound stmt, take the type of the last one
8923 // as the type of the stmtexpr.
8924 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008925 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008926 if (!Compound->body_empty()) {
8927 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008928 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008929 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008930 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8931 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008932 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008933 }
John McCallf85e1932011-06-15 23:02:42 +00008934
John Wiegley429bb272011-04-08 18:41:53 +00008935 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008936 // Do function/array conversion on the last expression, but not
8937 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008938 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8939 if (LastExpr.isInvalid())
8940 return ExprError();
8941 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008942
John Wiegley429bb272011-04-08 18:41:53 +00008943 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008944 // In ARC, if the final expression ends in a consume, splice
8945 // the consume out and bind it later. In the alternate case
8946 // (when dealing with a retainable type), the result
8947 // initialization will create a produce. In both cases the
8948 // result will be +1, and we'll need to balance that out with
8949 // a bind.
8950 if (Expr *rebuiltLastStmt
8951 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8952 LastExpr = rebuiltLastStmt;
8953 } else {
8954 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008955 InitializedEntity::InitializeResult(LPLoc,
8956 Ty,
8957 false),
8958 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008959 LastExpr);
8960 }
8961
John Wiegley429bb272011-04-08 18:41:53 +00008962 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008963 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008964 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008965 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008966 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008967 else
John Wiegley429bb272011-04-08 18:41:53 +00008968 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008969 StmtExprMayBindToTemp = true;
8970 }
8971 }
8972 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008973 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008974
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008975 // FIXME: Check that expression type is complete/non-abstract; statement
8976 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008977 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8978 if (StmtExprMayBindToTemp)
8979 return MaybeBindToTemporary(ResStmtExpr);
8980 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008981}
Steve Naroffd34e9152007-08-01 22:05:33 +00008982
John McCall60d7b3a2010-08-24 06:29:42 +00008983ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008984 TypeSourceInfo *TInfo,
8985 OffsetOfComponent *CompPtr,
8986 unsigned NumComponents,
8987 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008988 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008989 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008990 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008991
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008992 // We must have at least one component that refers to the type, and the first
8993 // one is known to be a field designator. Verify that the ArgTy represents
8994 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008995 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008996 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8997 << ArgTy << TypeRange);
8998
8999 // Type must be complete per C99 7.17p3 because a declaring a variable
9000 // with an incomplete type would be ill-formed.
9001 if (!Dependent
9002 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009003 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009004 return ExprError();
9005
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009006 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9007 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009008 // FIXME: This diagnostic isn't actually visible because the location is in
9009 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009010 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009011 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9012 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009013
9014 bool DidWarnAboutNonPOD = false;
9015 QualType CurrentType = ArgTy;
9016 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009017 SmallVector<OffsetOfNode, 4> Comps;
9018 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009019 for (unsigned i = 0; i != NumComponents; ++i) {
9020 const OffsetOfComponent &OC = CompPtr[i];
9021 if (OC.isBrackets) {
9022 // Offset of an array sub-field. TODO: Should we allow vector elements?
9023 if (!CurrentType->isDependentType()) {
9024 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9025 if(!AT)
9026 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9027 << CurrentType);
9028 CurrentType = AT->getElementType();
9029 } else
9030 CurrentType = Context.DependentTy;
9031
Richard Smithea011432011-10-17 23:29:39 +00009032 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9033 if (IdxRval.isInvalid())
9034 return ExprError();
9035 Expr *Idx = IdxRval.take();
9036
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009037 // The expression must be an integral expression.
9038 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009039 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9040 !Idx->getType()->isIntegerType())
9041 return ExprError(Diag(Idx->getLocStart(),
9042 diag::err_typecheck_subscript_not_integer)
9043 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009044
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009045 // Record this array index.
9046 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009047 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009048 continue;
9049 }
9050
9051 // Offset of a field.
9052 if (CurrentType->isDependentType()) {
9053 // We have the offset of a field, but we can't look into the dependent
9054 // type. Just record the identifier of the field.
9055 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9056 CurrentType = Context.DependentTy;
9057 continue;
9058 }
9059
9060 // We need to have a complete type to look into.
9061 if (RequireCompleteType(OC.LocStart, CurrentType,
9062 diag::err_offsetof_incomplete_type))
9063 return ExprError();
9064
9065 // Look for the designated field.
9066 const RecordType *RC = CurrentType->getAs<RecordType>();
9067 if (!RC)
9068 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9069 << CurrentType);
9070 RecordDecl *RD = RC->getDecl();
9071
9072 // C++ [lib.support.types]p5:
9073 // The macro offsetof accepts a restricted set of type arguments in this
9074 // International Standard. type shall be a POD structure or a POD union
9075 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009076 // C++11 [support.types]p4:
9077 // If type is not a standard-layout class (Clause 9), the results are
9078 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009079 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009080 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9081 unsigned DiagID =
9082 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9083 : diag::warn_offsetof_non_pod_type;
9084
9085 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009086 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009087 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009088 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9089 << CurrentType))
9090 DidWarnAboutNonPOD = true;
9091 }
9092
9093 // Look for the field.
9094 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9095 LookupQualifiedName(R, RD);
9096 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009097 IndirectFieldDecl *IndirectMemberDecl = 0;
9098 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009099 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009100 MemberDecl = IndirectMemberDecl->getAnonField();
9101 }
9102
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009103 if (!MemberDecl)
9104 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9105 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9106 OC.LocEnd));
9107
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009108 // C99 7.17p3:
9109 // (If the specified member is a bit-field, the behavior is undefined.)
9110 //
9111 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009112 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009113 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9114 << MemberDecl->getDeclName()
9115 << SourceRange(BuiltinLoc, RParenLoc);
9116 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9117 return ExprError();
9118 }
Eli Friedman19410a72010-08-05 10:11:36 +00009119
9120 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009121 if (IndirectMemberDecl)
9122 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009123
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009124 // If the member was found in a base class, introduce OffsetOfNodes for
9125 // the base class indirections.
9126 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9127 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009128 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009129 CXXBasePath &Path = Paths.front();
9130 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9131 B != BEnd; ++B)
9132 Comps.push_back(OffsetOfNode(B->Base));
9133 }
Eli Friedman19410a72010-08-05 10:11:36 +00009134
Francois Pichet87c2e122010-11-21 06:08:52 +00009135 if (IndirectMemberDecl) {
9136 for (IndirectFieldDecl::chain_iterator FI =
9137 IndirectMemberDecl->chain_begin(),
9138 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9139 assert(isa<FieldDecl>(*FI));
9140 Comps.push_back(OffsetOfNode(OC.LocStart,
9141 cast<FieldDecl>(*FI), OC.LocEnd));
9142 }
9143 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009144 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009145
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009146 CurrentType = MemberDecl->getType().getNonReferenceType();
9147 }
9148
9149 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9150 TInfo, Comps.data(), Comps.size(),
9151 Exprs.data(), Exprs.size(), RParenLoc));
9152}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009153
John McCall60d7b3a2010-08-24 06:29:42 +00009154ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009155 SourceLocation BuiltinLoc,
9156 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009157 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009158 OffsetOfComponent *CompPtr,
9159 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009160 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009161
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009162 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009163 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009164 if (ArgTy.isNull())
9165 return ExprError();
9166
Eli Friedman5a15dc12010-08-05 10:15:45 +00009167 if (!ArgTInfo)
9168 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9169
9170 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009171 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009172}
9173
9174
John McCall60d7b3a2010-08-24 06:29:42 +00009175ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009176 Expr *CondExpr,
9177 Expr *LHSExpr, Expr *RHSExpr,
9178 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009179 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9180
John McCallf89e55a2010-11-18 06:31:45 +00009181 ExprValueKind VK = VK_RValue;
9182 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009183 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009184 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009185 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009186 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009187 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009188 } else {
9189 // The conditional expression is required to be a constant expression.
9190 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009191 ExprResult CondICE
9192 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9193 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009194 if (CondICE.isInvalid())
9195 return ExprError();
9196 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009197
Sebastian Redl28507842009-02-26 14:39:58 +00009198 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009199 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9200
9201 resType = ActiveExpr->getType();
9202 ValueDependent = ActiveExpr->isValueDependent();
9203 VK = ActiveExpr->getValueKind();
9204 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009205 }
9206
Sebastian Redlf53597f2009-03-15 17:47:39 +00009207 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009208 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009209 resType->isDependentType(),
9210 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009211}
9212
Steve Naroff4eb206b2008-09-03 18:15:37 +00009213//===----------------------------------------------------------------------===//
9214// Clang Extensions.
9215//===----------------------------------------------------------------------===//
9216
9217/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009218void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009219 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009220 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009221 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009222 if (CurScope)
9223 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009224 else
9225 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009226
Eli Friedman84b007f2012-01-26 03:00:14 +00009227 getCurBlock()->HasImplicitReturnType = true;
9228
John McCall538773c2011-11-11 03:19:12 +00009229 // Enter a new evaluation context to insulate the block from any
9230 // cleanups from the enclosing full-expression.
9231 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009232}
9233
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009234void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9235 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009236 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009237 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009238 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009239
John McCallbf1a0282010-06-04 23:28:52 +00009240 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009241 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009242
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009243 // FIXME: We should allow unexpanded parameter packs here, but that would,
9244 // in turn, make the block expression contain unexpanded parameter packs.
9245 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9246 // Drop the parameters.
9247 FunctionProtoType::ExtProtoInfo EPI;
9248 EPI.HasTrailingReturn = false;
9249 EPI.TypeQuals |= DeclSpec::TQ_const;
9250 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9251 EPI);
9252 Sig = Context.getTrivialTypeSourceInfo(T);
9253 }
9254
John McCall711c52b2011-01-05 12:14:39 +00009255 // GetTypeForDeclarator always produces a function type for a block
9256 // literal signature. Furthermore, it is always a FunctionProtoType
9257 // unless the function was written with a typedef.
9258 assert(T->isFunctionType() &&
9259 "GetTypeForDeclarator made a non-function block signature");
9260
9261 // Look for an explicit signature in that function type.
9262 FunctionProtoTypeLoc ExplicitSignature;
9263
9264 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9265 if (isa<FunctionProtoTypeLoc>(tmp)) {
9266 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9267
9268 // Check whether that explicit signature was synthesized by
9269 // GetTypeForDeclarator. If so, don't save that as part of the
9270 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009271 if (ExplicitSignature.getLocalRangeBegin() ==
9272 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009273 // This would be much cheaper if we stored TypeLocs instead of
9274 // TypeSourceInfos.
9275 TypeLoc Result = ExplicitSignature.getResultLoc();
9276 unsigned Size = Result.getFullDataSize();
9277 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9278 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9279
9280 ExplicitSignature = FunctionProtoTypeLoc();
9281 }
John McCall82dc0092010-06-04 11:21:44 +00009282 }
Mike Stump1eb44332009-09-09 15:08:12 +00009283
John McCall711c52b2011-01-05 12:14:39 +00009284 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9285 CurBlock->FunctionType = T;
9286
9287 const FunctionType *Fn = T->getAs<FunctionType>();
9288 QualType RetTy = Fn->getResultType();
9289 bool isVariadic =
9290 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9291
John McCallc71a4912010-06-04 19:02:56 +00009292 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009293
John McCall82dc0092010-06-04 11:21:44 +00009294 // Don't allow returning a objc interface by value.
9295 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009296 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009297 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9298 return;
9299 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009300
John McCall82dc0092010-06-04 11:21:44 +00009301 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009302 // return type. TODO: what should we do with declarators like:
9303 // ^ * { ... }
9304 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009305 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009306 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009307 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009308 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009309 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009310
John McCall82dc0092010-06-04 11:21:44 +00009311 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009312 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009313 if (ExplicitSignature) {
9314 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9315 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009316 if (Param->getIdentifier() == 0 &&
9317 !Param->isImplicit() &&
9318 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009319 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009320 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009321 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009322 }
John McCall82dc0092010-06-04 11:21:44 +00009323
9324 // Fake up parameter variables if we have a typedef, like
9325 // ^ fntype { ... }
9326 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9327 for (FunctionProtoType::arg_type_iterator
9328 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9329 ParmVarDecl *Param =
9330 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009331 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009332 *I);
John McCallc71a4912010-06-04 19:02:56 +00009333 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009334 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009335 }
John McCall82dc0092010-06-04 11:21:44 +00009336
John McCallc71a4912010-06-04 19:02:56 +00009337 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009338 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009339 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009340 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9341 CurBlock->TheDecl->param_end(),
9342 /*CheckParameterNames=*/false);
9343 }
9344
John McCall82dc0092010-06-04 11:21:44 +00009345 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009346 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009347
John McCall82dc0092010-06-04 11:21:44 +00009348 // Put the parameter variables in scope. We can bail out immediately
9349 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009350 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009351 return;
9352
Steve Naroff090276f2008-10-10 01:28:17 +00009353 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009354 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9355 (*AI)->setOwningFunction(CurBlock->TheDecl);
9356
Steve Naroff090276f2008-10-10 01:28:17 +00009357 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009358 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009359 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009360
Steve Naroff090276f2008-10-10 01:28:17 +00009361 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009362 }
John McCall7a9813c2010-01-22 00:28:27 +00009363 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009364}
9365
9366/// ActOnBlockError - If there is an error parsing a block, this callback
9367/// is invoked to pop the information about the block from the action impl.
9368void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009369 // Leave the expression-evaluation context.
9370 DiscardCleanupsInEvaluationContext();
9371 PopExpressionEvaluationContext();
9372
Steve Naroff4eb206b2008-09-03 18:15:37 +00009373 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009374 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009375 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009376}
9377
9378/// ActOnBlockStmtExpr - This is called when the body of a block statement
9379/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009380ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009381 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009382 // If blocks are disabled, emit an error.
9383 if (!LangOpts.Blocks)
9384 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009385
John McCall538773c2011-11-11 03:19:12 +00009386 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009387 if (hasAnyUnrecoverableErrorsInThisFunction())
9388 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009389 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9390 PopExpressionEvaluationContext();
9391
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009392 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009393
9394 if (BSI->HasImplicitReturnType)
9395 deduceClosureReturnType(*BSI);
9396
Steve Naroff090276f2008-10-10 01:28:17 +00009397 PopDeclContext();
9398
Steve Naroff4eb206b2008-09-03 18:15:37 +00009399 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009400 if (!BSI->ReturnType.isNull())
9401 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009402
Mike Stump56925862009-07-28 22:04:01 +00009403 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009404 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009405
John McCall469a1eb2011-02-02 13:00:07 +00009406 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009407 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9408 SmallVector<BlockDecl::Capture, 4> Captures;
9409 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9410 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9411 if (Cap.isThisCapture())
9412 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009413 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009414 Cap.isNested(), Cap.getCopyExpr());
9415 Captures.push_back(NewCap);
9416 }
9417 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9418 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009419
John McCallc71a4912010-06-04 19:02:56 +00009420 // If the user wrote a function type in some form, try to use that.
9421 if (!BSI->FunctionType.isNull()) {
9422 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9423
9424 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9425 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9426
9427 // Turn protoless block types into nullary block types.
9428 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009429 FunctionProtoType::ExtProtoInfo EPI;
9430 EPI.ExtInfo = Ext;
9431 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009432
9433 // Otherwise, if we don't need to change anything about the function type,
9434 // preserve its sugar structure.
9435 } else if (FTy->getResultType() == RetTy &&
9436 (!NoReturn || FTy->getNoReturnAttr())) {
9437 BlockTy = BSI->FunctionType;
9438
9439 // Otherwise, make the minimal modifications to the function type.
9440 } else {
9441 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009442 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9443 EPI.TypeQuals = 0; // FIXME: silently?
9444 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009445 BlockTy = Context.getFunctionType(RetTy,
9446 FPT->arg_type_begin(),
9447 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009448 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009449 }
9450
9451 // If we don't have a function type, just build one from nothing.
9452 } else {
John McCalle23cf432010-12-14 08:05:40 +00009453 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009454 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009455 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009456 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009457
John McCallc71a4912010-06-04 19:02:56 +00009458 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9459 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009460 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009461
Chris Lattner17a78302009-04-19 05:28:12 +00009462 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009463 if (getCurFunction()->NeedsScopeChecking() &&
9464 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009465 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009466
Chris Lattnere476bdc2011-02-17 23:58:47 +00009467 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009468
Jordan Rose7dd900e2012-07-02 21:19:23 +00009469 // Try to apply the named return value optimization. We have to check again
9470 // if we can do this, though, because blocks keep return statements around
9471 // to deduce an implicit return type.
9472 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9473 !BSI->TheDecl->isDependentContext())
9474 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009475
Benjamin Kramerd2486192011-07-12 14:11:05 +00009476 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9477 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009478 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009479
John McCall80ee6e82011-11-10 05:35:25 +00009480 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009481 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009482 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009483 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009484 ExprCleanupObjects.push_back(Result->getBlockDecl());
9485 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009486
9487 // It also gets a branch-protected scope if any of the captured
9488 // variables needs destruction.
9489 for (BlockDecl::capture_const_iterator
9490 ci = Result->getBlockDecl()->capture_begin(),
9491 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9492 const VarDecl *var = ci->getVariable();
9493 if (var->getType().isDestructedType() != QualType::DK_none) {
9494 getCurFunction()->setHasBranchProtectedScope();
9495 break;
9496 }
9497 }
John McCall80ee6e82011-11-10 05:35:25 +00009498 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009499
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009500 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009501}
9502
John McCall60d7b3a2010-08-24 06:29:42 +00009503ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009504 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009505 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009506 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009507 GetTypeFromParser(Ty, &TInfo);
9508 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009509}
9510
John McCall60d7b3a2010-08-24 06:29:42 +00009511ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009512 Expr *E, TypeSourceInfo *TInfo,
9513 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009514 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009515
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009516 // Get the va_list type
9517 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009518 if (VaListType->isArrayType()) {
9519 // Deal with implicit array decay; for example, on x86-64,
9520 // va_list is an array, but it's supposed to decay to
9521 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009522 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009523 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009524 ExprResult Result = UsualUnaryConversions(E);
9525 if (Result.isInvalid())
9526 return ExprError();
9527 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009528 } else {
9529 // Otherwise, the va_list argument must be an l-value because
9530 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009531 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009532 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009533 return ExprError();
9534 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009535
Douglas Gregordd027302009-05-19 23:10:31 +00009536 if (!E->isTypeDependent() &&
9537 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009538 return ExprError(Diag(E->getLocStart(),
9539 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009540 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009541 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009542
David Majnemer0adde122011-06-14 05:17:32 +00009543 if (!TInfo->getType()->isDependentType()) {
9544 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009545 diag::err_second_parameter_to_va_arg_incomplete,
9546 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009547 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009548
David Majnemer0adde122011-06-14 05:17:32 +00009549 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009550 TInfo->getType(),
9551 diag::err_second_parameter_to_va_arg_abstract,
9552 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009553 return ExprError();
9554
Douglas Gregor4eb75222011-07-30 06:45:27 +00009555 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009556 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009557 TInfo->getType()->isObjCLifetimeType()
9558 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9559 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009560 << TInfo->getType()
9561 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009562 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009563
9564 // Check for va_arg where arguments of the given type will be promoted
9565 // (i.e. this va_arg is guaranteed to have undefined behavior).
9566 QualType PromoteType;
9567 if (TInfo->getType()->isPromotableIntegerType()) {
9568 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9569 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9570 PromoteType = QualType();
9571 }
9572 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9573 PromoteType = Context.DoubleTy;
9574 if (!PromoteType.isNull())
9575 Diag(TInfo->getTypeLoc().getBeginLoc(),
9576 diag::warn_second_parameter_to_va_arg_never_compatible)
9577 << TInfo->getType()
9578 << PromoteType
9579 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009580 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009581
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009582 QualType T = TInfo->getType().getNonLValueExprType(Context);
9583 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009584}
9585
John McCall60d7b3a2010-08-24 06:29:42 +00009586ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009587 // The type of __null will be int or long, depending on the size of
9588 // pointers on the target.
9589 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009590 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9591 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009592 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009593 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009594 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009595 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009596 Ty = Context.LongLongTy;
9597 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009598 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009599 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009600
Sebastian Redlf53597f2009-03-15 17:47:39 +00009601 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009602}
9603
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009604static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009605 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009606 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009607 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009608
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009609 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9610 if (!PT)
9611 return;
9612
9613 // Check if the destination is of type 'id'.
9614 if (!PT->isObjCIdType()) {
9615 // Check if the destination is the 'NSString' interface.
9616 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9617 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9618 return;
9619 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009620
John McCall4b9c2d22011-11-06 09:01:30 +00009621 // Ignore any parens, implicit casts (should only be
9622 // array-to-pointer decays), and not-so-opaque values. The last is
9623 // important for making this trigger for property assignments.
9624 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9625 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9626 if (OV->getSourceExpr())
9627 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9628
9629 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009630 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009631 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009632
Douglas Gregor849b2432010-03-31 17:46:05 +00009633 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009634}
9635
Chris Lattner5cf216b2008-01-04 18:04:52 +00009636bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9637 SourceLocation Loc,
9638 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009639 Expr *SrcExpr, AssignmentAction Action,
9640 bool *Complained) {
9641 if (Complained)
9642 *Complained = false;
9643
Chris Lattner5cf216b2008-01-04 18:04:52 +00009644 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009645 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009646 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009647 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009648 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009649 ConversionFixItGenerator ConvHints;
9650 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009651 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009652
Chris Lattner5cf216b2008-01-04 18:04:52 +00009653 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009654 case Compatible:
9655 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9656 return false;
9657
Chris Lattnerb7b61152008-01-04 18:22:42 +00009658 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009659 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009660 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9661 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009662 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009663 case IntToPointer:
9664 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009665 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9666 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009667 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009668 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009669 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009670 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009671 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9672 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009673 if (Hint.isNull() && !CheckInferredResultType) {
9674 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9675 }
9676 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009677 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009678 case IncompatiblePointerSign:
9679 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9680 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009681 case FunctionVoidPointer:
9682 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9683 break;
John McCall86c05f32011-02-01 00:10:29 +00009684 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009685 // Perform array-to-pointer decay if necessary.
9686 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9687
John McCall86c05f32011-02-01 00:10:29 +00009688 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9689 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9690 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9691 DiagKind = diag::err_typecheck_incompatible_address_space;
9692 break;
John McCallf85e1932011-06-15 23:02:42 +00009693
9694
9695 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009696 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009697 break;
John McCall86c05f32011-02-01 00:10:29 +00009698 }
9699
9700 llvm_unreachable("unknown error case for discarding qualifiers!");
9701 // fallthrough
9702 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009703 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009704 // If the qualifiers lost were because we were applying the
9705 // (deprecated) C++ conversion from a string literal to a char*
9706 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9707 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009708 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009709 // bit of refactoring (so that the second argument is an
9710 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009711 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009712 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009713 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009714 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9715 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009716 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9717 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009718 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009719 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009720 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009721 case IntToBlockPointer:
9722 DiagKind = diag::err_int_to_block_pointer;
9723 break;
9724 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009725 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009726 break;
Steve Naroff39579072008-10-14 22:18:38 +00009727 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009728 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009729 // it can give a more specific diagnostic.
9730 DiagKind = diag::warn_incompatible_qualified_id;
9731 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009732 case IncompatibleVectors:
9733 DiagKind = diag::warn_incompatible_vectors;
9734 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009735 case IncompatibleObjCWeakRef:
9736 DiagKind = diag::err_arc_weak_unavailable_assign;
9737 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009738 case Incompatible:
9739 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009740 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9741 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009742 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009743 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009744 break;
9745 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009746
Douglas Gregord4eea832010-04-09 00:35:39 +00009747 QualType FirstType, SecondType;
9748 switch (Action) {
9749 case AA_Assigning:
9750 case AA_Initializing:
9751 // The destination type comes first.
9752 FirstType = DstType;
9753 SecondType = SrcType;
9754 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009755
Douglas Gregord4eea832010-04-09 00:35:39 +00009756 case AA_Returning:
9757 case AA_Passing:
9758 case AA_Converting:
9759 case AA_Sending:
9760 case AA_Casting:
9761 // The source type comes first.
9762 FirstType = SrcType;
9763 SecondType = DstType;
9764 break;
9765 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009766
Anna Zaks67221552011-07-28 19:51:27 +00009767 PartialDiagnostic FDiag = PDiag(DiagKind);
9768 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9769
9770 // If we can fix the conversion, suggest the FixIts.
9771 assert(ConvHints.isNull() || Hint.isNull());
9772 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009773 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9774 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009775 FDiag << *HI;
9776 } else {
9777 FDiag << Hint;
9778 }
9779 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9780
Richard Trieu6efd4c52011-11-23 22:32:32 +00009781 if (MayHaveFunctionDiff)
9782 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9783
Anna Zaks67221552011-07-28 19:51:27 +00009784 Diag(Loc, FDiag);
9785
Richard Trieu6efd4c52011-11-23 22:32:32 +00009786 if (SecondType == Context.OverloadTy)
9787 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9788 FirstType);
9789
Douglas Gregor926df6c2011-06-11 01:09:30 +00009790 if (CheckInferredResultType)
9791 EmitRelatedResultTypeNote(SrcExpr);
9792
Douglas Gregora41a8c52010-04-22 00:20:18 +00009793 if (Complained)
9794 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009795 return isInvalid;
9796}
Anders Carlssone21555e2008-11-30 19:50:32 +00009797
Richard Smith282e7e62012-02-04 09:53:13 +00009798ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9799 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009800 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9801 public:
9802 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9803 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9804 }
9805 } Diagnoser;
9806
9807 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9808}
9809
9810ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9811 llvm::APSInt *Result,
9812 unsigned DiagID,
9813 bool AllowFold) {
9814 class IDDiagnoser : public VerifyICEDiagnoser {
9815 unsigned DiagID;
9816
9817 public:
9818 IDDiagnoser(unsigned DiagID)
9819 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9820
9821 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9822 S.Diag(Loc, DiagID) << SR;
9823 }
9824 } Diagnoser(DiagID);
9825
9826 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9827}
9828
9829void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9830 SourceRange SR) {
9831 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009832}
9833
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009834ExprResult
9835Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009836 VerifyICEDiagnoser &Diagnoser,
9837 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009838 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009839
David Blaikie4e4d0842012-03-11 07:00:24 +00009840 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009841 // C++11 [expr.const]p5:
9842 // If an expression of literal class type is used in a context where an
9843 // integral constant expression is required, then that class type shall
9844 // have a single non-explicit conversion function to an integral or
9845 // unscoped enumeration type
9846 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009847 if (!Diagnoser.Suppress) {
9848 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9849 public:
9850 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9851
9852 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9853 QualType T) {
9854 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9855 }
9856
9857 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9858 SourceLocation Loc,
9859 QualType T) {
9860 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9861 }
9862
9863 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9864 SourceLocation Loc,
9865 QualType T,
9866 QualType ConvTy) {
9867 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9868 }
9869
9870 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9871 CXXConversionDecl *Conv,
9872 QualType ConvTy) {
9873 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9874 << ConvTy->isEnumeralType() << ConvTy;
9875 }
9876
9877 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9878 QualType T) {
9879 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9880 }
9881
9882 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9883 CXXConversionDecl *Conv,
9884 QualType ConvTy) {
9885 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9886 << ConvTy->isEnumeralType() << ConvTy;
9887 }
9888
9889 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9890 SourceLocation Loc,
9891 QualType T,
9892 QualType ConvTy) {
9893 return DiagnosticBuilder::getEmpty();
9894 }
9895 } ConvertDiagnoser;
9896
9897 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9898 ConvertDiagnoser,
9899 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +00009900 } else {
9901 // The caller wants to silently enquire whether this is an ICE. Don't
9902 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009903 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9904 public:
9905 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9906
9907 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9908 QualType T) {
9909 return DiagnosticBuilder::getEmpty();
9910 }
9911
9912 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9913 SourceLocation Loc,
9914 QualType T) {
9915 return DiagnosticBuilder::getEmpty();
9916 }
9917
9918 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9919 SourceLocation Loc,
9920 QualType T,
9921 QualType ConvTy) {
9922 return DiagnosticBuilder::getEmpty();
9923 }
9924
9925 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9926 CXXConversionDecl *Conv,
9927 QualType ConvTy) {
9928 return DiagnosticBuilder::getEmpty();
9929 }
9930
9931 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9932 QualType T) {
9933 return DiagnosticBuilder::getEmpty();
9934 }
9935
9936 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9937 CXXConversionDecl *Conv,
9938 QualType ConvTy) {
9939 return DiagnosticBuilder::getEmpty();
9940 }
9941
9942 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9943 SourceLocation Loc,
9944 QualType T,
9945 QualType ConvTy) {
9946 return DiagnosticBuilder::getEmpty();
9947 }
9948 } ConvertDiagnoser;
9949
9950 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9951 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009952 }
9953 if (Converted.isInvalid())
9954 return Converted;
9955 E = Converted.take();
9956 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9957 return ExprError();
9958 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9959 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009960 if (!Diagnoser.Suppress)
9961 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +00009962 return ExprError();
9963 }
9964
Richard Smithdaaefc52011-12-14 23:32:26 +00009965 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9966 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +00009967 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +00009968 if (Result)
9969 *Result = E->EvaluateKnownConstInt(Context);
9970 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009971 }
9972
Anders Carlssone21555e2008-11-30 19:50:32 +00009973 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +00009974 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9975 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +00009976
Richard Smithdaaefc52011-12-14 23:32:26 +00009977 // Try to evaluate the expression, and produce diagnostics explaining why it's
9978 // not a constant expression as a side-effect.
9979 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9980 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9981
9982 // In C++11, we can rely on diagnostics being produced for any expression
9983 // which is not a constant expression. If no diagnostics were produced, then
9984 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00009985 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009986 if (Result)
9987 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +00009988 return Owned(E);
9989 }
9990
9991 // If our only note is the usual "invalid subexpression" note, just point
9992 // the caret at its location rather than producing an essentially
9993 // redundant note.
9994 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9995 diag::note_invalid_subexpr_in_const_expr) {
9996 DiagLoc = Notes[0].first;
9997 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +00009998 }
9999
10000 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010001 if (!Diagnoser.Suppress) {
10002 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010003 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10004 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010005 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010006
Richard Smith282e7e62012-02-04 09:53:13 +000010007 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010008 }
10009
Douglas Gregorab41fe92012-05-04 22:38:52 +000010010 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010011 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10012 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010013
Anders Carlssone21555e2008-11-30 19:50:32 +000010014 if (Result)
10015 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010016 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010017}
Douglas Gregore0762c92009-06-19 23:52:42 +000010018
Eli Friedmanef331b72012-01-20 01:26:23 +000010019namespace {
10020 // Handle the case where we conclude a expression which we speculatively
10021 // considered to be unevaluated is actually evaluated.
10022 class TransformToPE : public TreeTransform<TransformToPE> {
10023 typedef TreeTransform<TransformToPE> BaseTransform;
10024
10025 public:
10026 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10027
10028 // Make sure we redo semantic analysis
10029 bool AlwaysRebuild() { return true; }
10030
Eli Friedman56ff2832012-02-06 23:29:57 +000010031 // Make sure we handle LabelStmts correctly.
10032 // FIXME: This does the right thing, but maybe we need a more general
10033 // fix to TreeTransform?
10034 StmtResult TransformLabelStmt(LabelStmt *S) {
10035 S->getDecl()->setStmt(0);
10036 return BaseTransform::TransformLabelStmt(S);
10037 }
10038
Eli Friedmanef331b72012-01-20 01:26:23 +000010039 // We need to special-case DeclRefExprs referring to FieldDecls which
10040 // are not part of a member pointer formation; normal TreeTransforming
10041 // doesn't catch this case because of the way we represent them in the AST.
10042 // FIXME: This is a bit ugly; is it really the best way to handle this
10043 // case?
10044 //
10045 // Error on DeclRefExprs referring to FieldDecls.
10046 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10047 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010048 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010049 return SemaRef.Diag(E->getLocation(),
10050 diag::err_invalid_non_static_member_use)
10051 << E->getDecl() << E->getSourceRange();
10052
10053 return BaseTransform::TransformDeclRefExpr(E);
10054 }
10055
10056 // Exception: filter out member pointer formation
10057 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10058 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10059 return E;
10060
10061 return BaseTransform::TransformUnaryOperator(E);
10062 }
10063
Douglas Gregore2c59132012-02-09 08:14:43 +000010064 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10065 // Lambdas never need to be transformed.
10066 return E;
10067 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010068 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010069}
10070
Eli Friedmanef331b72012-01-20 01:26:23 +000010071ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010072 assert(ExprEvalContexts.back().Context == Unevaluated &&
10073 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010074 ExprEvalContexts.back().Context =
10075 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10076 if (ExprEvalContexts.back().Context == Unevaluated)
10077 return E;
10078 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010079}
10080
Douglas Gregor2afce722009-11-26 00:44:06 +000010081void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010082Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010083 Decl *LambdaContextDecl,
10084 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010085 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010086 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010087 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010088 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010089 LambdaContextDecl,
10090 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010091 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010092 if (!MaybeODRUseExprs.empty())
10093 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010094}
10095
Richard Trieu67e29332011-08-02 04:35:43 +000010096void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010097 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010098
Douglas Gregore2c59132012-02-09 08:14:43 +000010099 if (!Rec.Lambdas.empty()) {
10100 if (Rec.Context == Unevaluated) {
10101 // C++11 [expr.prim.lambda]p2:
10102 // A lambda-expression shall not appear in an unevaluated operand
10103 // (Clause 5).
10104 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10105 Diag(Rec.Lambdas[I]->getLocStart(),
10106 diag::err_lambda_unevaluated_operand);
10107 } else {
10108 // Mark the capture expressions odr-used. This was deferred
10109 // during lambda expression creation.
10110 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10111 LambdaExpr *Lambda = Rec.Lambdas[I];
10112 for (LambdaExpr::capture_init_iterator
10113 C = Lambda->capture_init_begin(),
10114 CEnd = Lambda->capture_init_end();
10115 C != CEnd; ++C) {
10116 MarkDeclarationsReferencedInExpr(*C);
10117 }
10118 }
10119 }
10120 }
10121
Douglas Gregor2afce722009-11-26 00:44:06 +000010122 // When are coming out of an unevaluated context, clear out any
10123 // temporaries that we may have created as part of the evaluation of
10124 // the expression in that context: they aren't relevant because they
10125 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010126 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010127 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10128 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010129 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010130 CleanupVarDeclMarking();
10131 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010132 // Otherwise, merge the contexts together.
10133 } else {
10134 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010135 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10136 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010137 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010138
10139 // Pop the current expression evaluation context off the stack.
10140 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010141}
Douglas Gregore0762c92009-06-19 23:52:42 +000010142
John McCallf85e1932011-06-15 23:02:42 +000010143void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010144 ExprCleanupObjects.erase(
10145 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10146 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010147 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010148 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010149}
10150
Eli Friedman71b8fb52012-01-21 01:01:51 +000010151ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10152 if (!E->getType()->isVariablyModifiedType())
10153 return E;
10154 return TranformToPotentiallyEvaluated(E);
10155}
10156
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010157static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010158 // Do not mark anything as "used" within a dependent context; wait for
10159 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010160 if (SemaRef.CurContext->isDependentContext())
10161 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010162
Eli Friedman5f2987c2012-02-02 03:46:19 +000010163 switch (SemaRef.ExprEvalContexts.back().Context) {
10164 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010165 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010166 // (Depending on how you read the standard, we actually do need to do
10167 // something here for null pointer constants, but the standard's
10168 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010169 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010170
Eli Friedman5f2987c2012-02-02 03:46:19 +000010171 case Sema::ConstantEvaluated:
10172 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010173 // We are in a potentially evaluated expression (or a constant-expression
10174 // in C++03); we need to do implicit template instantiation, implicitly
10175 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010176 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010177
Eli Friedman5f2987c2012-02-02 03:46:19 +000010178 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010179 // Referenced declarations will only be used if the construct in the
10180 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010181 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010182 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010183 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010184}
10185
10186/// \brief Mark a function referenced, and check whether it is odr-used
10187/// (C++ [basic.def.odr]p2, C99 6.9p3)
10188void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10189 assert(Func && "No function?");
10190
10191 Func->setReferenced();
10192
Richard Smith57b9c4e2012-02-14 22:25:15 +000010193 // Don't mark this function as used multiple times, unless it's a constexpr
10194 // function which we need to instantiate.
10195 if (Func->isUsed(false) &&
10196 !(Func->isConstexpr() && !Func->getBody() &&
10197 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010198 return;
10199
10200 if (!IsPotentiallyEvaluatedContext(*this))
10201 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010202
Douglas Gregore0762c92009-06-19 23:52:42 +000010203 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010204 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010205 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010206 if (Constructor->isDefaultConstructor()) {
10207 if (Constructor->isTrivial())
10208 return;
10209 if (!Constructor->isUsed(false))
10210 DefineImplicitDefaultConstructor(Loc, Constructor);
10211 } else if (Constructor->isCopyConstructor()) {
10212 if (!Constructor->isUsed(false))
10213 DefineImplicitCopyConstructor(Loc, Constructor);
10214 } else if (Constructor->isMoveConstructor()) {
10215 if (!Constructor->isUsed(false))
10216 DefineImplicitMoveConstructor(Loc, Constructor);
10217 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010218 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010219
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010220 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010221 } else if (CXXDestructorDecl *Destructor =
10222 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010223 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10224 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010225 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010226 if (Destructor->isVirtual())
10227 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010228 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010229 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10230 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010231 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010232 if (!MethodDecl->isUsed(false)) {
10233 if (MethodDecl->isCopyAssignmentOperator())
10234 DefineImplicitCopyAssignment(Loc, MethodDecl);
10235 else
10236 DefineImplicitMoveAssignment(Loc, MethodDecl);
10237 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010238 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10239 MethodDecl->getParent()->isLambda()) {
10240 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10241 if (Conversion->isLambdaToBlockPointerConversion())
10242 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10243 else
10244 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010245 } else if (MethodDecl->isVirtual())
10246 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010247 }
John McCall15e310a2011-02-19 02:53:41 +000010248
Eli Friedman5f2987c2012-02-02 03:46:19 +000010249 // Recursive functions should be marked when used from another function.
10250 // FIXME: Is this really right?
10251 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010252
Richard Smithb9d0b762012-07-27 04:22:15 +000010253 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010254 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010255 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010256 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10257 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010258
Eli Friedman5f2987c2012-02-02 03:46:19 +000010259 // Implicit instantiation of function templates and member functions of
10260 // class templates.
10261 if (Func->isImplicitlyInstantiable()) {
10262 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010263 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010264 if (FunctionTemplateSpecializationInfo *SpecInfo
10265 = Func->getTemplateSpecializationInfo()) {
10266 if (SpecInfo->getPointOfInstantiation().isInvalid())
10267 SpecInfo->setPointOfInstantiation(Loc);
10268 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010269 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010270 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010271 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10272 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010273 } else if (MemberSpecializationInfo *MSInfo
10274 = Func->getMemberSpecializationInfo()) {
10275 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010276 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010277 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010278 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010279 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010280 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10281 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010282 }
Mike Stump1eb44332009-09-09 15:08:12 +000010283
Richard Smith57b9c4e2012-02-14 22:25:15 +000010284 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010285 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10286 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010287 PendingLocalImplicitInstantiations.push_back(
10288 std::make_pair(Func, PointOfInstantiation));
10289 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010290 // Do not defer instantiations of constexpr functions, to avoid the
10291 // expression evaluator needing to call back into Sema if it sees a
10292 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010293 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010294 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010295 PendingInstantiations.push_back(std::make_pair(Func,
10296 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010297 // Notify the consumer that a function was implicitly instantiated.
10298 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10299 }
John McCall15e310a2011-02-19 02:53:41 +000010300 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010301 } else {
10302 // Walk redefinitions, as some of them may be instantiable.
10303 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10304 e(Func->redecls_end()); i != e; ++i) {
10305 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10306 MarkFunctionReferenced(Loc, *i);
10307 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010308 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010309
10310 // Keep track of used but undefined functions.
10311 if (!Func->isPure() && !Func->hasBody() &&
10312 Func->getLinkage() != ExternalLinkage) {
10313 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10314 if (old.isInvalid()) old = Loc;
10315 }
10316
10317 Func->setUsed(true);
10318}
10319
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010320static void
10321diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10322 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010323 DeclContext *VarDC = var->getDeclContext();
10324
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010325 // If the parameter still belongs to the translation unit, then
10326 // we're actually just using one parameter in the declaration of
10327 // the next.
10328 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010329 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010330 return;
10331
Eli Friedman0a294222012-02-07 00:15:00 +000010332 // For C code, don't diagnose about capture if we're not actually in code
10333 // right now; it's impossible to write a non-constant expression outside of
10334 // function context, so we'll get other (more useful) diagnostics later.
10335 //
10336 // For C++, things get a bit more nasty... it would be nice to suppress this
10337 // diagnostic for certain cases like using a local variable in an array bound
10338 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010339 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010340 return;
10341
Eli Friedman0a294222012-02-07 00:15:00 +000010342 if (isa<CXXMethodDecl>(VarDC) &&
10343 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10344 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10345 << var->getIdentifier();
10346 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10347 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10348 << var->getIdentifier() << fn->getDeclName();
10349 } else if (isa<BlockDecl>(VarDC)) {
10350 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10351 << var->getIdentifier();
10352 } else {
10353 // FIXME: Is there any other context where a local variable can be
10354 // declared?
10355 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10356 << var->getIdentifier();
10357 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010358
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010359 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10360 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010361
10362 // FIXME: Add additional diagnostic info about class etc. which prevents
10363 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010364}
10365
Douglas Gregorf8af9822012-02-12 18:42:33 +000010366/// \brief Capture the given variable in the given lambda expression.
10367static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010368 VarDecl *Var, QualType FieldType,
10369 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010370 SourceLocation Loc,
10371 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010372 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010373
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010374 // Build the non-static data member.
10375 FieldDecl *Field
10376 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10377 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010378 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010379 Field->setImplicit(true);
10380 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010381 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010382
10383 // C++11 [expr.prim.lambda]p21:
10384 // When the lambda-expression is evaluated, the entities that
10385 // are captured by copy are used to direct-initialize each
10386 // corresponding non-static data member of the resulting closure
10387 // object. (For array members, the array elements are
10388 // direct-initialized in increasing subscript order.) These
10389 // initializations are performed in the (unspecified) order in
10390 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010391
Douglas Gregore2c59132012-02-09 08:14:43 +000010392 // Introduce a new evaluation context for the initialization, so
10393 // that temporaries introduced as part of the capture are retained
10394 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010395 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10396
Douglas Gregor73d90922012-02-10 09:26:04 +000010397 // C++ [expr.prim.labda]p12:
10398 // An entity captured by a lambda-expression is odr-used (3.2) in
10399 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010400 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10401 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010402 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010403 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010404
10405 // When the field has array type, create index variables for each
10406 // dimension of the array. We use these index variables to subscript
10407 // the source array, and other clients (e.g., CodeGen) will perform
10408 // the necessary iteration with these index variables.
10409 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010410 QualType BaseType = FieldType;
10411 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010412 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010413 while (const ConstantArrayType *Array
10414 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010415 // Create the iteration variable for this array index.
10416 IdentifierInfo *IterationVarName = 0;
10417 {
10418 SmallString<8> Str;
10419 llvm::raw_svector_ostream OS(Str);
10420 OS << "__i" << IndexVariables.size();
10421 IterationVarName = &S.Context.Idents.get(OS.str());
10422 }
10423 VarDecl *IterationVar
10424 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10425 IterationVarName, SizeType,
10426 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10427 SC_None, SC_None);
10428 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010429 LSI->ArrayIndexVars.push_back(IterationVar);
10430
Douglas Gregor18fe0842012-02-09 02:45:47 +000010431 // Create a reference to the iteration variable.
10432 ExprResult IterationVarRef
10433 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10434 assert(!IterationVarRef.isInvalid() &&
10435 "Reference to invented variable cannot fail!");
10436 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10437 assert(!IterationVarRef.isInvalid() &&
10438 "Conversion of invented variable cannot fail!");
10439
10440 // Subscript the array with this iteration variable.
10441 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10442 Ref, Loc, IterationVarRef.take(), Loc);
10443 if (Subscript.isInvalid()) {
10444 S.CleanupVarDeclMarking();
10445 S.DiscardCleanupsInEvaluationContext();
10446 S.PopExpressionEvaluationContext();
10447 return ExprError();
10448 }
10449
10450 Ref = Subscript.take();
10451 BaseType = Array->getElementType();
10452 }
10453
10454 // Construct the entity that we will be initializing. For an array, this
10455 // will be first element in the array, which may require several levels
10456 // of array-subscript entities.
10457 SmallVector<InitializedEntity, 4> Entities;
10458 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010459 Entities.push_back(
10460 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010461 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10462 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10463 0,
10464 Entities.back()));
10465
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010466 InitializationKind InitKind
10467 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010468 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010469 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010470 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10471 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010472 MultiExprArg(S, &Ref, 1));
10473
10474 // If this initialization requires any cleanups (e.g., due to a
10475 // default argument to a copy constructor), note that for the
10476 // lambda.
10477 if (S.ExprNeedsCleanups)
10478 LSI->ExprNeedsCleanups = true;
10479
10480 // Exit the expression evaluation context used for the capture.
10481 S.CleanupVarDeclMarking();
10482 S.DiscardCleanupsInEvaluationContext();
10483 S.PopExpressionEvaluationContext();
10484 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010485}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010486
Douglas Gregor999713e2012-02-18 09:37:24 +000010487bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10488 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10489 bool BuildAndDiagnose,
10490 QualType &CaptureType,
10491 QualType &DeclRefType) {
10492 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010493
Eli Friedmanb942cb22012-02-03 22:47:37 +000010494 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010495 if (Var->getDeclContext() == DC) return true;
10496 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010497
Douglas Gregorf8af9822012-02-12 18:42:33 +000010498 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010499
Douglas Gregor999713e2012-02-18 09:37:24 +000010500 // Walk up the stack to determine whether we can capture the variable,
10501 // performing the "simple" checks that don't depend on type. We stop when
10502 // we've either hit the declared scope of the variable or find an existing
10503 // capture of that variable.
10504 CaptureType = Var->getType();
10505 DeclRefType = CaptureType.getNonReferenceType();
10506 bool Explicit = (Kind != TryCapture_Implicit);
10507 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010508 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010509 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010510 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010511 DeclContext *ParentDC;
10512 if (isa<BlockDecl>(DC))
10513 ParentDC = DC->getParent();
10514 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010515 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010516 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10517 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010518 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010519 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010520 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010521 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010522 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010523
Eli Friedmanb942cb22012-02-03 22:47:37 +000010524 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010525 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010526
Eli Friedmanb942cb22012-02-03 22:47:37 +000010527 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010528 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010529 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010530 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010531
10532 // Retrieve the capture type for this variable.
10533 CaptureType = CSI->getCapture(Var).getCaptureType();
10534
10535 // Compute the type of an expression that refers to this variable.
10536 DeclRefType = CaptureType.getNonReferenceType();
10537
10538 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10539 if (Cap.isCopyCapture() &&
10540 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10541 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010542 break;
10543 }
10544
Douglas Gregorf8af9822012-02-12 18:42:33 +000010545 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010546 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010547
10548 // Lambdas are not allowed to capture unnamed variables
10549 // (e.g. anonymous unions).
10550 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10551 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010552 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010553 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010554 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10555 Diag(Var->getLocation(), diag::note_declared_at);
10556 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010557 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010558 }
10559
10560 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010561 if (Var->getType()->isVariablyModifiedType()) {
10562 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010563 if (IsBlock)
10564 Diag(Loc, diag::err_ref_vm_type);
10565 else
10566 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10567 Diag(Var->getLocation(), diag::note_previous_decl)
10568 << Var->getDeclName();
10569 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010570 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010571 }
10572
Eli Friedmanb942cb22012-02-03 22:47:37 +000010573 // Lambdas are not allowed to capture __block variables; they don't
10574 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010575 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010576 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010577 Diag(Loc, diag::err_lambda_capture_block)
10578 << Var->getDeclName();
10579 Diag(Var->getLocation(), diag::note_previous_decl)
10580 << Var->getDeclName();
10581 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010582 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010583 }
10584
Douglas Gregorf8af9822012-02-12 18:42:33 +000010585 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10586 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010587 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010588 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10589 Diag(Var->getLocation(), diag::note_previous_decl)
10590 << Var->getDeclName();
10591 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10592 diag::note_lambda_decl);
10593 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010594 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010595 }
10596
10597 FunctionScopesIndex--;
10598 DC = ParentDC;
10599 Explicit = false;
10600 } while (!Var->getDeclContext()->Equals(DC));
10601
Douglas Gregor999713e2012-02-18 09:37:24 +000010602 // Walk back down the scope stack, computing the type of the capture at
10603 // each step, checking type-specific requirements, and adding captures if
10604 // requested.
10605 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10606 ++I) {
10607 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010608
Douglas Gregor999713e2012-02-18 09:37:24 +000010609 // Compute the type of the capture and of a reference to the capture within
10610 // this scope.
10611 if (isa<BlockScopeInfo>(CSI)) {
10612 Expr *CopyExpr = 0;
10613 bool ByRef = false;
10614
10615 // Blocks are not allowed to capture arrays.
10616 if (CaptureType->isArrayType()) {
10617 if (BuildAndDiagnose) {
10618 Diag(Loc, diag::err_ref_array_type);
10619 Diag(Var->getLocation(), diag::note_previous_decl)
10620 << Var->getDeclName();
10621 }
10622 return true;
10623 }
10624
John McCall100c6492012-03-30 05:23:48 +000010625 // Forbid the block-capture of autoreleasing variables.
10626 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10627 if (BuildAndDiagnose) {
10628 Diag(Loc, diag::err_arc_autoreleasing_capture)
10629 << /*block*/ 0;
10630 Diag(Var->getLocation(), diag::note_previous_decl)
10631 << Var->getDeclName();
10632 }
10633 return true;
10634 }
10635
Douglas Gregor999713e2012-02-18 09:37:24 +000010636 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10637 // Block capture by reference does not change the capture or
10638 // declaration reference types.
10639 ByRef = true;
10640 } else {
10641 // Block capture by copy introduces 'const'.
10642 CaptureType = CaptureType.getNonReferenceType().withConst();
10643 DeclRefType = CaptureType;
10644
David Blaikie4e4d0842012-03-11 07:00:24 +000010645 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010646 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10647 // The capture logic needs the destructor, so make sure we mark it.
10648 // Usually this is unnecessary because most local variables have
10649 // their destructors marked at declaration time, but parameters are
10650 // an exception because it's technically only the call site that
10651 // actually requires the destructor.
10652 if (isa<ParmVarDecl>(Var))
10653 FinalizeVarWithDestructor(Var, Record);
10654
10655 // According to the blocks spec, the capture of a variable from
10656 // the stack requires a const copy constructor. This is not true
10657 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010658 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010659 DeclRefType.withConst(),
10660 VK_LValue, Loc);
10661 ExprResult Result
10662 = PerformCopyInitialization(
10663 InitializedEntity::InitializeBlock(Var->getLocation(),
10664 CaptureType, false),
10665 Loc, Owned(DeclRef));
10666
10667 // Build a full-expression copy expression if initialization
10668 // succeeded and used a non-trivial constructor. Recover from
10669 // errors by pretending that the copy isn't necessary.
10670 if (!Result.isInvalid() &&
10671 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10672 ->isTrivial()) {
10673 Result = MaybeCreateExprWithCleanups(Result);
10674 CopyExpr = Result.take();
10675 }
10676 }
10677 }
10678 }
10679
10680 // Actually capture the variable.
10681 if (BuildAndDiagnose)
10682 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10683 SourceLocation(), CaptureType, CopyExpr);
10684 Nested = true;
10685 continue;
10686 }
Douglas Gregor68932842012-02-18 05:51:20 +000010687
Douglas Gregor999713e2012-02-18 09:37:24 +000010688 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10689
10690 // Determine whether we are capturing by reference or by value.
10691 bool ByRef = false;
10692 if (I == N - 1 && Kind != TryCapture_Implicit) {
10693 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010694 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010695 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010696 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010697
10698 // Compute the type of the field that will capture this variable.
10699 if (ByRef) {
10700 // C++11 [expr.prim.lambda]p15:
10701 // An entity is captured by reference if it is implicitly or
10702 // explicitly captured but not captured by copy. It is
10703 // unspecified whether additional unnamed non-static data
10704 // members are declared in the closure type for entities
10705 // captured by reference.
10706 //
10707 // FIXME: It is not clear whether we want to build an lvalue reference
10708 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10709 // to do the former, while EDG does the latter. Core issue 1249 will
10710 // clarify, but for now we follow GCC because it's a more permissive and
10711 // easily defensible position.
10712 CaptureType = Context.getLValueReferenceType(DeclRefType);
10713 } else {
10714 // C++11 [expr.prim.lambda]p14:
10715 // For each entity captured by copy, an unnamed non-static
10716 // data member is declared in the closure type. The
10717 // declaration order of these members is unspecified. The type
10718 // of such a data member is the type of the corresponding
10719 // captured entity if the entity is not a reference to an
10720 // object, or the referenced type otherwise. [Note: If the
10721 // captured entity is a reference to a function, the
10722 // corresponding data member is also a reference to a
10723 // function. - end note ]
10724 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10725 if (!RefType->getPointeeType()->isFunctionType())
10726 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010727 }
John McCall100c6492012-03-30 05:23:48 +000010728
10729 // Forbid the lambda copy-capture of autoreleasing variables.
10730 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10731 if (BuildAndDiagnose) {
10732 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10733 Diag(Var->getLocation(), diag::note_previous_decl)
10734 << Var->getDeclName();
10735 }
10736 return true;
10737 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010738 }
10739
Douglas Gregor999713e2012-02-18 09:37:24 +000010740 // Capture this variable in the lambda.
10741 Expr *CopyExpr = 0;
10742 if (BuildAndDiagnose) {
10743 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010744 DeclRefType, Loc,
10745 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010746 if (!Result.isInvalid())
10747 CopyExpr = Result.take();
10748 }
10749
10750 // Compute the type of a reference to this captured variable.
10751 if (ByRef)
10752 DeclRefType = CaptureType.getNonReferenceType();
10753 else {
10754 // C++ [expr.prim.lambda]p5:
10755 // The closure type for a lambda-expression has a public inline
10756 // function call operator [...]. This function call operator is
10757 // declared const (9.3.1) if and only if the lambda-expression’s
10758 // parameter-declaration-clause is not followed by mutable.
10759 DeclRefType = CaptureType.getNonReferenceType();
10760 if (!LSI->Mutable && !CaptureType->isReferenceType())
10761 DeclRefType.addConst();
10762 }
10763
10764 // Add the capture.
10765 if (BuildAndDiagnose)
10766 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10767 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010768 Nested = true;
10769 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010770
10771 return false;
10772}
10773
10774bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10775 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10776 QualType CaptureType;
10777 QualType DeclRefType;
10778 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10779 /*BuildAndDiagnose=*/true, CaptureType,
10780 DeclRefType);
10781}
10782
10783QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10784 QualType CaptureType;
10785 QualType DeclRefType;
10786
10787 // Determine whether we can capture this variable.
10788 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10789 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10790 return QualType();
10791
10792 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010793}
10794
Eli Friedmand2cce132012-02-02 23:15:15 +000010795static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10796 SourceLocation Loc) {
10797 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010798 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010799 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010800 Var->getLinkage() != ExternalLinkage &&
10801 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010802 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10803 if (old.isInvalid()) old = Loc;
10804 }
10805
Douglas Gregor999713e2012-02-18 09:37:24 +000010806 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010807
Eli Friedmand2cce132012-02-02 23:15:15 +000010808 Var->setUsed(true);
10809}
10810
10811void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10812 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10813 // an object that satisfies the requirements for appearing in a
10814 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10815 // is immediately applied." This function handles the lvalue-to-rvalue
10816 // conversion part.
10817 MaybeODRUseExprs.erase(E->IgnoreParens());
10818}
10819
Eli Friedmanac626012012-02-29 03:16:56 +000010820ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10821 if (!Res.isUsable())
10822 return Res;
10823
10824 // If a constant-expression is a reference to a variable where we delay
10825 // deciding whether it is an odr-use, just assume we will apply the
10826 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10827 // (a non-type template argument), we have special handling anyway.
10828 UpdateMarkingForLValueToRValue(Res.get());
10829 return Res;
10830}
10831
Eli Friedmand2cce132012-02-02 23:15:15 +000010832void Sema::CleanupVarDeclMarking() {
10833 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10834 e = MaybeODRUseExprs.end();
10835 i != e; ++i) {
10836 VarDecl *Var;
10837 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010838 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010839 Var = cast<VarDecl>(DRE->getDecl());
10840 Loc = DRE->getLocation();
10841 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10842 Var = cast<VarDecl>(ME->getMemberDecl());
10843 Loc = ME->getMemberLoc();
10844 } else {
10845 llvm_unreachable("Unexpcted expression");
10846 }
10847
10848 MarkVarDeclODRUsed(*this, Var, Loc);
10849 }
10850
10851 MaybeODRUseExprs.clear();
10852}
10853
10854// Mark a VarDecl referenced, and perform the necessary handling to compute
10855// odr-uses.
10856static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10857 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010858 Var->setReferenced();
10859
Eli Friedmand2cce132012-02-02 23:15:15 +000010860 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010861 return;
10862
10863 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010864 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010865 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10866 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010867 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10868 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010869 (!AlreadyInstantiated ||
10870 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010871 if (!AlreadyInstantiated) {
10872 // This is a modification of an existing AST node. Notify listeners.
10873 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10874 L->StaticDataMemberInstantiated(Var);
10875 MSInfo->setPointOfInstantiation(Loc);
10876 }
10877 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010878 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010879 // Do not defer instantiations of variables which could be used in a
10880 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000010881 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010882 else
Richard Smith37ce0102012-02-15 02:42:50 +000010883 SemaRef.PendingInstantiations.push_back(
10884 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010885 }
10886 }
10887
Eli Friedmand2cce132012-02-02 23:15:15 +000010888 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10889 // an object that satisfies the requirements for appearing in a
10890 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10891 // is immediately applied." We check the first part here, and
10892 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10893 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000010894 // C++03 depends on whether we get the C++03 version correct. This does not
10895 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000010896 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000010897 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010898 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000010899 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10900 SemaRef.MaybeODRUseExprs.insert(E);
10901 else
10902 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10903}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010904
Eli Friedmand2cce132012-02-02 23:15:15 +000010905/// \brief Mark a variable referenced, and check whether it is odr-used
10906/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10907/// used directly for normal expressions referring to VarDecl.
10908void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10909 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010910}
10911
10912static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10913 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010914 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10915 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10916 return;
10917 }
10918
Eli Friedman5f2987c2012-02-02 03:46:19 +000010919 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010920
10921 // If this is a call to a method via a cast, also mark the method in the
10922 // derived class used in case codegen can devirtualize the call.
10923 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10924 if (!ME)
10925 return;
10926 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10927 if (!MD)
10928 return;
10929 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000010930 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010931 if (!MostDerivedClassDecl)
10932 return;
10933 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000010934 if (!DM)
10935 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010936 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010937}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010938
Eli Friedman5f2987c2012-02-02 03:46:19 +000010939/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10940void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10941 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10942}
10943
10944/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10945void Sema::MarkMemberReferenced(MemberExpr *E) {
10946 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10947}
10948
Douglas Gregor73d90922012-02-10 09:26:04 +000010949/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000010950/// marks the declaration referenced, and performs odr-use checking for functions
10951/// and variables. This method should not be used when building an normal
10952/// expression which refers to a variable.
10953void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10954 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10955 MarkVariableReferenced(Loc, VD);
10956 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10957 MarkFunctionReferenced(Loc, FD);
10958 else
10959 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000010960}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010961
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010962namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010963 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010964 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010965 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010966 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10967 Sema &S;
10968 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010969
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010970 public:
10971 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010972
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010973 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010974
10975 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10976 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010977 };
10978}
10979
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010980bool MarkReferencedDecls::TraverseTemplateArgument(
10981 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010982 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000010983 if (Decl *D = Arg.getAsDecl())
10984 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010985 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010986
10987 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010988}
10989
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010990bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010991 if (ClassTemplateSpecializationDecl *Spec
10992 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10993 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010994 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010995 }
10996
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010997 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010998}
10999
11000void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11001 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011002 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011003}
11004
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011005namespace {
11006 /// \brief Helper class that marks all of the declarations referenced by
11007 /// potentially-evaluated subexpressions as "referenced".
11008 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11009 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011010 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011011
11012 public:
11013 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11014
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011015 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11016 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011017
11018 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011019 // If we were asked not to visit local variables, don't.
11020 if (SkipLocalVariables) {
11021 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11022 if (VD->hasLocalStorage())
11023 return;
11024 }
11025
Eli Friedman5f2987c2012-02-02 03:46:19 +000011026 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011027 }
11028
11029 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011030 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011031 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011032 }
11033
John McCall80ee6e82011-11-10 05:35:25 +000011034 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011035 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011036 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11037 Visit(E->getSubExpr());
11038 }
11039
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011040 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011041 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011042 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011043 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011044 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011045 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011046 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011047
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011048 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11049 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011050 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011051 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11052 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11053 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011054 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011055 S.LookupDestructor(Record));
11056 }
11057
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011058 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011059 }
11060
11061 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011062 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011063 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011064 }
11065
Douglas Gregor102ff972010-10-19 17:17:35 +000011066 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11067 Visit(E->getExpr());
11068 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011069
11070 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11071 Inherited::VisitImplicitCastExpr(E);
11072
11073 if (E->getCastKind() == CK_LValueToRValue)
11074 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11075 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011076 };
11077}
11078
11079/// \brief Mark any declarations that appear within this expression or any
11080/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011081///
11082/// \param SkipLocalVariables If true, don't mark local variables as
11083/// 'referenced'.
11084void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11085 bool SkipLocalVariables) {
11086 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011087}
11088
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011089/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11090/// of the program being compiled.
11091///
11092/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011093/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011094/// possibility that the code will actually be executable. Code in sizeof()
11095/// expressions, code used only during overload resolution, etc., are not
11096/// potentially evaluated. This routine will suppress such diagnostics or,
11097/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011098/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011099/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011100///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011101/// This routine should be used for all diagnostics that describe the run-time
11102/// behavior of a program, such as passing a non-POD value through an ellipsis.
11103/// Failure to do so will likely result in spurious diagnostics or failures
11104/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011105bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011106 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011107 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011108 case Unevaluated:
11109 // The argument will never be evaluated, so don't complain.
11110 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011111
Richard Smithf6702a32011-12-20 02:08:33 +000011112 case ConstantEvaluated:
11113 // Relevant diagnostics should be produced by constant evaluation.
11114 break;
11115
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011116 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011117 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011118 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011119 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011120 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011121 }
11122 else
11123 Diag(Loc, PD);
11124
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011125 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011126 }
11127
11128 return false;
11129}
11130
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011131bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11132 CallExpr *CE, FunctionDecl *FD) {
11133 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11134 return false;
11135
Richard Smith76f3f692012-02-22 02:04:18 +000011136 // If we're inside a decltype's expression, don't check for a valid return
11137 // type or construct temporaries until we know whether this is the last call.
11138 if (ExprEvalContexts.back().IsDecltype) {
11139 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11140 return false;
11141 }
11142
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011143 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011144 FunctionDecl *FD;
11145 CallExpr *CE;
11146
11147 public:
11148 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11149 : FD(FD), CE(CE) { }
11150
11151 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11152 if (!FD) {
11153 S.Diag(Loc, diag::err_call_incomplete_return)
11154 << T << CE->getSourceRange();
11155 return;
11156 }
11157
11158 S.Diag(Loc, diag::err_call_function_incomplete_return)
11159 << CE->getSourceRange() << FD->getDeclName() << T;
11160 S.Diag(FD->getLocation(),
11161 diag::note_function_with_incomplete_return_type_declared_here)
11162 << FD->getDeclName();
11163 }
11164 } Diagnoser(FD, CE);
11165
11166 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011167 return true;
11168
11169 return false;
11170}
11171
Douglas Gregor92c3a042011-01-19 16:50:08 +000011172// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011173// will prevent this condition from triggering, which is what we want.
11174void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11175 SourceLocation Loc;
11176
John McCalla52ef082009-11-11 02:41:58 +000011177 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011178 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011179
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011180 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011181 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011182 return;
11183
Douglas Gregor92c3a042011-01-19 16:50:08 +000011184 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11185
John McCallc8d8ac52009-11-12 00:06:05 +000011186 // Greylist some idioms by putting them into a warning subcategory.
11187 if (ObjCMessageExpr *ME
11188 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11189 Selector Sel = ME->getSelector();
11190
John McCallc8d8ac52009-11-12 00:06:05 +000011191 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011192 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011193 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11194
11195 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011196 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011197 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11198 }
John McCalla52ef082009-11-11 02:41:58 +000011199
John McCall5a881bb2009-10-12 21:59:07 +000011200 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011201 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011202 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011203 return;
11204
Douglas Gregor92c3a042011-01-19 16:50:08 +000011205 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011206 Loc = Op->getOperatorLoc();
11207 } else {
11208 // Not an assignment.
11209 return;
11210 }
11211
Douglas Gregor55b38842010-04-14 16:09:52 +000011212 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011213
Daniel Dunbar96a00142012-03-09 18:35:03 +000011214 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011215 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11216 Diag(Loc, diag::note_condition_assign_silence)
11217 << FixItHint::CreateInsertion(Open, "(")
11218 << FixItHint::CreateInsertion(Close, ")");
11219
Douglas Gregor92c3a042011-01-19 16:50:08 +000011220 if (IsOrAssign)
11221 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11222 << FixItHint::CreateReplacement(Loc, "!=");
11223 else
11224 Diag(Loc, diag::note_condition_assign_to_comparison)
11225 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011226}
11227
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011228/// \brief Redundant parentheses over an equality comparison can indicate
11229/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011230void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011231 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011232 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011233 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11234 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011235 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011236 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011237 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011238
Richard Trieuccd891a2011-09-09 01:45:06 +000011239 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011240
11241 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011242 if (opE->getOpcode() == BO_EQ &&
11243 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11244 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011245 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011246
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011247 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011248 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011249 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011250 << FixItHint::CreateRemoval(ParenERange.getBegin())
11251 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011252 Diag(Loc, diag::note_equality_comparison_to_assign)
11253 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011254 }
11255}
11256
John Wiegley429bb272011-04-08 18:41:53 +000011257ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011258 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011259 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11260 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011261
John McCall864c0412011-04-26 20:42:42 +000011262 ExprResult result = CheckPlaceholderExpr(E);
11263 if (result.isInvalid()) return ExprError();
11264 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011265
John McCall864c0412011-04-26 20:42:42 +000011266 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011267 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011268 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11269
John Wiegley429bb272011-04-08 18:41:53 +000011270 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11271 if (ERes.isInvalid())
11272 return ExprError();
11273 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011274
11275 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011276 if (!T->isScalarType()) { // C99 6.8.4.1p1
11277 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11278 << T << E->getSourceRange();
11279 return ExprError();
11280 }
John McCall5a881bb2009-10-12 21:59:07 +000011281 }
11282
John Wiegley429bb272011-04-08 18:41:53 +000011283 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011284}
Douglas Gregor586596f2010-05-06 17:25:47 +000011285
John McCall60d7b3a2010-08-24 06:29:42 +000011286ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011287 Expr *SubExpr) {
11288 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011289 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011290
Richard Trieuccd891a2011-09-09 01:45:06 +000011291 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011292}
John McCall2a984ca2010-10-12 00:20:44 +000011293
John McCall1de4d4e2011-04-07 08:22:57 +000011294namespace {
John McCall755d8492011-04-12 00:42:48 +000011295 /// A visitor for rebuilding a call to an __unknown_any expression
11296 /// to have an appropriate type.
11297 struct RebuildUnknownAnyFunction
11298 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11299
11300 Sema &S;
11301
11302 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11303
11304 ExprResult VisitStmt(Stmt *S) {
11305 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011306 }
11307
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011308 ExprResult VisitExpr(Expr *E) {
11309 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11310 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011311 return ExprError();
11312 }
11313
11314 /// Rebuild an expression which simply semantically wraps another
11315 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011316 template <class T> ExprResult rebuildSugarExpr(T *E) {
11317 ExprResult SubResult = Visit(E->getSubExpr());
11318 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011319
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011320 Expr *SubExpr = SubResult.take();
11321 E->setSubExpr(SubExpr);
11322 E->setType(SubExpr->getType());
11323 E->setValueKind(SubExpr->getValueKind());
11324 assert(E->getObjectKind() == OK_Ordinary);
11325 return E;
John McCall755d8492011-04-12 00:42:48 +000011326 }
11327
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011328 ExprResult VisitParenExpr(ParenExpr *E) {
11329 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011330 }
11331
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011332 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11333 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011334 }
11335
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011336 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11337 ExprResult SubResult = Visit(E->getSubExpr());
11338 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011339
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011340 Expr *SubExpr = SubResult.take();
11341 E->setSubExpr(SubExpr);
11342 E->setType(S.Context.getPointerType(SubExpr->getType()));
11343 assert(E->getValueKind() == VK_RValue);
11344 assert(E->getObjectKind() == OK_Ordinary);
11345 return E;
John McCall755d8492011-04-12 00:42:48 +000011346 }
11347
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011348 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11349 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011350
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011351 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011352
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011353 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011354 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011355 !(isa<CXXMethodDecl>(VD) &&
11356 cast<CXXMethodDecl>(VD)->isInstance()))
11357 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011358
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011359 return E;
John McCall755d8492011-04-12 00:42:48 +000011360 }
11361
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011362 ExprResult VisitMemberExpr(MemberExpr *E) {
11363 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011364 }
11365
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011366 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11367 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011368 }
11369 };
11370}
11371
11372/// Given a function expression of unknown-any type, try to rebuild it
11373/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011374static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11375 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11376 if (Result.isInvalid()) return ExprError();
11377 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011378}
11379
11380namespace {
John McCall379b5152011-04-11 07:02:50 +000011381 /// A visitor for rebuilding an expression of type __unknown_anytype
11382 /// into one which resolves the type directly on the referring
11383 /// expression. Strict preservation of the original source
11384 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011385 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011386 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011387
11388 Sema &S;
11389
11390 /// The current destination type.
11391 QualType DestType;
11392
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011393 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11394 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011395
John McCalla5fc4722011-04-09 22:50:59 +000011396 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011397 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011398 }
11399
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011400 ExprResult VisitExpr(Expr *E) {
11401 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11402 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011403 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011404 }
11405
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011406 ExprResult VisitCallExpr(CallExpr *E);
11407 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011408
John McCalla5fc4722011-04-09 22:50:59 +000011409 /// Rebuild an expression which simply semantically wraps another
11410 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011411 template <class T> ExprResult rebuildSugarExpr(T *E) {
11412 ExprResult SubResult = Visit(E->getSubExpr());
11413 if (SubResult.isInvalid()) return ExprError();
11414 Expr *SubExpr = SubResult.take();
11415 E->setSubExpr(SubExpr);
11416 E->setType(SubExpr->getType());
11417 E->setValueKind(SubExpr->getValueKind());
11418 assert(E->getObjectKind() == OK_Ordinary);
11419 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011420 }
John McCall1de4d4e2011-04-07 08:22:57 +000011421
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011422 ExprResult VisitParenExpr(ParenExpr *E) {
11423 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011424 }
11425
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011426 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11427 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011428 }
11429
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011430 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11431 const PointerType *Ptr = DestType->getAs<PointerType>();
11432 if (!Ptr) {
11433 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11434 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011435 return ExprError();
11436 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011437 assert(E->getValueKind() == VK_RValue);
11438 assert(E->getObjectKind() == OK_Ordinary);
11439 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011440
11441 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011442 DestType = Ptr->getPointeeType();
11443 ExprResult SubResult = Visit(E->getSubExpr());
11444 if (SubResult.isInvalid()) return ExprError();
11445 E->setSubExpr(SubResult.take());
11446 return E;
John McCall755d8492011-04-12 00:42:48 +000011447 }
11448
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011449 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011450
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011451 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011452
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011453 ExprResult VisitMemberExpr(MemberExpr *E) {
11454 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011455 }
John McCalla5fc4722011-04-09 22:50:59 +000011456
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011457 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11458 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011459 }
11460 };
11461}
11462
John McCall379b5152011-04-11 07:02:50 +000011463/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011464ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11465 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011466
11467 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011468 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011469 FK_FunctionPointer,
11470 FK_BlockPointer
11471 };
11472
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011473 FnKind Kind;
11474 QualType CalleeType = CalleeExpr->getType();
11475 if (CalleeType == S.Context.BoundMemberTy) {
11476 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11477 Kind = FK_MemberFunction;
11478 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11479 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11480 CalleeType = Ptr->getPointeeType();
11481 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011482 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011483 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11484 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011485 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011486 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011487
11488 // Verify that this is a legal result type of a function.
11489 if (DestType->isArrayType() || DestType->isFunctionType()) {
11490 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011491 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011492 diagID = diag::err_block_returning_array_function;
11493
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011494 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011495 << DestType->isFunctionType() << DestType;
11496 return ExprError();
11497 }
11498
11499 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011500 E->setType(DestType.getNonLValueExprType(S.Context));
11501 E->setValueKind(Expr::getValueKindForType(DestType));
11502 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011503
11504 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011505 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011506 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011507 Proto->arg_type_begin(),
11508 Proto->getNumArgs(),
11509 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011510 else
11511 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011512 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011513
11514 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011515 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011516 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011517 // Nothing to do.
11518 break;
11519
11520 case FK_FunctionPointer:
11521 DestType = S.Context.getPointerType(DestType);
11522 break;
11523
11524 case FK_BlockPointer:
11525 DestType = S.Context.getBlockPointerType(DestType);
11526 break;
11527 }
11528
11529 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011530 ExprResult CalleeResult = Visit(CalleeExpr);
11531 if (!CalleeResult.isUsable()) return ExprError();
11532 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011533
11534 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011535 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011536}
11537
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011538ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011539 // Verify that this is a legal result type of a call.
11540 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011541 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011542 << DestType->isFunctionType() << DestType;
11543 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011544 }
11545
John McCall48218c62011-07-13 17:56:40 +000011546 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011547 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11548 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11549 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011550 }
John McCall755d8492011-04-12 00:42:48 +000011551
John McCall379b5152011-04-11 07:02:50 +000011552 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011553 E->setType(DestType.getNonReferenceType());
11554 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011555
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011556 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011557}
11558
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011559ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011560 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011561 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011562 assert(E->getValueKind() == VK_RValue);
11563 assert(E->getObjectKind() == OK_Ordinary);
11564
11565 E->setType(DestType);
11566
11567 // Rebuild the sub-expression as the pointee (function) type.
11568 DestType = DestType->castAs<PointerType>()->getPointeeType();
11569
11570 ExprResult Result = Visit(E->getSubExpr());
11571 if (!Result.isUsable()) return ExprError();
11572
11573 E->setSubExpr(Result.take());
11574 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011575 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011576 assert(E->getValueKind() == VK_RValue);
11577 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011578
Sean Callanance9c8312012-03-06 21:34:12 +000011579 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011580
Sean Callanance9c8312012-03-06 21:34:12 +000011581 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011582
Sean Callanance9c8312012-03-06 21:34:12 +000011583 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11584 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011585
Sean Callanance9c8312012-03-06 21:34:12 +000011586 ExprResult Result = Visit(E->getSubExpr());
11587 if (!Result.isUsable()) return ExprError();
11588
11589 E->setSubExpr(Result.take());
11590 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011591 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011592 llvm_unreachable("Unhandled cast type!");
11593 }
John McCall379b5152011-04-11 07:02:50 +000011594}
11595
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011596ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11597 ExprValueKind ValueKind = VK_LValue;
11598 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011599
11600 // We know how to make this work for certain kinds of decls:
11601
11602 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011603 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11604 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11605 DestType = Ptr->getPointeeType();
11606 ExprResult Result = resolveDecl(E, VD);
11607 if (Result.isInvalid()) return ExprError();
11608 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011609 CK_FunctionToPointerDecay, VK_RValue);
11610 }
11611
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011612 if (!Type->isFunctionType()) {
11613 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11614 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011615 return ExprError();
11616 }
John McCall379b5152011-04-11 07:02:50 +000011617
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011618 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11619 if (MD->isInstance()) {
11620 ValueKind = VK_RValue;
11621 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011622 }
11623
John McCall379b5152011-04-11 07:02:50 +000011624 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011625 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011626 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011627
11628 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011629 } else if (isa<VarDecl>(VD)) {
11630 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11631 Type = RefTy->getPointeeType();
11632 } else if (Type->isFunctionType()) {
11633 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11634 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011635 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011636 }
11637
11638 // - nothing else
11639 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011640 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11641 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011642 return ExprError();
11643 }
11644
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011645 VD->setType(DestType);
11646 E->setType(Type);
11647 E->setValueKind(ValueKind);
11648 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011649}
11650
John McCall1de4d4e2011-04-07 08:22:57 +000011651/// Check a cast of an unknown-any type. We intentionally only
11652/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011653ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11654 Expr *CastExpr, CastKind &CastKind,
11655 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011656 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011657 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011658 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011659
Richard Trieuccd891a2011-09-09 01:45:06 +000011660 CastExpr = result.take();
11661 VK = CastExpr->getValueKind();
11662 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011663
Richard Trieuccd891a2011-09-09 01:45:06 +000011664 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011665}
11666
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011667ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11668 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11669}
11670
Richard Trieuccd891a2011-09-09 01:45:06 +000011671static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11672 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011673 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011674 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011675 E = E->IgnoreParenImpCasts();
11676 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11677 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011678 diagID = diag::err_uncasted_call_of_unknown_any;
11679 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011680 break;
John McCall379b5152011-04-11 07:02:50 +000011681 }
John McCall1de4d4e2011-04-07 08:22:57 +000011682 }
11683
John McCall379b5152011-04-11 07:02:50 +000011684 SourceLocation loc;
11685 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011686 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011687 loc = ref->getLocation();
11688 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011689 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011690 loc = mem->getMemberLoc();
11691 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011692 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011693 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011694 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011695 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011696 if (!d) {
11697 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11698 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11699 << orig->getSourceRange();
11700 return ExprError();
11701 }
John McCall379b5152011-04-11 07:02:50 +000011702 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011703 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11704 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011705 return ExprError();
11706 }
11707
11708 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011709
11710 // Never recoverable.
11711 return ExprError();
11712}
11713
John McCall2a984ca2010-10-12 00:20:44 +000011714/// Check for operands with placeholder types and complain if found.
11715/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011716ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011717 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11718 if (!placeholderType) return Owned(E);
11719
11720 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011721
John McCall1de4d4e2011-04-07 08:22:57 +000011722 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011723 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011724 // Try to resolve a single function template specialization.
11725 // This is obligatory.
11726 ExprResult result = Owned(E);
11727 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11728 return result;
11729
11730 // If that failed, try to recover with a call.
11731 } else {
11732 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11733 /*complain*/ true);
11734 return result;
11735 }
11736 }
John McCall1de4d4e2011-04-07 08:22:57 +000011737
John McCall864c0412011-04-26 20:42:42 +000011738 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011739 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011740 ExprResult result = Owned(E);
11741 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11742 /*complain*/ true);
11743 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011744 }
11745
11746 // ARC unbridged casts.
11747 case BuiltinType::ARCUnbridgedCast: {
11748 Expr *realCast = stripARCUnbridgedCast(E);
11749 diagnoseARCUnbridgedCast(realCast);
11750 return Owned(realCast);
11751 }
John McCall864c0412011-04-26 20:42:42 +000011752
John McCall1de4d4e2011-04-07 08:22:57 +000011753 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011754 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011755 return diagnoseUnknownAnyExpr(*this, E);
11756
John McCall3c3b7f92011-10-25 17:37:35 +000011757 // Pseudo-objects.
11758 case BuiltinType::PseudoObject:
11759 return checkPseudoObjectRValue(E);
11760
John McCalle0a22d02011-10-18 21:02:43 +000011761 // Everything else should be impossible.
11762#define BUILTIN_TYPE(Id, SingletonId) \
11763 case BuiltinType::Id:
11764#define PLACEHOLDER_TYPE(Id, SingletonId)
11765#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011766 break;
11767 }
11768
11769 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011770}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011771
Richard Trieuccd891a2011-09-09 01:45:06 +000011772bool Sema::CheckCaseExpression(Expr *E) {
11773 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011774 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011775 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11776 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011777 return false;
11778}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011779
11780/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11781ExprResult
11782Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11783 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11784 "Unknown Objective-C Boolean value!");
11785 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian93a49942012-04-16 21:03:30 +000011786 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011787}