blob: 1628e7f14b10a33bc09fca4c8bb3ad3b4b7108e2 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedmanef331b72012-01-20 01:26:23 +000044#include "TreeTransform.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000046using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Sebastian Redl14b0c192011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redl14b0c192011-09-24 17:48:00 +000066 return true;
67}
David Chisnall0f436562009-08-17 16:35:33 +000068
Ted Kremenekd6cf9122012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenekd6cf9122012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000096 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith6c4c36c2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith5bdaac52012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Jordan Rose0eb3f452012-06-18 22:09:19 +0000133/// \brief Determine whether a FunctionDecl was ever declared with an
134/// explicit storage class.
135static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137 E = D->redecls_end();
138 I != E; ++I) {
139 if (I->getStorageClassAsWritten() != SC_None)
140 return true;
141 }
142 return false;
143}
144
145/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000146/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000147///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000148/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000149/// in many cases it will not behave correctly. This is not enabled in C++ mode
150/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
151/// and so while there may still be user mistakes, most of the time we can't
152/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000153static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
154 const NamedDecl *D,
155 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000156 // This is disabled under C++; there are too many ways for this to fire in
157 // contexts where the warning is a false positive, or where it is technically
158 // correct but benign.
159 if (S.getLangOpts().CPlusPlus)
160 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000161
162 // Check if this is an inlined function or method.
163 FunctionDecl *Current = S.getCurFunctionDecl();
164 if (!Current)
165 return;
166 if (!Current->isInlined())
167 return;
168 if (Current->getLinkage() != ExternalLinkage)
169 return;
170
171 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000172 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000173 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174
Jordan Rose05233272012-06-21 05:54:50 +0000175 // Downgrade from ExtWarn to Extension if
176 // (1) the supposedly external inline function is in the main file,
177 // and probably won't be included anywhere else.
178 // (2) the thing we're referencing is a pure function.
179 // (3) the thing we're referencing is another inline function.
180 // This last can give us false negatives, but it's better than warning on
181 // wrappers for simple C library functions.
182 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
183 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
184 if (!DowngradeWarning && UsedFn)
185 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
186
187 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
188 : diag::warn_internal_in_extern_inline)
189 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000190
191 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000192 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000193 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
194 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
195 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
196 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
197 }
198
199 S.Diag(D->getCanonicalDecl()->getLocation(),
200 diag::note_internal_decl_declared_here)
201 << D;
202}
203
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000204/// \brief Determine whether the use of this declaration is valid, and
205/// emit any corresponding diagnostics.
206///
207/// This routine diagnoses various problems with referencing
208/// declarations that can occur when using a declaration. For example,
209/// it might warn if a deprecated or unavailable declaration is being
210/// used, or produce an error (and return true) if a C++0x deleted
211/// function is being used.
212///
213/// \returns true if there was an error (this declaration cannot be
214/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000215///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000216bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000217 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000219 // If there were any diagnostics suppressed by template argument deduction,
220 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000221 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000222 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
223 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000224 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000225 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
226 Diag(Suppressed[I].first, Suppressed[I].second);
227
228 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000229 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000230 // entry from the table, because we want to avoid ever emitting these
231 // diagnostics again.
232 Suppressed.clear();
233 }
234 }
235
Richard Smith34b41d92011-02-20 03:19:35 +0000236 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000237 if (ParsingInitForAutoVars.count(D)) {
238 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
239 << D->getDeclName();
240 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000241 }
242
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000243 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000245 if (FD->isDeleted()) {
246 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000247 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000248 return true;
249 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000250 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000251 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000252
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000253 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000254 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000255 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Jordan Rose106af9e2012-06-15 18:19:48 +0000256
Jordan Rose0eb3f452012-06-18 22:09:19 +0000257 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000258
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000259 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000260}
261
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000262/// \brief Retrieve the message suffix that should be added to a
263/// diagnostic complaining about the given function being deleted or
264/// unavailable.
265std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
266 // FIXME: C++0x implicitly-deleted special member functions could be
267 // detected here so that we could improve diagnostics to say, e.g.,
268 // "base class 'A' had a deleted copy constructor".
269 if (FD->isDeleted())
270 return std::string();
271
272 std::string Message;
273 if (FD->getAvailability(&Message))
274 return ": " + Message;
275
276 return std::string();
277}
278
John McCall3323fad2011-09-09 07:56:05 +0000279/// DiagnoseSentinelCalls - This routine checks whether a call or
280/// message-send is to a declaration with the sentinel attribute, and
281/// if so, it checks that the requirements of the sentinel are
282/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000283void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000284 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000285 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000286 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000287 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000288
John McCall3323fad2011-09-09 07:56:05 +0000289 // The number of formal parameters of the declaration.
290 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000291
John McCall3323fad2011-09-09 07:56:05 +0000292 // The kind of declaration. This is also an index into a %select in
293 // the diagnostic.
294 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
295
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000296 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000297 numFormalParams = MD->param_size();
298 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000299 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000300 numFormalParams = FD->param_size();
301 calleeType = CT_Function;
302 } else if (isa<VarDecl>(D)) {
303 QualType type = cast<ValueDecl>(D)->getType();
304 const FunctionType *fn = 0;
305 if (const PointerType *ptr = type->getAs<PointerType>()) {
306 fn = ptr->getPointeeType()->getAs<FunctionType>();
307 if (!fn) return;
308 calleeType = CT_Function;
309 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
310 fn = ptr->getPointeeType()->castAs<FunctionType>();
311 calleeType = CT_Block;
312 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000313 return;
John McCall3323fad2011-09-09 07:56:05 +0000314 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000315
John McCall3323fad2011-09-09 07:56:05 +0000316 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
317 numFormalParams = proto->getNumArgs();
318 } else {
319 numFormalParams = 0;
320 }
321 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000322 return;
323 }
John McCall3323fad2011-09-09 07:56:05 +0000324
325 // "nullPos" is the number of formal parameters at the end which
326 // effectively count as part of the variadic arguments. This is
327 // useful if you would prefer to not have *any* formal parameters,
328 // but the language forces you to have at least one.
329 unsigned nullPos = attr->getNullPos();
330 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
331 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
332
333 // The number of arguments which should follow the sentinel.
334 unsigned numArgsAfterSentinel = attr->getSentinel();
335
336 // If there aren't enough arguments for all the formal parameters,
337 // the sentinel, and the args after the sentinel, complain.
338 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000339 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000340 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000341 return;
342 }
John McCall3323fad2011-09-09 07:56:05 +0000343
344 // Otherwise, find the sentinel expression.
345 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000346 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000347 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000348 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000349
John McCall3323fad2011-09-09 07:56:05 +0000350 // Pick a reasonable string to insert. Optimistically use 'nil' or
351 // 'NULL' if those are actually defined in the context. Only use
352 // 'nil' for ObjC methods, where it's much more likely that the
353 // variadic arguments form a list of object pointers.
354 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000355 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
356 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000357 if (calleeType == CT_Method &&
358 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000359 NullValue = "nil";
360 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
361 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000362 else
John McCall3323fad2011-09-09 07:56:05 +0000363 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000364
365 if (MissingNilLoc.isInvalid())
366 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
367 else
368 Diag(MissingNilLoc, diag::warn_missing_sentinel)
369 << calleeType
370 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000371 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000372}
373
Richard Trieuccd891a2011-09-09 01:45:06 +0000374SourceRange Sema::getExprRange(Expr *E) const {
375 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000376}
377
Chris Lattnere7a2e912008-07-25 21:10:04 +0000378//===----------------------------------------------------------------------===//
379// Standard Promotions and Conversions
380//===----------------------------------------------------------------------===//
381
Chris Lattnere7a2e912008-07-25 21:10:04 +0000382/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000383ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000384 // Handle any placeholder expressions which made it here.
385 if (E->getType()->isPlaceholderType()) {
386 ExprResult result = CheckPlaceholderExpr(E);
387 if (result.isInvalid()) return ExprError();
388 E = result.take();
389 }
390
Chris Lattnere7a2e912008-07-25 21:10:04 +0000391 QualType Ty = E->getType();
392 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
393
Chris Lattnere7a2e912008-07-25 21:10:04 +0000394 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000395 E = ImpCastExprToType(E, Context.getPointerType(Ty),
396 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000397 else if (Ty->isArrayType()) {
398 // In C90 mode, arrays only promote to pointers if the array expression is
399 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
400 // type 'array of type' is converted to an expression that has type 'pointer
401 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
402 // that has type 'array of type' ...". The relevant change is "an lvalue"
403 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000404 //
405 // C++ 4.2p1:
406 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
407 // T" can be converted to an rvalue of type "pointer to T".
408 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000409 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
411 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000412 }
John Wiegley429bb272011-04-08 18:41:53 +0000413 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000414}
415
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000416static void CheckForNullPointerDereference(Sema &S, Expr *E) {
417 // Check to see if we are dereferencing a null pointer. If so,
418 // and if not volatile-qualified, this is undefined behavior that the
419 // optimizer will delete, so warn about it. People sometimes try to use this
420 // to get a deterministic trap and are surprised by clang's behavior. This
421 // only handles the pattern "*null", which is a very syntactic check.
422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
423 if (UO->getOpcode() == UO_Deref &&
424 UO->getSubExpr()->IgnoreParenCasts()->
425 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
426 !UO->getType().isVolatileQualified()) {
427 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
428 S.PDiag(diag::warn_indirection_through_null)
429 << UO->getSubExpr()->getSourceRange());
430 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
431 S.PDiag(diag::note_indirection_through_null));
432 }
433}
434
John Wiegley429bb272011-04-08 18:41:53 +0000435ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000436 // Handle any placeholder expressions which made it here.
437 if (E->getType()->isPlaceholderType()) {
438 ExprResult result = CheckPlaceholderExpr(E);
439 if (result.isInvalid()) return ExprError();
440 E = result.take();
441 }
442
John McCall0ae287a2010-12-01 04:43:34 +0000443 // C++ [conv.lval]p1:
444 // A glvalue of a non-function, non-array type T can be
445 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000446 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000447
John McCall409fa9a2010-12-06 20:48:59 +0000448 QualType T = E->getType();
449 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000450
John McCall409fa9a2010-12-06 20:48:59 +0000451 // We don't want to throw lvalue-to-rvalue casts on top of
452 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000453 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000454 (E->getType() == Context.OverloadTy ||
455 T->isDependentType() ||
456 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000457 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000458
459 // The C standard is actually really unclear on this point, and
460 // DR106 tells us what the result should be but not why. It's
461 // generally best to say that void types just doesn't undergo
462 // lvalue-to-rvalue at all. Note that expressions of unqualified
463 // 'void' type are never l-values, but qualified void can be.
464 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000465 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000466
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000467 CheckForNullPointerDereference(*this, E);
468
John McCall409fa9a2010-12-06 20:48:59 +0000469 // C++ [conv.lval]p1:
470 // [...] If T is a non-class type, the type of the prvalue is the
471 // cv-unqualified version of T. Otherwise, the type of the
472 // rvalue is T.
473 //
474 // C99 6.3.2.1p2:
475 // If the lvalue has qualified type, the value has the unqualified
476 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000477 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000478 if (T.hasQualifiers())
479 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000480
Eli Friedmand2cce132012-02-02 23:15:15 +0000481 UpdateMarkingForLValueToRValue(E);
482
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000483 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
484 E, 0, VK_RValue));
485
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000486 // C11 6.3.2.1p2:
487 // ... if the lvalue has atomic type, the value has the non-atomic version
488 // of the type of the lvalue ...
489 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
490 T = Atomic->getValueType().getUnqualifiedType();
491 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
492 Res.get(), 0, VK_RValue));
493 }
494
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000495 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000496}
497
John Wiegley429bb272011-04-08 18:41:53 +0000498ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
499 ExprResult Res = DefaultFunctionArrayConversion(E);
500 if (Res.isInvalid())
501 return ExprError();
502 Res = DefaultLvalueConversion(Res.take());
503 if (Res.isInvalid())
504 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000505 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000506}
507
508
Chris Lattnere7a2e912008-07-25 21:10:04 +0000509/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000510/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000511/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000512/// apply if the array is an argument to the sizeof or address (&) operators.
513/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000514ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000515 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000516 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
517 if (Res.isInvalid())
518 return Owned(E);
519 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000520
John McCall0ae287a2010-12-01 04:43:34 +0000521 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000522 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000523
524 // Half FP is a bit different: it's a storage-only type, meaning that any
525 // "use" of it should be promoted to float.
526 if (Ty->isHalfType())
527 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
528
John McCall0ae287a2010-12-01 04:43:34 +0000529 // Try to perform integral promotions if the object has a theoretically
530 // promotable type.
531 if (Ty->isIntegralOrUnscopedEnumerationType()) {
532 // C99 6.3.1.1p2:
533 //
534 // The following may be used in an expression wherever an int or
535 // unsigned int may be used:
536 // - an object or expression with an integer type whose integer
537 // conversion rank is less than or equal to the rank of int
538 // and unsigned int.
539 // - A bit-field of type _Bool, int, signed int, or unsigned int.
540 //
541 // If an int can represent all values of the original type, the
542 // value is converted to an int; otherwise, it is converted to an
543 // unsigned int. These are called the integer promotions. All
544 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000545
John McCall0ae287a2010-12-01 04:43:34 +0000546 QualType PTy = Context.isPromotableBitField(E);
547 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000548 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
549 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000550 }
551 if (Ty->isPromotableIntegerType()) {
552 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000553 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
554 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000555 }
Eli Friedman04e83572009-08-20 04:21:42 +0000556 }
John Wiegley429bb272011-04-08 18:41:53 +0000557 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000558}
559
Chris Lattner05faf172008-07-25 22:25:12 +0000560/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000561/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000562/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000563ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
564 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000565 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000566
John Wiegley429bb272011-04-08 18:41:53 +0000567 ExprResult Res = UsualUnaryConversions(E);
568 if (Res.isInvalid())
569 return Owned(E);
570 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000571
Chris Lattner05faf172008-07-25 22:25:12 +0000572 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000573 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
575
John McCall96a914a2011-08-27 22:06:17 +0000576 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000577 // promotion, even on class types, but note:
578 // C++11 [conv.lval]p2:
579 // When an lvalue-to-rvalue conversion occurs in an unevaluated
580 // operand or a subexpression thereof the value contained in the
581 // referenced object is not accessed. Otherwise, if the glvalue
582 // has a class type, the conversion copy-initializes a temporary
583 // of type T from the glvalue and the result of the conversion
584 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000585 // FIXME: add some way to gate this entire thing for correctness in
586 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000587 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000588 ExprResult Temp = PerformCopyInitialization(
589 InitializedEntity::InitializeTemporary(E->getType()),
590 E->getExprLoc(),
591 Owned(E));
592 if (Temp.isInvalid())
593 return ExprError();
594 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000595 }
596
John Wiegley429bb272011-04-08 18:41:53 +0000597 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000598}
599
Richard Smith831421f2012-06-25 20:30:08 +0000600/// Determine the degree of POD-ness for an expression.
601/// Incomplete types are considered POD, since this check can be performed
602/// when we're in an unevaluated context.
603Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000604 if (Ty->isIncompleteType()) {
605 if (Ty->isObjCObjectType())
606 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000607 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000608 }
609
610 if (Ty.isCXX98PODType(Context))
611 return VAK_Valid;
612
Richard Smith831421f2012-06-25 20:30:08 +0000613 // C++0x [expr.call]p7:
614 // Passing a potentially-evaluated argument of class type (Clause 9)
615 // having a non-trivial copy constructor, a non-trivial move constructor,
616 // or a non-trivial destructor, with no corresponding parameter,
617 // is conditionally-supported with implementation-defined semantics.
Richard Smith831421f2012-06-25 20:30:08 +0000618 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
619 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
620 if (Record->hasTrivialCopyConstructor() &&
621 Record->hasTrivialMoveConstructor() &&
622 Record->hasTrivialDestructor())
623 return VAK_ValidInCXX11;
624
625 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
626 return VAK_Valid;
627 return VAK_Invalid;
628}
629
630bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
631 // Don't allow one to pass an Objective-C interface to a vararg.
632 const QualType & Ty = E->getType();
633
634 // Complain about passing non-POD types through varargs.
635 switch (isValidVarArgType(Ty)) {
636 case VAK_Valid:
637 break;
638 case VAK_ValidInCXX11:
639 DiagRuntimeBehavior(E->getLocStart(), 0,
640 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
641 << E->getType() << CT);
642 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000643 case VAK_Invalid: {
644 if (Ty->isObjCObjectType())
645 return DiagRuntimeBehavior(E->getLocStart(), 0,
646 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
647 << Ty << CT);
648
Richard Smith831421f2012-06-25 20:30:08 +0000649 return DiagRuntimeBehavior(E->getLocStart(), 0,
650 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
651 << getLangOpts().CPlusPlus0x << Ty << CT);
652 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000653 }
Richard Smith831421f2012-06-25 20:30:08 +0000654 // c++ rules are enforced elsewhere.
655 return false;
656}
657
Chris Lattner312531a2009-04-12 08:11:20 +0000658/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000659/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000660ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000661 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000662 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000663 // Strip the unbridged-cast placeholder expression off, if applicable.
664 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
665 (CT == VariadicMethod ||
666 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
667 E = stripARCUnbridgedCast(E);
668
669 // Otherwise, do normal placeholder checking.
670 } else {
671 ExprResult ExprRes = CheckPlaceholderExpr(E);
672 if (ExprRes.isInvalid())
673 return ExprError();
674 E = ExprRes.take();
675 }
676 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000677
John McCall5acb0c92011-10-17 18:40:02 +0000678 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000679 if (ExprRes.isInvalid())
680 return ExprError();
681 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Richard Smith831421f2012-06-25 20:30:08 +0000683 // Diagnostics regarding non-POD argument types are
684 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000685 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000686 // Turn this into a trap.
687 CXXScopeSpec SS;
688 SourceLocation TemplateKWLoc;
689 UnqualifiedId Name;
690 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
691 E->getLocStart());
692 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
693 Name, true, false);
694 if (TrapFn.isInvalid())
695 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000696
Richard Smith831421f2012-06-25 20:30:08 +0000697 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
698 E->getLocStart(), MultiExprArg(),
699 E->getLocEnd());
700 if (Call.isInvalid())
701 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000702
Richard Smith831421f2012-06-25 20:30:08 +0000703 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
704 Call.get(), E);
705 if (Comma.isInvalid())
706 return ExprError();
707 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000708 }
Richard Smith831421f2012-06-25 20:30:08 +0000709
David Blaikie4e4d0842012-03-11 07:00:24 +0000710 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000711 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000712 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000713 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000714
John Wiegley429bb272011-04-08 18:41:53 +0000715 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000716}
717
Richard Trieu8289f492011-09-02 20:58:51 +0000718/// \brief Converts an integer to complex float type. Helper function of
719/// UsualArithmeticConversions()
720///
721/// \return false if the integer expression is an integer type and is
722/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000723static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
724 ExprResult &ComplexExpr,
725 QualType IntTy,
726 QualType ComplexTy,
727 bool SkipCast) {
728 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
729 if (SkipCast) return false;
730 if (IntTy->isIntegerType()) {
731 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
732 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
733 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000734 CK_FloatingRealToComplex);
735 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000736 assert(IntTy->isComplexIntegerType());
737 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000738 CK_IntegralComplexToFloatingComplex);
739 }
740 return false;
741}
742
743/// \brief Takes two complex float types and converts them to the same type.
744/// Helper function of UsualArithmeticConversions()
745static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000746handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
747 ExprResult &RHS, QualType LHSType,
748 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000749 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000750 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000751
752 if (order < 0) {
753 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000754 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000755 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
756 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000757 }
758 if (order > 0)
759 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000760 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
761 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000762}
763
764/// \brief Converts otherExpr to complex float and promotes complexExpr if
765/// necessary. Helper function of UsualArithmeticConversions()
766static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000767 ExprResult &ComplexExpr,
768 ExprResult &OtherExpr,
769 QualType ComplexTy,
770 QualType OtherTy,
771 bool ConvertComplexExpr,
772 bool ConvertOtherExpr) {
773 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000774
775 // If just the complexExpr is complex, the otherExpr needs to be converted,
776 // and the complexExpr might need to be promoted.
777 if (order > 0) { // complexExpr is wider
778 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (ConvertOtherExpr) {
780 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
781 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
782 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000783 CK_FloatingRealToComplex);
784 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000785 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000786 }
787
788 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000789 QualType result = (order == 0 ? ComplexTy :
790 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000791
792 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000793 if (ConvertOtherExpr)
794 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000795 CK_FloatingRealToComplex);
796
797 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000798 if (ConvertComplexExpr && order < 0)
799 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000800 CK_FloatingComplexCast);
801
802 return result;
803}
804
805/// \brief Handle arithmetic conversion with complex types. Helper function of
806/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000807static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
808 ExprResult &RHS, QualType LHSType,
809 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000811 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000812 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000813 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000814 return LHSType;
815 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000816 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000817 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000818
819 // This handles complex/complex, complex/float, or float/complex.
820 // When both operands are complex, the shorter operand is converted to the
821 // type of the longer, and that is the type of the result. This corresponds
822 // to what is done when combining two real floating-point operands.
823 // The fun begins when size promotion occur across type domains.
824 // From H&S 6.3.4: When one operand is complex and the other is a real
825 // floating-point type, the less precise type is converted, within it's
826 // real or complex domain, to the precision of the other type. For example,
827 // when combining a "long double" with a "double _Complex", the
828 // "double _Complex" is promoted to "long double _Complex".
829
Richard Trieucafd30b2011-09-06 18:25:09 +0000830 bool LHSComplexFloat = LHSType->isComplexType();
831 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000832
833 // If both are complex, just cast to the more precise type.
834 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000835 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
836 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000837 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000838
839 // If only one operand is complex, promote it if necessary and convert the
840 // other operand to complex.
841 if (LHSComplexFloat)
842 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000843 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000844 /*convertOtherExpr*/ true);
845
846 assert(RHSComplexFloat);
847 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000848 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000849 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000850}
851
852/// \brief Hande arithmetic conversion from integer to float. Helper function
853/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000854static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
855 ExprResult &IntExpr,
856 QualType FloatTy, QualType IntTy,
857 bool ConvertFloat, bool ConvertInt) {
858 if (IntTy->isIntegerType()) {
859 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000860 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000861 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000862 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000863 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000864 }
865
866 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000867 assert(IntTy->isComplexIntegerType());
868 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000869
870 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000871 if (ConvertInt)
872 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000873 CK_IntegralComplexToFloatingComplex);
874
875 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000876 if (ConvertFloat)
877 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000878 CK_FloatingRealToComplex);
879
880 return result;
881}
882
883/// \brief Handle arithmethic conversion with floating point types. Helper
884/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000885static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
886 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000887 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000888 bool LHSFloat = LHSType->isRealFloatingType();
889 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000890
891 // If we have two real floating types, convert the smaller operand
892 // to the bigger result.
893 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000894 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000895 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000896 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
897 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000898 }
899
900 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000901 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000902 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
903 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000904 }
905
906 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000907 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000908 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000909 /*convertInt=*/ true);
910 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000911 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000912 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000913 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000914}
915
916/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000917/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000918// FIXME: if the operands are (int, _Complex long), we currently
919// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000920static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
921 ExprResult &RHS, QualType LHSType,
922 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000923 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000924 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
925 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000926
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000927 if (LHSComplexInt && RHSComplexInt) {
928 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
929 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000930 assert(order && "inequal types with equal element ordering");
931 if (order > 0) {
932 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000933 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
934 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000935 }
936
Richard Trieuccd891a2011-09-09 01:45:06 +0000937 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000938 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
939 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000940 }
941
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000942 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000943 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000944 // FIXME: This needs to take integer ranks into account
945 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
946 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000947 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
948 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000949 }
950
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000951 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000952 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000953 // FIXME: This needs to take integer ranks into account
954 if (!IsCompAssign) {
955 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
956 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000957 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000958 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000959 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000960}
961
962/// \brief Handle integer arithmetic conversions. Helper function of
963/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000964static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
965 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000966 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000967 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000968 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
969 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
970 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
971 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000972 // Same signedness; use the higher-ranked type
973 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000974 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
975 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000976 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000977 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
978 return RHSType;
979 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000980 // The unsigned type has greater than or equal rank to the
981 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000982 if (RHSSigned) {
983 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
984 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000985 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000986 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
987 return RHSType;
988 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000989 // The two types are different widths; if we are here, that
990 // means the signed type is larger than the unsigned type, so
991 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000992 if (LHSSigned) {
993 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
994 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000995 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000996 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
997 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000998 } else {
999 // The signed type is higher-ranked than the unsigned type,
1000 // but isn't actually any bigger (like unsigned int and long
1001 // on most 32-bit systems). Use the unsigned type corresponding
1002 // to the signed type.
1003 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001004 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1005 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001006 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001007 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001008 return result;
1009 }
1010}
1011
Chris Lattnere7a2e912008-07-25 21:10:04 +00001012/// UsualArithmeticConversions - Performs various conversions that are common to
1013/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001014/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001015/// responsible for emitting appropriate error diagnostics.
1016/// FIXME: verify the conversion rules for "complex int" are consistent with
1017/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001018QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001019 bool IsCompAssign) {
1020 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001021 LHS = UsualUnaryConversions(LHS.take());
1022 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001023 return QualType();
1024 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001025
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001026 RHS = UsualUnaryConversions(RHS.take());
1027 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001028 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001029
Mike Stump1eb44332009-09-09 15:08:12 +00001030 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001031 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001032 QualType LHSType =
1033 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1034 QualType RHSType =
1035 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001036
Eli Friedman860a3192012-06-16 02:19:17 +00001037 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1038 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1039 LHSType = AtomicLHS->getValueType();
1040
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001041 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001042 if (LHSType == RHSType)
1043 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001044
1045 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1046 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001047 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001048 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001049
John McCallcf33b242010-11-13 08:17:45 +00001050 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001051 QualType LHSUnpromotedType = LHSType;
1052 if (LHSType->isPromotableIntegerType())
1053 LHSType = Context.getPromotedIntegerType(LHSType);
1054 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001055 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001056 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001057 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001058 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001059
John McCallcf33b242010-11-13 08:17:45 +00001060 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001061 if (LHSType == RHSType)
1062 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001063
1064 // At this point, we have two different arithmetic types.
1065
1066 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001067 if (LHSType->isComplexType() || RHSType->isComplexType())
1068 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001069 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001070
1071 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001072 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1073 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001074 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001075
1076 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001077 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001078 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001079 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001080
1081 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001082 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001083 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001084}
1085
Chris Lattnere7a2e912008-07-25 21:10:04 +00001086//===----------------------------------------------------------------------===//
1087// Semantic Analysis for various Expression Types
1088//===----------------------------------------------------------------------===//
1089
1090
Peter Collingbournef111d932011-04-15 00:35:48 +00001091ExprResult
1092Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1093 SourceLocation DefaultLoc,
1094 SourceLocation RParenLoc,
1095 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001096 MultiTypeArg ArgTypes,
1097 MultiExprArg ArgExprs) {
1098 unsigned NumAssocs = ArgTypes.size();
1099 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001100
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001101 ParsedType *ParsedTypes = ArgTypes.get();
1102 Expr **Exprs = ArgExprs.get();
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
John McCall2b5289b2010-08-23 07:28:44 +00001436 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001437 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001438 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001439 TemplateArgs = &Buffer;
1440 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001441 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001442 TemplateArgs = 0;
1443 }
1444}
1445
John McCall578b69b2009-12-16 08:11:27 +00001446/// Diagnose an empty lookup.
1447///
1448/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001449bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001450 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001451 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001452 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001453 DeclarationName Name = R.getLookupName();
1454
John McCall578b69b2009-12-16 08:11:27 +00001455 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001456 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001457 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1458 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001459 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001460 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001461 diagnostic_suggest = diag::err_undeclared_use_suggest;
1462 }
John McCall578b69b2009-12-16 08:11:27 +00001463
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001464 // If the original lookup was an unqualified lookup, fake an
1465 // unqualified lookup. This is useful when (for example) the
1466 // original lookup would not have found something because it was a
1467 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001468 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1469 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001470 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001471 if (isa<CXXRecordDecl>(DC)) {
1472 LookupQualifiedName(R, DC);
1473
1474 if (!R.empty()) {
1475 // Don't give errors about ambiguities in this lookup.
1476 R.suppressDiagnostics();
1477
Francois Pichete6226ae2011-11-17 03:44:24 +00001478 // During a default argument instantiation the CurContext points
1479 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1480 // function parameter list, hence add an explicit check.
1481 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1482 ActiveTemplateInstantiations.back().Kind ==
1483 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001484 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1485 bool isInstance = CurMethod &&
1486 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001487 DC == CurMethod->getParent() && !isDefaultArgument;
1488
John McCall578b69b2009-12-16 08:11:27 +00001489
1490 // Give a code modification hint to insert 'this->'.
1491 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1492 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001493 if (getLangOpts().MicrosoftMode)
1494 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001495 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001496 Diag(R.getNameLoc(), diagnostic) << Name
1497 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001498 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1499 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001500
1501
1502 CXXMethodDecl *DepMethod;
1503 if (CurMethod->getTemplatedKind() ==
1504 FunctionDecl::TK_FunctionTemplateSpecialization)
1505 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1506 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1507 else
1508 DepMethod = cast<CXXMethodDecl>(
1509 CurMethod->getInstantiatedFromMemberFunction());
1510 assert(DepMethod && "No template pattern found");
1511
1512 QualType DepThisType = DepMethod->getThisType(Context);
1513 CheckCXXThisCapture(R.getNameLoc());
1514 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1515 R.getNameLoc(), DepThisType, false);
1516 TemplateArgumentListInfo TList;
1517 if (ULE->hasExplicitTemplateArgs())
1518 ULE->copyTemplateArgumentsInto(TList);
1519
1520 CXXScopeSpec SS;
1521 SS.Adopt(ULE->getQualifierLoc());
1522 CXXDependentScopeMemberExpr *DepExpr =
1523 CXXDependentScopeMemberExpr::Create(
1524 Context, DepThis, DepThisType, true, SourceLocation(),
1525 SS.getWithLocInContext(Context),
1526 ULE->getTemplateKeywordLoc(), 0,
1527 R.getLookupNameInfo(),
1528 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1529 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001530 } else {
John McCall578b69b2009-12-16 08:11:27 +00001531 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001532 }
John McCall578b69b2009-12-16 08:11:27 +00001533
1534 // Do we really want to note all of these?
1535 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1536 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1537
Francois Pichete6226ae2011-11-17 03:44:24 +00001538 // Return true if we are inside a default argument instantiation
1539 // and the found name refers to an instance member function, otherwise
1540 // the function calling DiagnoseEmptyLookup will try to create an
1541 // implicit member call and this is wrong for default argument.
1542 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1543 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1544 return true;
1545 }
1546
John McCall578b69b2009-12-16 08:11:27 +00001547 // Tell the callee to try to recover.
1548 return false;
1549 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001550
1551 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001552 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001553
1554 // In Microsoft mode, if we are performing lookup from within a friend
1555 // function definition declared at class scope then we must set
1556 // DC to the lexical parent to be able to search into the parent
1557 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001558 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001559 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1560 DC->getLexicalParent()->isRecord())
1561 DC = DC->getLexicalParent();
1562 else
1563 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001564 }
1565
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001566 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001567 TypoCorrection Corrected;
1568 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001569 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001570 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1571 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001572 R.setLookupName(Corrected.getCorrection());
1573
Hans Wennborg701d1e72011-07-12 08:45:31 +00001574 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001575 if (Corrected.isOverloaded()) {
1576 OverloadCandidateSet OCS(R.getNameLoc());
1577 OverloadCandidateSet::iterator Best;
1578 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1579 CDEnd = Corrected.end();
1580 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001581 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001582 dyn_cast<FunctionTemplateDecl>(*CD))
1583 AddTemplateOverloadCandidate(
1584 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001585 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001586 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1587 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1588 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001589 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001590 }
1591 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1592 case OR_Success:
1593 ND = Best->Function;
1594 break;
1595 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001596 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001597 }
1598 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001599 R.addDecl(ND);
1600 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001601 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001602 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1603 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001604 else
1605 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001606 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001607 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001608 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1609 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001610 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001611 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001612
1613 // Tell the callee to try to recover.
1614 return false;
1615 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001616
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001617 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001618 // FIXME: If we ended up with a typo for a type name or
1619 // Objective-C class name, we're in trouble because the parser
1620 // is in the wrong place to recover. Suggest the typo
1621 // correction, but don't make it a fix-it since we're not going
1622 // to recover well anyway.
1623 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001624 Diag(R.getNameLoc(), diagnostic_suggest)
1625 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001626 else
1627 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001628 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001629 << SS.getRange();
1630
1631 // Don't try to recover; it won't work.
1632 return true;
1633 }
1634 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001635 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001636 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001637 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001638 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001639 else
Douglas Gregord203a162010-01-01 00:15:04 +00001640 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001641 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001642 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001643 return true;
1644 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001645 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001646 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001647
1648 // Emit a special diagnostic for failed member lookups.
1649 // FIXME: computing the declaration context might fail here (?)
1650 if (!SS.isEmpty()) {
1651 Diag(R.getNameLoc(), diag::err_no_member)
1652 << Name << computeDeclContext(SS, false)
1653 << SS.getRange();
1654 return true;
1655 }
1656
John McCall578b69b2009-12-16 08:11:27 +00001657 // Give up, we can't recover.
1658 Diag(R.getNameLoc(), diagnostic) << Name;
1659 return true;
1660}
1661
John McCall60d7b3a2010-08-24 06:29:42 +00001662ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001663 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001664 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001665 UnqualifiedId &Id,
1666 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001667 bool IsAddressOfOperand,
1668 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001669 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001670 "cannot be direct & operand and have a trailing lparen");
1671
1672 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001673 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001674
John McCall129e2df2009-11-30 22:42:35 +00001675 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001676
1677 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001678 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001679 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001680 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001681
Abramo Bagnara25777432010-08-11 22:01:17 +00001682 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001683 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001684 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001685
John McCallf7a1a742009-11-24 19:00:30 +00001686 // C++ [temp.dep.expr]p3:
1687 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001688 // -- an identifier that was declared with a dependent type,
1689 // (note: handled after lookup)
1690 // -- a template-id that is dependent,
1691 // (note: handled in BuildTemplateIdExpr)
1692 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001693 // -- a nested-name-specifier that contains a class-name that
1694 // names a dependent type.
1695 // Determine whether this is a member of an unknown specialization;
1696 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001697 bool DependentID = false;
1698 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1699 Name.getCXXNameType()->isDependentType()) {
1700 DependentID = true;
1701 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001702 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001703 if (RequireCompleteDeclContext(SS, DC))
1704 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001705 } else {
1706 DependentID = true;
1707 }
1708 }
1709
Chris Lattner337e5502011-02-18 01:27:55 +00001710 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001711 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1712 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001713
John McCallf7a1a742009-11-24 19:00:30 +00001714 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001715 LookupResult R(*this, NameInfo,
1716 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1717 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001718 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001719 // Lookup the template name again to correctly establish the context in
1720 // which it was found. This is really unfortunate as we already did the
1721 // lookup to determine that it was a template name in the first place. If
1722 // this becomes a performance hit, we can work harder to preserve those
1723 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001724 bool MemberOfUnknownSpecialization;
1725 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1726 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001727
1728 if (MemberOfUnknownSpecialization ||
1729 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001730 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1731 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001732 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001733 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001734 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001736 // If the result might be in a dependent base class, this is a dependent
1737 // id-expression.
1738 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001739 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1740 IsAddressOfOperand, TemplateArgs);
1741
John McCallf7a1a742009-11-24 19:00:30 +00001742 // If this reference is in an Objective-C method, then we need to do
1743 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001744 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001745 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001746 if (E.isInvalid())
1747 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Chris Lattner337e5502011-02-18 01:27:55 +00001749 if (Expr *Ex = E.takeAs<Expr>())
1750 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001751 }
Chris Lattner8a934232008-03-31 00:36:02 +00001752 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001753
John McCallf7a1a742009-11-24 19:00:30 +00001754 if (R.isAmbiguous())
1755 return ExprError();
1756
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001757 // Determine whether this name might be a candidate for
1758 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001759 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001760
John McCallf7a1a742009-11-24 19:00:30 +00001761 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001763 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001764 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001765 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1766 if (D) R.addDecl(D);
1767 }
1768
1769 // If this name wasn't predeclared and if this is not a function
1770 // call, diagnose the problem.
1771 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001772
1773 // In Microsoft mode, if we are inside a template class member function
1774 // and we can't resolve an identifier then assume the identifier is type
1775 // dependent. The goal is to postpone name lookup to instantiation time
1776 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001777 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001778 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001779 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1780 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001781
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001782 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001783 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001784 return ExprError();
1785
1786 assert(!R.empty() &&
1787 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001788
1789 // If we found an Objective-C instance variable, let
1790 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001791 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001792 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1793 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001794 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001795 // In a hopelessly buggy code, Objective-C instance variable
1796 // lookup fails and no expression will be built to reference it.
1797 if (!E.isInvalid() && !E.get())
1798 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001799 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001800 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 }
1802 }
Mike Stump1eb44332009-09-09 15:08:12 +00001803
John McCallf7a1a742009-11-24 19:00:30 +00001804 // This is guaranteed from this point on.
1805 assert(!R.empty() || ADL);
1806
John McCallaa81e162009-12-01 22:10:20 +00001807 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001808 // C++ [class.mfct.non-static]p3:
1809 // When an id-expression that is not part of a class member access
1810 // syntax and not used to form a pointer to member is used in the
1811 // body of a non-static member function of class X, if name lookup
1812 // resolves the name in the id-expression to a non-static non-type
1813 // member of some class C, the id-expression is transformed into a
1814 // class member access expression using (*this) as the
1815 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001816 //
1817 // But we don't actually need to do this for '&' operands if R
1818 // resolved to a function or overloaded function set, because the
1819 // expression is ill-formed if it actually works out to be a
1820 // non-static member function:
1821 //
1822 // C++ [expr.ref]p4:
1823 // Otherwise, if E1.E2 refers to a non-static member function. . .
1824 // [t]he expression can be used only as the left-hand operand of a
1825 // member function call.
1826 //
1827 // There are other safeguards against such uses, but it's important
1828 // to get this right here so that we don't end up making a
1829 // spuriously dependent expression if we're inside a dependent
1830 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001831 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001832 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001833 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001834 MightBeImplicitMember = true;
1835 else if (!SS.isEmpty())
1836 MightBeImplicitMember = false;
1837 else if (R.isOverloadedResult())
1838 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001839 else if (R.isUnresolvableResult())
1840 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001841 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001842 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1843 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001844
1845 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001846 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1847 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001848 }
1849
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001850 if (TemplateArgs || TemplateKWLoc.isValid())
1851 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001852
John McCallf7a1a742009-11-24 19:00:30 +00001853 return BuildDeclarationNameExpr(SS, R, ADL);
1854}
1855
John McCall129e2df2009-11-30 22:42:35 +00001856/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1857/// declaration name, generally during template instantiation.
1858/// There's a large number of things which don't need to be done along
1859/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001860ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001861Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001862 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001863 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001864 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001865 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1866 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001867
John McCall77bb1aa2010-05-01 00:40:08 +00001868 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001869 return ExprError();
1870
Abramo Bagnara25777432010-08-11 22:01:17 +00001871 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001872 LookupQualifiedName(R, DC);
1873
1874 if (R.isAmbiguous())
1875 return ExprError();
1876
1877 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001878 Diag(NameInfo.getLoc(), diag::err_no_member)
1879 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001880 return ExprError();
1881 }
1882
1883 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1884}
1885
1886/// LookupInObjCMethod - The parser has read a name in, and Sema has
1887/// detected that we're currently inside an ObjC method. Perform some
1888/// additional lookup.
1889///
1890/// Ideally, most of this would be done by lookup, but there's
1891/// actually quite a lot of extra work involved.
1892///
1893/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001894ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001895Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001896 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001897 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001898 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001899
John McCallf7a1a742009-11-24 19:00:30 +00001900 // There are two cases to handle here. 1) scoped lookup could have failed,
1901 // in which case we should look for an ivar. 2) scoped lookup could have
1902 // found a decl, but that decl is outside the current instance method (i.e.
1903 // a global variable). In these two cases, we do a lookup for an ivar with
1904 // this name, if the lookup sucedes, we replace it our current decl.
1905
1906 // If we're in a class method, we don't normally want to look for
1907 // ivars. But if we don't find anything else, and there's an
1908 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001909 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001910
1911 bool LookForIvars;
1912 if (Lookup.empty())
1913 LookForIvars = true;
1914 else if (IsClassMethod)
1915 LookForIvars = false;
1916 else
1917 LookForIvars = (Lookup.isSingleResult() &&
1918 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001919 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001920 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001921 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001922 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001923 ObjCIvarDecl *IV = 0;
1924 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001925 // Diagnose using an ivar in a class method.
1926 if (IsClassMethod)
1927 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1928 << IV->getDeclName());
1929
1930 // If we're referencing an invalid decl, just return this as a silent
1931 // error node. The error diagnostic was already emitted on the decl.
1932 if (IV->isInvalidDecl())
1933 return ExprError();
1934
1935 // Check if referencing a field with __attribute__((deprecated)).
1936 if (DiagnoseUseOfDecl(IV, Loc))
1937 return ExprError();
1938
1939 // Diagnose the use of an ivar outside of the declaring class.
1940 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001941 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001942 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001943 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1944
1945 // FIXME: This should use a new expr for a direct reference, don't
1946 // turn this into Self->ivar, just return a BareIVarExpr or something.
1947 IdentifierInfo &II = Context.Idents.get("self");
1948 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001949 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001950 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001951 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001952 SourceLocation TemplateKWLoc;
1953 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001954 SelfName, false, false);
1955 if (SelfExpr.isInvalid())
1956 return ExprError();
1957
John Wiegley429bb272011-04-08 18:41:53 +00001958 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1959 if (SelfExpr.isInvalid())
1960 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001961
Eli Friedman5f2987c2012-02-02 03:46:19 +00001962 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001963
1964 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1965 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1966 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
John McCallf7a1a742009-11-24 19:00:30 +00001967 return Owned(new (Context)
1968 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001969 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001970 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001971 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001972 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001973 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1974 ObjCInterfaceDecl *ClassDeclared;
1975 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1976 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00001977 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001978 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1979 }
John McCallf7a1a742009-11-24 19:00:30 +00001980 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00001981 } else if (Lookup.isSingleResult() &&
1982 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1983 // If accessing a stand-alone ivar in a class method, this is an error.
1984 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1985 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1986 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00001987 }
1988
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001989 if (Lookup.empty() && II && AllowBuiltinCreation) {
1990 // FIXME. Consolidate this with similar code in LookupName.
1991 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001992 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001993 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1994 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1995 S, Lookup.isForRedeclaration(),
1996 Lookup.getNameLoc());
1997 if (D) Lookup.addDecl(D);
1998 }
1999 }
2000 }
John McCallf7a1a742009-11-24 19:00:30 +00002001 // Sentinel value saying that we didn't do anything special.
2002 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002003}
John McCallba135432009-11-21 08:51:07 +00002004
John McCall6bb80172010-03-30 21:47:33 +00002005/// \brief Cast a base object to a member's actual type.
2006///
2007/// Logically this happens in three phases:
2008///
2009/// * First we cast from the base type to the naming class.
2010/// The naming class is the class into which we were looking
2011/// when we found the member; it's the qualifier type if a
2012/// qualifier was provided, and otherwise it's the base type.
2013///
2014/// * Next we cast from the naming class to the declaring class.
2015/// If the member we found was brought into a class's scope by
2016/// a using declaration, this is that class; otherwise it's
2017/// the class declaring the member.
2018///
2019/// * Finally we cast from the declaring class to the "true"
2020/// declaring class of the member. This conversion does not
2021/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002022ExprResult
2023Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002024 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002025 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002026 NamedDecl *Member) {
2027 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2028 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002029 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002030
Douglas Gregor5fccd362010-03-03 23:55:11 +00002031 QualType DestRecordType;
2032 QualType DestType;
2033 QualType FromRecordType;
2034 QualType FromType = From->getType();
2035 bool PointerConversions = false;
2036 if (isa<FieldDecl>(Member)) {
2037 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002038
Douglas Gregor5fccd362010-03-03 23:55:11 +00002039 if (FromType->getAs<PointerType>()) {
2040 DestType = Context.getPointerType(DestRecordType);
2041 FromRecordType = FromType->getPointeeType();
2042 PointerConversions = true;
2043 } else {
2044 DestType = DestRecordType;
2045 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002046 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002047 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2048 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002049 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002050
Douglas Gregor5fccd362010-03-03 23:55:11 +00002051 DestType = Method->getThisType(Context);
2052 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002053
Douglas Gregor5fccd362010-03-03 23:55:11 +00002054 if (FromType->getAs<PointerType>()) {
2055 FromRecordType = FromType->getPointeeType();
2056 PointerConversions = true;
2057 } else {
2058 FromRecordType = FromType;
2059 DestType = DestRecordType;
2060 }
2061 } else {
2062 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002063 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002064 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002065
Douglas Gregor5fccd362010-03-03 23:55:11 +00002066 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002067 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002068
Douglas Gregor5fccd362010-03-03 23:55:11 +00002069 // If the unqualified types are the same, no conversion is necessary.
2070 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002071 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002072
John McCall6bb80172010-03-30 21:47:33 +00002073 SourceRange FromRange = From->getSourceRange();
2074 SourceLocation FromLoc = FromRange.getBegin();
2075
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002076 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002077
Douglas Gregor5fccd362010-03-03 23:55:11 +00002078 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002079 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002080 // class name.
2081 //
2082 // If the member was a qualified name and the qualified referred to a
2083 // specific base subobject type, we'll cast to that intermediate type
2084 // first and then to the object in which the member is declared. That allows
2085 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2086 //
2087 // class Base { public: int x; };
2088 // class Derived1 : public Base { };
2089 // class Derived2 : public Base { };
2090 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2091 //
2092 // void VeryDerived::f() {
2093 // x = 17; // error: ambiguous base subobjects
2094 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2095 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002096 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002097 QualType QType = QualType(Qualifier->getAsType(), 0);
2098 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2099 assert(QType->isRecordType() && "lookup done with non-record type");
2100
2101 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2102
2103 // In C++98, the qualifier type doesn't actually have to be a base
2104 // type of the object type, in which case we just ignore it.
2105 // Otherwise build the appropriate casts.
2106 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002107 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002108 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002109 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002110 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002111
Douglas Gregor5fccd362010-03-03 23:55:11 +00002112 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002113 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002114 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2115 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002116
2117 FromType = QType;
2118 FromRecordType = QRecordType;
2119
2120 // If the qualifier type was the same as the destination type,
2121 // we're done.
2122 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002123 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002124 }
2125 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002126
John McCall6bb80172010-03-30 21:47:33 +00002127 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002128
John McCall6bb80172010-03-30 21:47:33 +00002129 // If we actually found the member through a using declaration, cast
2130 // down to the using declaration's type.
2131 //
2132 // Pointer equality is fine here because only one declaration of a
2133 // class ever has member declarations.
2134 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2135 assert(isa<UsingShadowDecl>(FoundDecl));
2136 QualType URecordType = Context.getTypeDeclType(
2137 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2138
2139 // We only need to do this if the naming-class to declaring-class
2140 // conversion is non-trivial.
2141 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2142 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002143 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002144 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002145 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002146 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002147
John McCall6bb80172010-03-30 21:47:33 +00002148 QualType UType = URecordType;
2149 if (PointerConversions)
2150 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002151 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2152 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002153 FromType = UType;
2154 FromRecordType = URecordType;
2155 }
2156
2157 // We don't do access control for the conversion from the
2158 // declaring class to the true declaring class.
2159 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002160 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002161
John McCallf871d0c2010-08-07 06:22:56 +00002162 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002163 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2164 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002165 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002166 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002167
John Wiegley429bb272011-04-08 18:41:53 +00002168 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2169 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002170}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002171
John McCallf7a1a742009-11-24 19:00:30 +00002172bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002173 const LookupResult &R,
2174 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002175 // Only when used directly as the postfix-expression of a call.
2176 if (!HasTrailingLParen)
2177 return false;
2178
2179 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002180 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002181 return false;
2182
2183 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002184 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002185 return false;
2186
2187 // Turn off ADL when we find certain kinds of declarations during
2188 // normal lookup:
2189 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2190 NamedDecl *D = *I;
2191
2192 // C++0x [basic.lookup.argdep]p3:
2193 // -- a declaration of a class member
2194 // Since using decls preserve this property, we check this on the
2195 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002196 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002197 return false;
2198
2199 // C++0x [basic.lookup.argdep]p3:
2200 // -- a block-scope function declaration that is not a
2201 // using-declaration
2202 // NOTE: we also trigger this for function templates (in fact, we
2203 // don't check the decl type at all, since all other decl types
2204 // turn off ADL anyway).
2205 if (isa<UsingShadowDecl>(D))
2206 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2207 else if (D->getDeclContext()->isFunctionOrMethod())
2208 return false;
2209
2210 // C++0x [basic.lookup.argdep]p3:
2211 // -- a declaration that is neither a function or a function
2212 // template
2213 // And also for builtin functions.
2214 if (isa<FunctionDecl>(D)) {
2215 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2216
2217 // But also builtin functions.
2218 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2219 return false;
2220 } else if (!isa<FunctionTemplateDecl>(D))
2221 return false;
2222 }
2223
2224 return true;
2225}
2226
2227
John McCallba135432009-11-21 08:51:07 +00002228/// Diagnoses obvious problems with the use of the given declaration
2229/// as an expression. This is only actually called for lookups that
2230/// were not overloaded, and it doesn't promise that the declaration
2231/// will in fact be used.
2232static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002233 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002234 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2235 return true;
2236 }
2237
2238 if (isa<ObjCInterfaceDecl>(D)) {
2239 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2240 return true;
2241 }
2242
2243 if (isa<NamespaceDecl>(D)) {
2244 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2245 return true;
2246 }
2247
2248 return false;
2249}
2250
John McCall60d7b3a2010-08-24 06:29:42 +00002251ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002252Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002253 LookupResult &R,
2254 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002255 // If this is a single, fully-resolved result and we don't need ADL,
2256 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002257 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002258 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2259 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002260
2261 // We only need to check the declaration if there's exactly one
2262 // result, because in the overloaded case the results can only be
2263 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002264 if (R.isSingleResult() &&
2265 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002266 return ExprError();
2267
John McCallc373d482010-01-27 01:50:18 +00002268 // Otherwise, just build an unresolved lookup expression. Suppress
2269 // any lookup-related diagnostics; we'll hash these out later, when
2270 // we've picked a target.
2271 R.suppressDiagnostics();
2272
John McCallba135432009-11-21 08:51:07 +00002273 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002274 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002275 SS.getWithLocInContext(Context),
2276 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002277 NeedsADL, R.isOverloadedResult(),
2278 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002279
2280 return Owned(ULE);
2281}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002282
John McCallba135432009-11-21 08:51:07 +00002283/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002284ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002285Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002286 const DeclarationNameInfo &NameInfo,
2287 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002288 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002289 assert(!isa<FunctionTemplateDecl>(D) &&
2290 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002291
Abramo Bagnara25777432010-08-11 22:01:17 +00002292 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002293 if (CheckDeclInExpr(*this, Loc, D))
2294 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002295
Douglas Gregor9af2f522009-12-01 16:58:18 +00002296 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2297 // Specifically diagnose references to class templates that are missing
2298 // a template argument list.
2299 Diag(Loc, diag::err_template_decl_ref)
2300 << Template << SS.getRange();
2301 Diag(Template->getLocation(), diag::note_template_decl_here);
2302 return ExprError();
2303 }
2304
2305 // Make sure that we're referring to a value.
2306 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2307 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002308 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002309 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002310 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002311 return ExprError();
2312 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002313
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002314 // Check whether this declaration can be used. Note that we suppress
2315 // this check when we're going to perform argument-dependent lookup
2316 // on this function name, because this might not be the function
2317 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002318 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002319 return ExprError();
2320
Steve Naroffdd972f22008-09-05 22:11:13 +00002321 // Only create DeclRefExpr's for valid Decl's.
2322 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002323 return ExprError();
2324
John McCall5808ce42011-02-03 08:15:49 +00002325 // Handle members of anonymous structs and unions. If we got here,
2326 // and the reference is to a class member indirect field, then this
2327 // must be the subject of a pointer-to-member expression.
2328 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2329 if (!indirectField->isCXXClassMember())
2330 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2331 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002332
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002333 {
John McCall76a40212011-02-09 01:13:10 +00002334 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002335 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002336
2337 switch (D->getKind()) {
2338 // Ignore all the non-ValueDecl kinds.
2339#define ABSTRACT_DECL(kind)
2340#define VALUE(type, base)
2341#define DECL(type, base) \
2342 case Decl::type:
2343#include "clang/AST/DeclNodes.inc"
2344 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002345
2346 // These shouldn't make it here.
2347 case Decl::ObjCAtDefsField:
2348 case Decl::ObjCIvar:
2349 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002350
2351 // Enum constants are always r-values and never references.
2352 // Unresolved using declarations are dependent.
2353 case Decl::EnumConstant:
2354 case Decl::UnresolvedUsingValue:
2355 valueKind = VK_RValue;
2356 break;
2357
2358 // Fields and indirect fields that got here must be for
2359 // pointer-to-member expressions; we just call them l-values for
2360 // internal consistency, because this subexpression doesn't really
2361 // exist in the high-level semantics.
2362 case Decl::Field:
2363 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002364 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002365 "building reference to field in C?");
2366
2367 // These can't have reference type in well-formed programs, but
2368 // for internal consistency we do this anyway.
2369 type = type.getNonReferenceType();
2370 valueKind = VK_LValue;
2371 break;
2372
2373 // Non-type template parameters are either l-values or r-values
2374 // depending on the type.
2375 case Decl::NonTypeTemplateParm: {
2376 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2377 type = reftype->getPointeeType();
2378 valueKind = VK_LValue; // even if the parameter is an r-value reference
2379 break;
2380 }
2381
2382 // For non-references, we need to strip qualifiers just in case
2383 // the template parameter was declared as 'const int' or whatever.
2384 valueKind = VK_RValue;
2385 type = type.getUnqualifiedType();
2386 break;
2387 }
2388
2389 case Decl::Var:
2390 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002391 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002392 !type.hasQualifiers() &&
2393 type->isVoidType()) {
2394 valueKind = VK_RValue;
2395 break;
2396 }
2397 // fallthrough
2398
2399 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002400 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002401 // These are always l-values.
2402 valueKind = VK_LValue;
2403 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002404
Douglas Gregor68932842012-02-18 05:51:20 +00002405 // FIXME: Does the addition of const really only apply in
2406 // potentially-evaluated contexts? Since the variable isn't actually
2407 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002408 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002409 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2410 if (!CapturedType.isNull())
2411 type = CapturedType;
2412 }
2413
John McCall76a40212011-02-09 01:13:10 +00002414 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002415 }
2416
John McCall76a40212011-02-09 01:13:10 +00002417 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002418 const FunctionType *fty = type->castAs<FunctionType>();
2419
2420 // If we're referring to a function with an __unknown_anytype
2421 // result type, make the entire expression __unknown_anytype.
2422 if (fty->getResultType() == Context.UnknownAnyTy) {
2423 type = Context.UnknownAnyTy;
2424 valueKind = VK_RValue;
2425 break;
2426 }
2427
John McCall76a40212011-02-09 01:13:10 +00002428 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002429 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002430 valueKind = VK_LValue;
2431 break;
2432 }
2433
2434 // C99 DR 316 says that, if a function type comes from a
2435 // function definition (without a prototype), that type is only
2436 // used for checking compatibility. Therefore, when referencing
2437 // the function, we pretend that we don't have the full function
2438 // type.
John McCall755d8492011-04-12 00:42:48 +00002439 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2440 isa<FunctionProtoType>(fty))
2441 type = Context.getFunctionNoProtoType(fty->getResultType(),
2442 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002443
2444 // Functions are r-values in C.
2445 valueKind = VK_RValue;
2446 break;
2447 }
2448
2449 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002450 // If we're referring to a method with an __unknown_anytype
2451 // result type, make the entire expression __unknown_anytype.
2452 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002453 if (const FunctionProtoType *proto
2454 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002455 if (proto->getResultType() == Context.UnknownAnyTy) {
2456 type = Context.UnknownAnyTy;
2457 valueKind = VK_RValue;
2458 break;
2459 }
2460
John McCall76a40212011-02-09 01:13:10 +00002461 // C++ methods are l-values if static, r-values if non-static.
2462 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2463 valueKind = VK_LValue;
2464 break;
2465 }
2466 // fallthrough
2467
2468 case Decl::CXXConversion:
2469 case Decl::CXXDestructor:
2470 case Decl::CXXConstructor:
2471 valueKind = VK_RValue;
2472 break;
2473 }
2474
2475 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2476 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002477}
2478
John McCall755d8492011-04-12 00:42:48 +00002479ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002480 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002481
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002483 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002484 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2485 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002486 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002487 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002489
Chris Lattnerfa28b302008-01-12 08:14:25 +00002490 // Pre-defined identifiers are of type char[x], where x is the length of the
2491 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002492
Anders Carlsson3a082d82009-09-08 18:24:21 +00002493 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002494 if (!currentDecl && getCurBlock())
2495 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002496 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002497 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002498 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002499 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002500
Anders Carlsson773f3972009-09-11 01:22:35 +00002501 QualType ResTy;
2502 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2503 ResTy = Context.DependentTy;
2504 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002505 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002506
Anders Carlsson773f3972009-09-11 01:22:35 +00002507 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002508 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002509 ResTy = Context.WCharTy.withConst();
2510 else
2511 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002512 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2513 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002514 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002515}
2516
Richard Smith36f5cfe2012-03-09 08:00:36 +00002517ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002518 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002519 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002520 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002521 if (Invalid)
2522 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002523
Benjamin Kramerddeea562010-02-27 13:44:12 +00002524 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002525 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002526 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002527 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002528
Chris Lattnere8337df2009-12-30 21:19:39 +00002529 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002530 if (Literal.isWide())
2531 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002532 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002533 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002534 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002535 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002536 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002537 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002538 else
2539 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002540
Douglas Gregor5cee1192011-07-27 05:40:30 +00002541 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2542 if (Literal.isWide())
2543 Kind = CharacterLiteral::Wide;
2544 else if (Literal.isUTF16())
2545 Kind = CharacterLiteral::UTF16;
2546 else if (Literal.isUTF32())
2547 Kind = CharacterLiteral::UTF32;
2548
Richard Smithdd66be72012-03-08 01:34:56 +00002549 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2550 Tok.getLocation());
2551
2552 if (Literal.getUDSuffix().empty())
2553 return Owned(Lit);
2554
2555 // We're building a user-defined literal.
2556 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2557 SourceLocation UDSuffixLoc =
2558 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2559
Richard Smith36f5cfe2012-03-09 08:00:36 +00002560 // Make sure we're allowed user-defined literals here.
2561 if (!UDLScope)
2562 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2563
Richard Smithdd66be72012-03-08 01:34:56 +00002564 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2565 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002566 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2567 llvm::makeArrayRef(&Lit, 1),
2568 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002569}
2570
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002571ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2572 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2573 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2574 Context.IntTy, Loc));
2575}
2576
Richard Smithb453ad32012-03-08 08:45:32 +00002577static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2578 QualType Ty, SourceLocation Loc) {
2579 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2580
2581 using llvm::APFloat;
2582 APFloat Val(Format);
2583
2584 APFloat::opStatus result = Literal.GetFloatValue(Val);
2585
2586 // Overflow is always an error, but underflow is only an error if
2587 // we underflowed to zero (APFloat reports denormals as underflow).
2588 if ((result & APFloat::opOverflow) ||
2589 ((result & APFloat::opUnderflow) && Val.isZero())) {
2590 unsigned diagnostic;
2591 SmallString<20> buffer;
2592 if (result & APFloat::opOverflow) {
2593 diagnostic = diag::warn_float_overflow;
2594 APFloat::getLargest(Format).toString(buffer);
2595 } else {
2596 diagnostic = diag::warn_float_underflow;
2597 APFloat::getSmallest(Format).toString(buffer);
2598 }
2599
2600 S.Diag(Loc, diagnostic)
2601 << Ty
2602 << StringRef(buffer.data(), buffer.size());
2603 }
2604
2605 bool isExact = (result == APFloat::opOK);
2606 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2607}
2608
Richard Smith36f5cfe2012-03-09 08:00:36 +00002609ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002610 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002611 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002613 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002614 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 }
Ted Kremenek28396602009-01-13 23:19:12 +00002616
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002617 SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002618 // Add padding so that NumericLiteralParser can overread by one character.
2619 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002621
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002623 bool Invalid = false;
2624 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2625 if (Invalid)
2626 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002627
Mike Stump1eb44332009-09-09 15:08:12 +00002628 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 Tok.getLocation(), PP);
2630 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002631 return ExprError();
2632
Richard Smithb453ad32012-03-08 08:45:32 +00002633 if (Literal.hasUDSuffix()) {
2634 // We're building a user-defined literal.
2635 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2636 SourceLocation UDSuffixLoc =
2637 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2638
Richard Smith36f5cfe2012-03-09 08:00:36 +00002639 // Make sure we're allowed user-defined literals here.
2640 if (!UDLScope)
2641 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002642
Richard Smith36f5cfe2012-03-09 08:00:36 +00002643 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002644 if (Literal.isFloatingLiteral()) {
2645 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2646 // long double, the literal is treated as a call of the form
2647 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002648 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002649 } else {
2650 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2651 // unsigned long long, the literal is treated as a call of the form
2652 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002653 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002654 }
2655
Richard Smith36f5cfe2012-03-09 08:00:36 +00002656 DeclarationName OpName =
2657 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2658 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2659 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2660
2661 // Perform literal operator lookup to determine if we're building a raw
2662 // literal or a cooked one.
2663 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2664 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2665 /*AllowRawAndTemplate*/true)) {
2666 case LOLR_Error:
2667 return ExprError();
2668
2669 case LOLR_Cooked: {
2670 Expr *Lit;
2671 if (Literal.isFloatingLiteral()) {
2672 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2673 } else {
2674 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2675 if (Literal.GetIntegerValue(ResultVal))
2676 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2677 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2678 Tok.getLocation());
2679 }
2680 return BuildLiteralOperatorCall(R, OpNameInfo,
2681 llvm::makeArrayRef(&Lit, 1),
2682 Tok.getLocation());
2683 }
2684
2685 case LOLR_Raw: {
2686 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2687 // literal is treated as a call of the form
2688 // operator "" X ("n")
2689 SourceLocation TokLoc = Tok.getLocation();
2690 unsigned Length = Literal.getUDSuffixOffset();
2691 QualType StrTy = Context.getConstantArrayType(
2692 Context.CharTy, llvm::APInt(32, Length + 1),
2693 ArrayType::Normal, 0);
2694 Expr *Lit = StringLiteral::Create(
2695 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2696 /*Pascal*/false, StrTy, &TokLoc, 1);
2697 return BuildLiteralOperatorCall(R, OpNameInfo,
2698 llvm::makeArrayRef(&Lit, 1), TokLoc);
2699 }
2700
2701 case LOLR_Template:
2702 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2703 // template), L is treated as a call fo the form
2704 // operator "" X <'c1', 'c2', ... 'ck'>()
2705 // where n is the source character sequence c1 c2 ... ck.
2706 TemplateArgumentListInfo ExplicitArgs;
2707 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2708 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2709 llvm::APSInt Value(CharBits, CharIsUnsigned);
2710 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2711 Value = ThisTokBegin[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002712 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002713 TemplateArgumentLocInfo ArgInfo;
2714 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2715 }
2716 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2717 Tok.getLocation(), &ExplicitArgs);
2718 }
2719
2720 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002721 }
2722
Chris Lattner5d661452007-08-26 03:42:43 +00002723 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002724
Chris Lattner5d661452007-08-26 03:42:43 +00002725 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002726 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002727 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002728 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002729 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002730 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002731 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002732 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002733
Richard Smithb453ad32012-03-08 08:45:32 +00002734 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002735
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002736 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002737 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002738 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002739 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002740 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002741 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002742 }
2743 }
Chris Lattner5d661452007-08-26 03:42:43 +00002744 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002745 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002746 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002747 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002748
Neil Boothb9449512007-08-29 22:00:19 +00002749 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00002750 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smithebaf0e62011-10-18 20:49:44 +00002751 Diag(Tok.getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002752 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00002753 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002754
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002756 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2757 // The microsoft literal suffix extensions support 128-bit literals, which
2758 // may be wider than [u]intmax_t.
2759 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2760 MaxWidth = 128;
2761 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002762
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 if (Literal.GetIntegerValue(ResultVal)) {
2764 // If this value didn't fit into uintmax_t, warn and force to ull.
2765 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002766 Ty = Context.UnsignedLongLongTy;
2767 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002768 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 } else {
2770 // If this value fits into a ULL, try to figure out what else it fits into
2771 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2774 // be an unsigned int.
2775 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2776
2777 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002778 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002779 if (!Literal.isLong && !Literal.isLongLong) {
2780 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002781 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002782
Reid Spencer5f016e22007-07-11 17:01:13 +00002783 // Does it fit in a unsigned int?
2784 if (ResultVal.isIntN(IntSize)) {
2785 // Does it fit in a signed int?
2786 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002787 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002789 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002790 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002793
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002795 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002796 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002797
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 // Does it fit in a unsigned long?
2799 if (ResultVal.isIntN(LongSize)) {
2800 // Does it fit in a signed long?
2801 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002802 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002804 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002805 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002807 }
2808
Stephen Canonb9e05f12012-05-03 22:49:43 +00002809 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002810 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002811 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002812
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 // Does it fit in a unsigned long long?
2814 if (ResultVal.isIntN(LongLongSize)) {
2815 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002816 // To be compatible with MSVC, hex integer literals ending with the
2817 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002818 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002819 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002820 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002822 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002823 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002824 }
2825 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002826
2827 // If it doesn't fit in unsigned long long, and we're using Microsoft
2828 // extensions, then its a 128-bit integer literal.
2829 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2830 if (Literal.isUnsigned)
2831 Ty = Context.UnsignedInt128Ty;
2832 else
2833 Ty = Context.Int128Ty;
2834 Width = 128;
2835 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002836
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 // If we still couldn't decide a type, we probably have something that
2838 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002839 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002840 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002841 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002842 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002844
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002845 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002846 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002848 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002849 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002850
Chris Lattner5d661452007-08-26 03:42:43 +00002851 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2852 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002853 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002854 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002855
2856 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002857}
2858
Richard Trieuccd891a2011-09-09 01:45:06 +00002859ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002860 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002861 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002862}
2863
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002864static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2865 SourceLocation Loc,
2866 SourceRange ArgRange) {
2867 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2868 // scalar or vector data type argument..."
2869 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2870 // type (C99 6.2.5p18) or void.
2871 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2872 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2873 << T << ArgRange;
2874 return true;
2875 }
2876
2877 assert((T->isVoidType() || !T->isIncompleteType()) &&
2878 "Scalar types should always be complete");
2879 return false;
2880}
2881
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002882static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2883 SourceLocation Loc,
2884 SourceRange ArgRange,
2885 UnaryExprOrTypeTrait TraitKind) {
2886 // C99 6.5.3.4p1:
2887 if (T->isFunctionType()) {
2888 // alignof(function) is allowed as an extension.
2889 if (TraitKind == UETT_SizeOf)
2890 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2891 return false;
2892 }
2893
2894 // Allow sizeof(void)/alignof(void) as an extension.
2895 if (T->isVoidType()) {
2896 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2897 return false;
2898 }
2899
2900 return true;
2901}
2902
2903static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2904 SourceLocation Loc,
2905 SourceRange ArgRange,
2906 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002907 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2908 // runtime doesn't allow it.
2909 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002910 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2911 << T << (TraitKind == UETT_SizeOf)
2912 << ArgRange;
2913 return true;
2914 }
2915
2916 return false;
2917}
2918
Chandler Carruth9d342d02011-05-26 08:53:10 +00002919/// \brief Check the constrains on expression operands to unary type expression
2920/// and type traits.
2921///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002922/// Completes any types necessary and validates the constraints on the operand
2923/// expression. The logic mostly mirrors the type-based overload, but may modify
2924/// the expression as it completes the type for that expression through template
2925/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002926bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002927 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002928 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002929
2930 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2931 // the result is the size of the referenced type."
2932 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2933 // result shall be the alignment of the referenced type."
2934 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2935 ExprTy = Ref->getPointeeType();
2936
2937 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002938 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2939 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002940
2941 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002942 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2943 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002944 return false;
2945
Richard Trieuccd891a2011-09-09 01:45:06 +00002946 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00002947 diag::err_sizeof_alignof_incomplete_type,
2948 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002949 return true;
2950
2951 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002952 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002953 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2954 ExprTy = Ref->getPointeeType();
2955
Richard Trieuccd891a2011-09-09 01:45:06 +00002956 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2957 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002958 return true;
2959
Nico Webercf739922011-06-15 02:47:03 +00002960 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002961 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002962 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2963 QualType OType = PVD->getOriginalType();
2964 QualType Type = PVD->getType();
2965 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002966 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002967 << Type << OType;
2968 Diag(PVD->getLocation(), diag::note_declared_at);
2969 }
2970 }
2971 }
2972 }
2973
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002974 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002975}
2976
2977/// \brief Check the constraints on operands to unary expression and type
2978/// traits.
2979///
2980/// This will complete any types necessary, and validate the various constraints
2981/// on those operands.
2982///
Reid Spencer5f016e22007-07-11 17:01:13 +00002983/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002984/// C99 6.3.2.1p[2-4] all state:
2985/// Except when it is the operand of the sizeof operator ...
2986///
2987/// C++ [expr.sizeof]p4
2988/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2989/// standard conversions are not applied to the operand of sizeof.
2990///
2991/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002992bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002993 SourceLocation OpLoc,
2994 SourceRange ExprRange,
2995 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002996 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002997 return false;
2998
Sebastian Redl5d484e82009-11-23 17:18:46 +00002999 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3000 // the result is the size of the referenced type."
3001 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3002 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003003 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3004 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003005
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003006 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003007 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003008
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003009 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003010 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003011 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003012 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Richard Trieuccd891a2011-09-09 01:45:06 +00003014 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003015 diag::err_sizeof_alignof_incomplete_type,
3016 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003017 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Richard Trieuccd891a2011-09-09 01:45:06 +00003019 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003020 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003021 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Chris Lattner1efaa952009-04-24 00:30:45 +00003023 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003024}
3025
Chandler Carruth9d342d02011-05-26 08:53:10 +00003026static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003027 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003028
Mike Stump1eb44332009-09-09 15:08:12 +00003029 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003030 if (isa<DeclRefExpr>(E))
3031 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003032
3033 // Cannot know anything else if the expression is dependent.
3034 if (E->isTypeDependent())
3035 return false;
3036
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003037 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003038 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3039 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003040 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003041 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003042
3043 // Alignment of a field access is always okay, so long as it isn't a
3044 // bit-field.
3045 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003046 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003047 return false;
3048
Chandler Carruth9d342d02011-05-26 08:53:10 +00003049 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003050}
3051
Chandler Carruth9d342d02011-05-26 08:53:10 +00003052bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003053 E = E->IgnoreParens();
3054
3055 // Cannot know anything else if the expression is dependent.
3056 if (E->isTypeDependent())
3057 return false;
3058
Chandler Carruth9d342d02011-05-26 08:53:10 +00003059 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003060}
3061
Douglas Gregorba498172009-03-13 21:01:28 +00003062/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003063ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003064Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3065 SourceLocation OpLoc,
3066 UnaryExprOrTypeTrait ExprKind,
3067 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003068 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003069 return ExprError();
3070
John McCalla93c9342009-12-07 02:54:59 +00003071 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003072
Douglas Gregorba498172009-03-13 21:01:28 +00003073 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003074 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003075 return ExprError();
3076
3077 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003078 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3079 Context.getSizeType(),
3080 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003081}
3082
3083/// \brief Build a sizeof or alignof expression given an expression
3084/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003085ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003086Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3087 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003088 ExprResult PE = CheckPlaceholderExpr(E);
3089 if (PE.isInvalid())
3090 return ExprError();
3091
3092 E = PE.get();
3093
Douglas Gregorba498172009-03-13 21:01:28 +00003094 // Verify that the operand is valid.
3095 bool isInvalid = false;
3096 if (E->isTypeDependent()) {
3097 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003098 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003099 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003100 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003101 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003102 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003103 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003104 isInvalid = true;
3105 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003106 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003107 }
3108
3109 if (isInvalid)
3110 return ExprError();
3111
Eli Friedman71b8fb52012-01-21 01:01:51 +00003112 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3113 PE = TranformToPotentiallyEvaluated(E);
3114 if (PE.isInvalid()) return ExprError();
3115 E = PE.take();
3116 }
3117
Douglas Gregorba498172009-03-13 21:01:28 +00003118 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003119 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003120 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003121 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003122}
3123
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003124/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3125/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003126/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003127ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003128Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003129 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003130 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003131 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003132 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003133
Richard Trieuccd891a2011-09-09 01:45:06 +00003134 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003135 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003136 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003137 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003138 }
Sebastian Redl05189992008-11-11 17:56:53 +00003139
Douglas Gregorba498172009-03-13 21:01:28 +00003140 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003141 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003142 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003143}
3144
John Wiegley429bb272011-04-08 18:41:53 +00003145static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003146 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003147 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003148 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003149
John McCallf6a16482010-12-04 03:47:34 +00003150 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003151 if (V.get()->getObjectKind() != OK_Ordinary) {
3152 V = S.DefaultLvalueConversion(V.take());
3153 if (V.isInvalid())
3154 return QualType();
3155 }
John McCallf6a16482010-12-04 03:47:34 +00003156
Chris Lattnercc26ed72007-08-26 05:39:26 +00003157 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003158 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003159 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Chris Lattnercc26ed72007-08-26 05:39:26 +00003161 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003162 if (V.get()->getType()->isArithmeticType())
3163 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003164
John McCall2cd11fe2010-10-12 02:09:17 +00003165 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003166 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003167 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003168 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003169 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003170 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003171 }
3172
Chris Lattnercc26ed72007-08-26 05:39:26 +00003173 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003174 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003175 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003176 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003177}
3178
3179
Reid Spencer5f016e22007-07-11 17:01:13 +00003180
John McCall60d7b3a2010-08-24 06:29:42 +00003181ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003182Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003183 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003184 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003185 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003186 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003187 case tok::plusplus: Opc = UO_PostInc; break;
3188 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003190
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003191 // Since this might is a postfix expression, get rid of ParenListExprs.
3192 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3193 if (Result.isInvalid()) return ExprError();
3194 Input = Result.take();
3195
John McCall9ae2f072010-08-23 23:25:46 +00003196 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003197}
3198
John McCall1503f0d2012-07-31 05:14:30 +00003199/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3200///
3201/// \return true on error
3202static bool checkArithmeticOnObjCPointer(Sema &S,
3203 SourceLocation opLoc,
3204 Expr *op) {
3205 assert(op->getType()->isObjCObjectPointerType());
3206 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3207 return false;
3208
3209 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3210 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3211 << op->getSourceRange();
3212 return true;
3213}
3214
John McCall60d7b3a2010-08-24 06:29:42 +00003215ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003216Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3217 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003218 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003219 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003220 if (Result.isInvalid()) return ExprError();
3221 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003222
John McCall9ae2f072010-08-23 23:25:46 +00003223 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003224
David Blaikie4e4d0842012-03-11 07:00:24 +00003225 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003226 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003227 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003228 Context.DependentTy,
3229 VK_LValue, OK_Ordinary,
3230 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003231 }
3232
David Blaikie4e4d0842012-03-11 07:00:24 +00003233 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003234 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003235 LHSExp->getType()->isEnumeralType() ||
3236 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003237 RHSExp->getType()->isEnumeralType()) &&
3238 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003239 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003240 }
3241
John McCall9ae2f072010-08-23 23:25:46 +00003242 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003243}
3244
John McCall60d7b3a2010-08-24 06:29:42 +00003245ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003246Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003247 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003248 Expr *LHSExp = Base;
3249 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003250
Chris Lattner12d9ff62007-07-16 00:14:47 +00003251 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003252 if (!LHSExp->getType()->getAs<VectorType>()) {
3253 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3254 if (Result.isInvalid())
3255 return ExprError();
3256 LHSExp = Result.take();
3257 }
3258 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3259 if (Result.isInvalid())
3260 return ExprError();
3261 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003262
Chris Lattner12d9ff62007-07-16 00:14:47 +00003263 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003264 ExprValueKind VK = VK_LValue;
3265 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003266
Reid Spencer5f016e22007-07-11 17:01:13 +00003267 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003268 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003269 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003270 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003271 Expr *BaseExpr, *IndexExpr;
3272 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003273 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3274 BaseExpr = LHSExp;
3275 IndexExpr = RHSExp;
3276 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003277 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003278 BaseExpr = LHSExp;
3279 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003280 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003281 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003282 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003283 BaseExpr = LHSExp;
3284 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003285
3286 // Use custom logic if this should be the pseudo-object subscript
3287 // expression.
3288 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3289 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3290
Steve Naroff14108da2009-07-10 23:34:53 +00003291 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003292 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3293 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3294 << ResultType << BaseExpr->getSourceRange();
3295 return ExprError();
3296 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003297 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3298 // Handle the uncommon case of "123[Ptr]".
3299 BaseExpr = RHSExp;
3300 IndexExpr = LHSExp;
3301 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003302 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003303 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003304 // Handle the uncommon case of "123[Ptr]".
3305 BaseExpr = RHSExp;
3306 IndexExpr = LHSExp;
3307 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003308 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3309 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3310 << ResultType << BaseExpr->getSourceRange();
3311 return ExprError();
3312 }
John McCall183700f2009-09-21 23:43:11 +00003313 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003314 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003315 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003316 VK = LHSExp->getValueKind();
3317 if (VK != VK_RValue)
3318 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003319
Chris Lattner12d9ff62007-07-16 00:14:47 +00003320 // FIXME: need to deal with const...
3321 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003322 } else if (LHSTy->isArrayType()) {
3323 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003324 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003325 // wasn't promoted because of the C90 rule that doesn't
3326 // allow promoting non-lvalue arrays. Warn, then
3327 // force the promotion here.
3328 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3329 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003330 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3331 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003332 LHSTy = LHSExp->getType();
3333
3334 BaseExpr = LHSExp;
3335 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003336 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003337 } else if (RHSTy->isArrayType()) {
3338 // Same as previous, except for 123[f().a] case
3339 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3340 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003341 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3342 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003343 RHSTy = RHSExp->getType();
3344
3345 BaseExpr = RHSExp;
3346 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003347 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003348 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003349 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3350 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003351 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003352 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003353 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003354 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3355 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003356
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003357 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003358 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3359 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003360 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3361
Douglas Gregore7450f52009-03-24 19:52:54 +00003362 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003363 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3364 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003365 // incomplete types are not object types.
3366 if (ResultType->isFunctionType()) {
3367 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3368 << ResultType << BaseExpr->getSourceRange();
3369 return ExprError();
3370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
David Blaikie4e4d0842012-03-11 07:00:24 +00003372 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003373 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003374 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3375 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003376
3377 // C forbids expressions of unqualified void type from being l-values.
3378 // See IsCForbiddenLValueType.
3379 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003380 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003381 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003382 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003383 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003384
John McCall09431682010-11-18 19:01:18 +00003385 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003386 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003387
Mike Stumpeed9cac2009-02-19 03:04:26 +00003388 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003389 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003390}
3391
John McCall60d7b3a2010-08-24 06:29:42 +00003392ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003393 FunctionDecl *FD,
3394 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003395 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003396 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003397 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003398 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003399 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003400 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003401 return ExprError();
3402 }
3403
3404 if (Param->hasUninstantiatedDefaultArg()) {
3405 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003406
Richard Smithadb1d4c2012-07-22 23:45:10 +00003407 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3408 Param);
3409
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003410 // Instantiate the expression.
3411 MultiLevelTemplateArgumentList ArgList
3412 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003413
Nico Weber08e41a62010-11-29 18:19:25 +00003414 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003415 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003416 InstantiatingTemplate Inst(*this, CallLoc, Param,
3417 ArrayRef<TemplateArgument>(Innermost.first,
3418 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003419 if (Inst)
3420 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003421
Nico Weber08e41a62010-11-29 18:19:25 +00003422 ExprResult Result;
3423 {
3424 // C++ [dcl.fct.default]p5:
3425 // The names in the [default argument] expression are bound, and
3426 // the semantic constraints are checked, at the point where the
3427 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003428 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003429 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003430 Result = SubstExpr(UninstExpr, ArgList);
3431 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003432 if (Result.isInvalid())
3433 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003435 // Check the expression as an initializer for the parameter.
3436 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003437 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003438 InitializationKind Kind
3439 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003440 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003441 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003442
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003443 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3444 Result = InitSeq.Perform(*this, Entity, Kind,
3445 MultiExprArg(*this, &ResultE, 1));
3446 if (Result.isInvalid())
3447 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003448
David Blaikiec1c07252012-04-30 18:21:31 +00003449 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003450 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003451 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003452 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003453 }
3454
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003455 // If the default expression creates temporaries, we need to
3456 // push them to the current stack of expression temporaries so they'll
3457 // be properly destroyed.
3458 // FIXME: We should really be rebuilding the default argument with new
3459 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003460 // We don't need to do that with block decls, though, because
3461 // blocks in default argument expression can never capture anything.
3462 if (isa<ExprWithCleanups>(Param->getInit())) {
3463 // Set the "needs cleanups" bit regardless of whether there are
3464 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003465 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003466
3467 // Append all the objects to the cleanup list. Right now, this
3468 // should always be a no-op, because blocks in default argument
3469 // expressions should never be able to capture anything.
3470 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3471 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003472 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003473
3474 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003475 // Just mark all of the declarations in this potentially-evaluated expression
3476 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003477 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3478 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003479 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003480}
3481
Richard Smith831421f2012-06-25 20:30:08 +00003482
3483Sema::VariadicCallType
3484Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3485 Expr *Fn) {
3486 if (Proto && Proto->isVariadic()) {
3487 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3488 return VariadicConstructor;
3489 else if (Fn && Fn->getType()->isBlockPointerType())
3490 return VariadicBlock;
3491 else if (FDecl) {
3492 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3493 if (Method->isInstance())
3494 return VariadicMethod;
3495 }
3496 return VariadicFunction;
3497 }
3498 return VariadicDoesNotApply;
3499}
3500
Douglas Gregor88a35142008-12-22 05:46:06 +00003501/// ConvertArgumentsForCall - Converts the arguments specified in
3502/// Args/NumArgs to the parameter types of the function FDecl with
3503/// function prototype Proto. Call is the call expression itself, and
3504/// Fn is the function expression. For a C++ member function, this
3505/// routine does not attempt to convert the object argument. Returns
3506/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003507bool
3508Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003509 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003510 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003511 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003512 SourceLocation RParenLoc,
3513 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003514 // Bail out early if calling a builtin with custom typechecking.
3515 // We don't need to do this in the
3516 if (FDecl)
3517 if (unsigned ID = FDecl->getBuiltinID())
3518 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3519 return false;
3520
Mike Stumpeed9cac2009-02-19 03:04:26 +00003521 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003522 // assignment, to the types of the corresponding parameter, ...
3523 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003524 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003525 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003526 unsigned FnKind = Fn->getType()->isBlockPointerType()
3527 ? 1 /* block */
3528 : (IsExecConfig ? 3 /* kernel function (exec config) */
3529 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003530
Douglas Gregor88a35142008-12-22 05:46:06 +00003531 // If too few arguments are available (and we don't have default
3532 // arguments for the remaining parameters), don't make the call.
3533 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003534 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003535 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3536 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3537 ? diag::err_typecheck_call_too_few_args_one
3538 : diag::err_typecheck_call_too_few_args_at_least_one)
3539 << FnKind
3540 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3541 else
3542 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3543 ? diag::err_typecheck_call_too_few_args
3544 : diag::err_typecheck_call_too_few_args_at_least)
3545 << FnKind
3546 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003547
3548 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003549 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003550 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3551 << FDecl;
3552
3553 return true;
3554 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003555 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003556 }
3557
3558 // If too many are passed and not variadic, error on the extras and drop
3559 // them.
3560 if (NumArgs > NumArgsInProto) {
3561 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003562 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3563 Diag(Args[NumArgsInProto]->getLocStart(),
3564 MinArgs == NumArgsInProto
3565 ? diag::err_typecheck_call_too_many_args_one
3566 : diag::err_typecheck_call_too_many_args_at_most_one)
3567 << FnKind
3568 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3569 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3570 Args[NumArgs-1]->getLocEnd());
3571 else
3572 Diag(Args[NumArgsInProto]->getLocStart(),
3573 MinArgs == NumArgsInProto
3574 ? diag::err_typecheck_call_too_many_args
3575 : diag::err_typecheck_call_too_many_args_at_most)
3576 << FnKind
3577 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3578 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3579 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003580
3581 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003582 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003583 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3584 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003585
Douglas Gregor88a35142008-12-22 05:46:06 +00003586 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003587 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003588 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003589 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003590 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003591 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003592 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3593
Daniel Dunbar96a00142012-03-09 18:35:03 +00003594 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003595 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003596 if (Invalid)
3597 return true;
3598 unsigned TotalNumArgs = AllArgs.size();
3599 for (unsigned i = 0; i < TotalNumArgs; ++i)
3600 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003601
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003602 return false;
3603}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003604
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003605bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3606 FunctionDecl *FDecl,
3607 const FunctionProtoType *Proto,
3608 unsigned FirstProtoArg,
3609 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003610 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003611 VariadicCallType CallType,
3612 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003613 unsigned NumArgsInProto = Proto->getNumArgs();
3614 unsigned NumArgsToCheck = NumArgs;
3615 bool Invalid = false;
3616 if (NumArgs != NumArgsInProto)
3617 // Use default arguments for missing arguments
3618 NumArgsToCheck = NumArgsInProto;
3619 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003620 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003621 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003622 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003623
Douglas Gregor88a35142008-12-22 05:46:06 +00003624 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003625 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003626 if (ArgIx < NumArgs) {
3627 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003628
Daniel Dunbar96a00142012-03-09 18:35:03 +00003629 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003630 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003631 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003632 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003633
Douglas Gregora188ff22009-12-22 16:09:06 +00003634 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003635 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003636 if (FDecl && i < FDecl->getNumParams())
3637 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003638
John McCall5acb0c92011-10-17 18:40:02 +00003639 // Strip the unbridged-cast placeholder expression off, if applicable.
3640 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3641 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3642 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3643 Arg = stripARCUnbridgedCast(Arg);
3644
Douglas Gregora188ff22009-12-22 16:09:06 +00003645 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003646 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003647 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3648 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003649 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003650 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003651 Owned(Arg),
3652 /*TopLevelOfInitList=*/false,
3653 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003654 if (ArgE.isInvalid())
3655 return true;
3656
3657 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003658 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003659 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003660
John McCall60d7b3a2010-08-24 06:29:42 +00003661 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003662 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003663 if (ArgExpr.isInvalid())
3664 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003665
Anders Carlsson56c5e332009-08-25 03:49:14 +00003666 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003667 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003668
3669 // Check for array bounds violations for each argument to the call. This
3670 // check only triggers warnings when the argument isn't a more complex Expr
3671 // with its own checking, such as a BinaryOperator.
3672 CheckArrayAccess(Arg);
3673
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003674 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3675 CheckStaticArrayArgument(CallLoc, Param, Arg);
3676
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003677 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003678 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003679
Douglas Gregor88a35142008-12-22 05:46:06 +00003680 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003681 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003682 // Assume that extern "C" functions with variadic arguments that
3683 // return __unknown_anytype aren't *really* variadic.
3684 if (Proto->getResultType() == Context.UnknownAnyTy &&
3685 FDecl && FDecl->isExternC()) {
3686 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3687 ExprResult arg;
3688 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3689 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3690 else
3691 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3692 Invalid |= arg.isInvalid();
3693 AllArgs.push_back(arg.take());
3694 }
3695
3696 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3697 } else {
3698 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003699 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3700 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003701 Invalid |= Arg.isInvalid();
3702 AllArgs.push_back(Arg.take());
3703 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003704 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003705
3706 // Check for array bounds violations.
3707 for (unsigned i = ArgIx; i != NumArgs; ++i)
3708 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003709 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003710 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003711}
3712
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003713static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3714 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3715 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3716 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3717 << ATL->getLocalSourceRange();
3718}
3719
3720/// CheckStaticArrayArgument - If the given argument corresponds to a static
3721/// array parameter, check that it is non-null, and that if it is formed by
3722/// array-to-pointer decay, the underlying array is sufficiently large.
3723///
3724/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3725/// array type derivation, then for each call to the function, the value of the
3726/// corresponding actual argument shall provide access to the first element of
3727/// an array with at least as many elements as specified by the size expression.
3728void
3729Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3730 ParmVarDecl *Param,
3731 const Expr *ArgExpr) {
3732 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003733 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003734 return;
3735
3736 QualType OrigTy = Param->getOriginalType();
3737
3738 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3739 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3740 return;
3741
3742 if (ArgExpr->isNullPointerConstant(Context,
3743 Expr::NPC_NeverValueDependent)) {
3744 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3745 DiagnoseCalleeStaticArrayParam(*this, Param);
3746 return;
3747 }
3748
3749 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3750 if (!CAT)
3751 return;
3752
3753 const ConstantArrayType *ArgCAT =
3754 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3755 if (!ArgCAT)
3756 return;
3757
3758 if (ArgCAT->getSize().ult(CAT->getSize())) {
3759 Diag(CallLoc, diag::warn_static_array_too_small)
3760 << ArgExpr->getSourceRange()
3761 << (unsigned) ArgCAT->getSize().getZExtValue()
3762 << (unsigned) CAT->getSize().getZExtValue();
3763 DiagnoseCalleeStaticArrayParam(*this, Param);
3764 }
3765}
3766
John McCall755d8492011-04-12 00:42:48 +00003767/// Given a function expression of unknown-any type, try to rebuild it
3768/// to have a function type.
3769static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3770
Steve Narofff69936d2007-09-16 03:34:24 +00003771/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003772/// This provides the location of the left/right parens and a list of comma
3773/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003774ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003775Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003776 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003777 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003778 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003779
3780 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003781 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003782 if (Result.isInvalid()) return ExprError();
3783 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003784
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003785 Expr **Args = ArgExprs.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003786
David Blaikie4e4d0842012-03-11 07:00:24 +00003787 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003788 // If this is a pseudo-destructor expression, build the call immediately.
3789 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3790 if (NumArgs > 0) {
3791 // Pseudo-destructor calls should not have any arguments.
3792 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003793 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003794 SourceRange(Args[0]->getLocStart(),
3795 Args[NumArgs-1]->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003796 }
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Douglas Gregora71d8192009-09-04 17:36:40 +00003798 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003799 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003800 }
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Douglas Gregor17330012009-02-04 15:01:18 +00003802 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003803 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003804 // FIXME: Will need to cache the results of name lookup (including ADL) in
3805 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003806 bool Dependent = false;
3807 if (Fn->isTypeDependent())
3808 Dependent = true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003809 else if (Expr::hasAnyTypeDependentArguments(
3810 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregor17330012009-02-04 15:01:18 +00003811 Dependent = true;
3812
Peter Collingbournee08ce652011-02-09 21:07:24 +00003813 if (Dependent) {
3814 if (ExecConfig) {
3815 return Owned(new (Context) CUDAKernelCallExpr(
3816 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3817 Context.DependentTy, VK_RValue, RParenLoc));
3818 } else {
3819 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3820 Context.DependentTy, VK_RValue,
3821 RParenLoc));
3822 }
3823 }
Douglas Gregor17330012009-02-04 15:01:18 +00003824
3825 // Determine whether this is a call to an object (C++ [over.call.object]).
3826 if (Fn->getType()->isRecordType())
3827 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003828 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003829
John McCall755d8492011-04-12 00:42:48 +00003830 if (Fn->getType() == Context.UnknownAnyTy) {
3831 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3832 if (result.isInvalid()) return ExprError();
3833 Fn = result.take();
3834 }
3835
John McCall864c0412011-04-26 20:42:42 +00003836 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003837 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003838 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003839 }
John McCall864c0412011-04-26 20:42:42 +00003840 }
John McCall129e2df2009-11-30 22:42:35 +00003841
John McCall864c0412011-04-26 20:42:42 +00003842 // Check for overloaded calls. This can happen even in C due to extensions.
3843 if (Fn->getType() == Context.OverloadTy) {
3844 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3845
Douglas Gregoree697e62011-10-13 18:10:35 +00003846 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003847 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003848 OverloadExpr *ovl = find.Expression;
3849 if (isa<UnresolvedLookupExpr>(ovl)) {
3850 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3851 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3852 RParenLoc, ExecConfig);
3853 } else {
John McCallaa81e162009-12-01 22:10:20 +00003854 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003855 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003856 }
3857 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003858 }
3859
Douglas Gregorfa047642009-02-04 00:32:51 +00003860 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003861 if (Fn->getType() == Context.UnknownAnyTy) {
3862 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3863 if (result.isInvalid()) return ExprError();
3864 Fn = result.take();
3865 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003866
Eli Friedmanefa42f72009-12-26 03:35:45 +00003867 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003868
John McCall3b4294e2009-12-16 12:17:52 +00003869 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003870 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3871 if (UnOp->getOpcode() == UO_AddrOf)
3872 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3873
John McCall3b4294e2009-12-16 12:17:52 +00003874 if (isa<DeclRefExpr>(NakedFn))
3875 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003876 else if (isa<MemberExpr>(NakedFn))
3877 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003878
Peter Collingbournee08ce652011-02-09 21:07:24 +00003879 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003880 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003881}
3882
3883ExprResult
3884Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003885 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003886 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3887 if (!ConfigDecl)
3888 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3889 << "cudaConfigureCall");
3890 QualType ConfigQTy = ConfigDecl->getType();
3891
3892 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003893 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003894 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003895
Peter Collingbourne1f240762011-10-02 23:49:29 +00003896 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3897 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003898}
3899
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003900/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3901///
3902/// __builtin_astype( value, dst type )
3903///
Richard Trieuccd891a2011-09-09 01:45:06 +00003904ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003905 SourceLocation BuiltinLoc,
3906 SourceLocation RParenLoc) {
3907 ExprValueKind VK = VK_RValue;
3908 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003909 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3910 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003911 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3912 return ExprError(Diag(BuiltinLoc,
3913 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003914 << DstTy
3915 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003916 << E->getSourceRange());
3917 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003918 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003919}
3920
John McCall3b4294e2009-12-16 12:17:52 +00003921/// BuildResolvedCallExpr - Build a call to a resolved expression,
3922/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003923/// unary-convert to an expression of function-pointer or
3924/// block-pointer type.
3925///
3926/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003927ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003928Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3929 SourceLocation LParenLoc,
3930 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003931 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003932 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003933 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3934
Chris Lattner04421082008-04-08 04:40:51 +00003935 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003936 ExprResult Result = UsualUnaryConversions(Fn);
3937 if (Result.isInvalid())
3938 return ExprError();
3939 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003940
Chris Lattner925e60d2007-12-28 05:29:59 +00003941 // Make the call expr early, before semantic checks. This guarantees cleanup
3942 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003943 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00003944 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00003945 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3946 cast<CallExpr>(Config),
3947 Args, NumArgs,
3948 Context.BoolTy,
3949 VK_RValue,
3950 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00003951 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00003952 TheCall = new (Context) CallExpr(Context, Fn,
3953 Args, NumArgs,
3954 Context.BoolTy,
3955 VK_RValue,
3956 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003957
John McCall8e10f3b2011-02-26 05:39:39 +00003958 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3959
3960 // Bail out early if calling a builtin with custom typechecking.
3961 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3962 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3963
John McCall1de4d4e2011-04-07 08:22:57 +00003964 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003965 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003966 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003967 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3968 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003969 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003970 if (FuncT == 0)
3971 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3972 << Fn->getType() << Fn->getSourceRange());
3973 } else if (const BlockPointerType *BPT =
3974 Fn->getType()->getAs<BlockPointerType>()) {
3975 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3976 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003977 // Handle calls to expressions of unknown-any type.
3978 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003979 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003980 if (rewrite.isInvalid()) return ExprError();
3981 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003982 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003983 goto retry;
3984 }
3985
Sebastian Redl0eb23302009-01-19 00:08:26 +00003986 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3987 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003988 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003989
David Blaikie4e4d0842012-03-11 07:00:24 +00003990 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003991 if (Config) {
3992 // CUDA: Kernel calls must be to global functions
3993 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3994 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3995 << FDecl->getName() << Fn->getSourceRange());
3996
3997 // CUDA: Kernel function must have 'void' return type
3998 if (!FuncT->getResultType()->isVoidType())
3999 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4000 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004001 } else {
4002 // CUDA: Calls to global functions must be configured
4003 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4004 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4005 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004006 }
4007 }
4008
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004009 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004010 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004011 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004012 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004013 return ExprError();
4014
Chris Lattner925e60d2007-12-28 05:29:59 +00004015 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004016 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004017 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004018
Richard Smith831421f2012-06-25 20:30:08 +00004019 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4020 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004021 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004022 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004023 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004024 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004025 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004026
Douglas Gregor74734d52009-04-02 15:37:10 +00004027 if (FDecl) {
4028 // Check if we have too few/too many template arguments, based
4029 // on our knowledge of the function definition.
4030 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004031 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004032 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004033 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004034 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4035 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004036 }
Douglas Gregor46542412010-10-25 20:39:23 +00004037
4038 // If the function we're calling isn't a function prototype, but we have
4039 // a function prototype from a prior declaratiom, use that prototype.
4040 if (!FDecl->hasPrototype())
4041 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004042 }
4043
Steve Naroffb291ab62007-08-28 23:30:39 +00004044 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004045 for (unsigned i = 0; i != NumArgs; i++) {
4046 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004047
4048 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004049 InitializedEntity Entity
4050 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004051 Proto->getArgType(i),
4052 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004053 ExprResult ArgE = PerformCopyInitialization(Entity,
4054 SourceLocation(),
4055 Owned(Arg));
4056 if (ArgE.isInvalid())
4057 return true;
4058
4059 Arg = ArgE.takeAs<Expr>();
4060
4061 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004062 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4063
4064 if (ArgE.isInvalid())
4065 return true;
4066
4067 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004068 }
4069
Daniel Dunbar96a00142012-03-09 18:35:03 +00004070 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004071 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004072 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004073 return ExprError();
4074
Chris Lattner925e60d2007-12-28 05:29:59 +00004075 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004076 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004077 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004078
Douglas Gregor88a35142008-12-22 05:46:06 +00004079 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4080 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004081 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4082 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004083
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004084 // Check for sentinels
4085 if (NDecl)
4086 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004087
Chris Lattner59907c42007-08-10 20:18:51 +00004088 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004089 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004090 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004091 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004092
John McCall8e10f3b2011-02-26 05:39:39 +00004093 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004094 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004095 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004096 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004097 return ExprError();
4098 }
Chris Lattner59907c42007-08-10 20:18:51 +00004099
John McCall9ae2f072010-08-23 23:25:46 +00004100 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004101}
4102
John McCall60d7b3a2010-08-24 06:29:42 +00004103ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004104Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004105 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004106 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004107 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004108 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004109
4110 TypeSourceInfo *TInfo;
4111 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4112 if (!TInfo)
4113 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4114
John McCall9ae2f072010-08-23 23:25:46 +00004115 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004116}
4117
John McCall60d7b3a2010-08-24 06:29:42 +00004118ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004119Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004120 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004121 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004122
Eli Friedman6223c222008-05-20 05:22:08 +00004123 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004124 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004125 diag::err_illegal_decl_array_incomplete_type,
4126 SourceRange(LParenLoc,
4127 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004128 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004129 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004130 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004131 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004132 } else if (!literalType->isDependentType() &&
4133 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004134 diag::err_typecheck_decl_incomplete_type,
4135 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004136 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004137
Douglas Gregor99a2e602009-12-16 01:38:02 +00004138 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004139 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004140 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004141 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004142 SourceRange(LParenLoc, RParenLoc),
4143 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004144 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004145 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00004146 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004147 &literalType);
4148 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004149 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004150 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004151
Chris Lattner371f2582008-12-04 23:50:19 +00004152 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004153 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004154 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004155 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004156 }
Eli Friedman08544622009-12-22 02:35:53 +00004157
John McCallf89e55a2010-11-18 06:31:45 +00004158 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004159 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004160
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004161 return MaybeBindToTemporary(
4162 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004163 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004164}
4165
John McCall60d7b3a2010-08-24 06:29:42 +00004166ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004167Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004168 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004169 unsigned NumInit = InitArgList.size();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004170 Expr **InitList = InitArgList.get();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004171
John McCall3c3b7f92011-10-25 17:37:35 +00004172 // Immediately handle non-overload placeholders. Overloads can be
4173 // resolved contextually, but everything else here can't.
4174 for (unsigned I = 0; I != NumInit; ++I) {
John McCall32509f12011-11-15 01:35:18 +00004175 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00004176 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4177
4178 // Ignore failures; dropping the entire initializer list because
4179 // of one failure would be terrible for indexing/etc.
4180 if (result.isInvalid()) continue;
4181
4182 InitList[I] = result.take();
4183 }
4184 }
4185
Steve Naroff08d92e42007-09-15 18:49:24 +00004186 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004187 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004188
Ted Kremenek709210f2010-04-13 23:39:13 +00004189 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4190 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004191 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004192 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004193}
4194
John McCalldc05b112011-09-10 01:16:55 +00004195/// Do an explicit extend of the given block pointer if we're in ARC.
4196static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4197 assert(E.get()->getType()->isBlockPointerType());
4198 assert(E.get()->isRValue());
4199
4200 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004201 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004202
4203 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004204 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004205 /*base path*/ 0, VK_RValue);
4206 S.ExprNeedsCleanups = true;
4207}
4208
4209/// Prepare a conversion of the given expression to an ObjC object
4210/// pointer type.
4211CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4212 QualType type = E.get()->getType();
4213 if (type->isObjCObjectPointerType()) {
4214 return CK_BitCast;
4215 } else if (type->isBlockPointerType()) {
4216 maybeExtendBlockObject(*this, E);
4217 return CK_BlockPointerToObjCPointerCast;
4218 } else {
4219 assert(type->isPointerType());
4220 return CK_CPointerToObjCPointerCast;
4221 }
4222}
4223
John McCallf3ea8cf2010-11-14 08:17:51 +00004224/// Prepares for a scalar cast, performing all the necessary stages
4225/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004226CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004227 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4228 // Also, callers should have filtered out the invalid cases with
4229 // pointers. Everything else should be possible.
4230
John Wiegley429bb272011-04-08 18:41:53 +00004231 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004232 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004233 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004234
John McCall1d9b3b22011-09-09 05:25:32 +00004235 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004236 case Type::STK_MemberPointer:
4237 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004238
John McCall1d9b3b22011-09-09 05:25:32 +00004239 case Type::STK_CPointer:
4240 case Type::STK_BlockPointer:
4241 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004242 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004243 case Type::STK_CPointer:
4244 return CK_BitCast;
4245 case Type::STK_BlockPointer:
4246 return (SrcKind == Type::STK_BlockPointer
4247 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4248 case Type::STK_ObjCObjectPointer:
4249 if (SrcKind == Type::STK_ObjCObjectPointer)
4250 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004251 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004252 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004253 maybeExtendBlockObject(*this, Src);
4254 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004255 case Type::STK_Bool:
4256 return CK_PointerToBoolean;
4257 case Type::STK_Integral:
4258 return CK_PointerToIntegral;
4259 case Type::STK_Floating:
4260 case Type::STK_FloatingComplex:
4261 case Type::STK_IntegralComplex:
4262 case Type::STK_MemberPointer:
4263 llvm_unreachable("illegal cast from pointer");
4264 }
David Blaikie7530c032012-01-17 06:56:22 +00004265 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004266
John McCalldaa8e4e2010-11-15 09:13:47 +00004267 case Type::STK_Bool: // casting from bool is like casting from an integer
4268 case Type::STK_Integral:
4269 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004270 case Type::STK_CPointer:
4271 case Type::STK_ObjCObjectPointer:
4272 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004273 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004274 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004275 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004276 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004277 case Type::STK_Bool:
4278 return CK_IntegralToBoolean;
4279 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004280 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004281 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004282 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004283 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004284 Src = ImpCastExprToType(Src.take(),
4285 DestTy->castAs<ComplexType>()->getElementType(),
4286 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004287 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004288 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004289 Src = ImpCastExprToType(Src.take(),
4290 DestTy->castAs<ComplexType>()->getElementType(),
4291 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004292 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004293 case Type::STK_MemberPointer:
4294 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004295 }
David Blaikie7530c032012-01-17 06:56:22 +00004296 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004297
John McCalldaa8e4e2010-11-15 09:13:47 +00004298 case Type::STK_Floating:
4299 switch (DestTy->getScalarTypeKind()) {
4300 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004301 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004302 case Type::STK_Bool:
4303 return CK_FloatingToBoolean;
4304 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004305 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004306 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004307 Src = ImpCastExprToType(Src.take(),
4308 DestTy->castAs<ComplexType>()->getElementType(),
4309 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004310 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004311 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004312 Src = ImpCastExprToType(Src.take(),
4313 DestTy->castAs<ComplexType>()->getElementType(),
4314 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004315 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004316 case Type::STK_CPointer:
4317 case Type::STK_ObjCObjectPointer:
4318 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004319 llvm_unreachable("valid float->pointer cast?");
4320 case Type::STK_MemberPointer:
4321 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004322 }
David Blaikie7530c032012-01-17 06:56:22 +00004323 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004324
John McCalldaa8e4e2010-11-15 09:13:47 +00004325 case Type::STK_FloatingComplex:
4326 switch (DestTy->getScalarTypeKind()) {
4327 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004328 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004329 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004330 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004331 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004332 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4333 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004334 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004335 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004336 return CK_FloatingCast;
4337 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004338 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004339 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004340 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004341 Src = ImpCastExprToType(Src.take(),
4342 SrcTy->castAs<ComplexType>()->getElementType(),
4343 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004344 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004345 case Type::STK_CPointer:
4346 case Type::STK_ObjCObjectPointer:
4347 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004348 llvm_unreachable("valid complex float->pointer cast?");
4349 case Type::STK_MemberPointer:
4350 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004351 }
David Blaikie7530c032012-01-17 06:56:22 +00004352 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004353
John McCalldaa8e4e2010-11-15 09:13:47 +00004354 case Type::STK_IntegralComplex:
4355 switch (DestTy->getScalarTypeKind()) {
4356 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004357 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004358 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004359 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004360 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004361 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4362 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004363 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004364 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004365 return CK_IntegralCast;
4366 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004367 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004368 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004369 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004370 Src = ImpCastExprToType(Src.take(),
4371 SrcTy->castAs<ComplexType>()->getElementType(),
4372 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004373 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004374 case Type::STK_CPointer:
4375 case Type::STK_ObjCObjectPointer:
4376 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004377 llvm_unreachable("valid complex int->pointer cast?");
4378 case Type::STK_MemberPointer:
4379 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004380 }
David Blaikie7530c032012-01-17 06:56:22 +00004381 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004382 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004383
John McCallf3ea8cf2010-11-14 08:17:51 +00004384 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004385}
4386
Anders Carlssonc3516322009-10-16 02:48:28 +00004387bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004388 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004389 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004390
Anders Carlssona64db8f2007-11-27 05:51:55 +00004391 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004392 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004393 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004394 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004395 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004396 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004397 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004398 } else
4399 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004400 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004401 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004402
John McCall2de56d12010-08-25 11:45:40 +00004403 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004404 return false;
4405}
4406
John Wiegley429bb272011-04-08 18:41:53 +00004407ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4408 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004409 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004410
Anders Carlsson16a89042009-10-16 05:23:41 +00004411 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004412
Nate Begeman9b10da62009-06-27 22:05:55 +00004413 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4414 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004415 // In OpenCL, casts between vectors of different types are not allowed.
4416 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004417 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004418 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004419 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004420 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004421 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004422 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004423 return ExprError();
4424 }
John McCall2de56d12010-08-25 11:45:40 +00004425 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004426 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004427 }
4428
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004429 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004430 // conversion will take place first from scalar to elt type, and then
4431 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004432 if (SrcTy->isPointerType())
4433 return Diag(R.getBegin(),
4434 diag::err_invalid_conversion_between_vector_and_scalar)
4435 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004436
4437 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004438 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004439 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004440 if (CastExprRes.isInvalid())
4441 return ExprError();
4442 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004443
John McCall2de56d12010-08-25 11:45:40 +00004444 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004445 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004446}
4447
John McCall60d7b3a2010-08-24 06:29:42 +00004448ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004449Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4450 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004451 SourceLocation RParenLoc, Expr *CastExpr) {
4452 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004453 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004454
Richard Trieuccd891a2011-09-09 01:45:06 +00004455 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004456 if (D.isInvalidType())
4457 return ExprError();
4458
David Blaikie4e4d0842012-03-11 07:00:24 +00004459 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004460 // Check that there are no default arguments (C++ only).
4461 CheckExtraCXXDefaultArguments(D);
4462 }
4463
John McCalle82247a2011-10-01 05:17:03 +00004464 checkUnusedDeclAttributes(D);
4465
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004466 QualType castType = castTInfo->getType();
4467 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004468
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004469 bool isVectorLiteral = false;
4470
4471 // Check for an altivec or OpenCL literal,
4472 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004473 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4474 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004475 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004476 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004477 if (PLE && PLE->getNumExprs() == 0) {
4478 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4479 return ExprError();
4480 }
4481 if (PE || PLE->getNumExprs() == 1) {
4482 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4483 if (!E->getType()->isVectorType())
4484 isVectorLiteral = true;
4485 }
4486 else
4487 isVectorLiteral = true;
4488 }
4489
4490 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4491 // then handle it as such.
4492 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004493 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004494
Nate Begeman2ef13e52009-08-10 23:49:36 +00004495 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004496 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4497 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004498 if (isa<ParenListExpr>(CastExpr)) {
4499 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004500 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004501 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004502 }
John McCallb042fdf2010-01-15 18:56:44 +00004503
Richard Trieuccd891a2011-09-09 01:45:06 +00004504 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004505}
4506
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004507ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4508 SourceLocation RParenLoc, Expr *E,
4509 TypeSourceInfo *TInfo) {
4510 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4511 "Expected paren or paren list expression");
4512
4513 Expr **exprs;
4514 unsigned numExprs;
4515 Expr *subExpr;
4516 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4517 exprs = PE->getExprs();
4518 numExprs = PE->getNumExprs();
4519 } else {
4520 subExpr = cast<ParenExpr>(E)->getSubExpr();
4521 exprs = &subExpr;
4522 numExprs = 1;
4523 }
4524
4525 QualType Ty = TInfo->getType();
4526 assert(Ty->isVectorType() && "Expected vector type");
4527
Chris Lattner5f9e2722011-07-23 10:55:15 +00004528 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004529 const VectorType *VTy = Ty->getAs<VectorType>();
4530 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4531
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004532 // '(...)' form of vector initialization in AltiVec: the number of
4533 // initializers must be one or must match the size of the vector.
4534 // If a single value is specified in the initializer then it will be
4535 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004536 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004537 // The number of initializers must be one or must match the size of the
4538 // vector. If a single value is specified in the initializer then it will
4539 // be replicated to all the components of the vector
4540 if (numExprs == 1) {
4541 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004542 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4543 if (Literal.isInvalid())
4544 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004545 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004546 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004547 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4548 }
4549 else if (numExprs < numElems) {
4550 Diag(E->getExprLoc(),
4551 diag::err_incorrect_number_of_vector_initializers);
4552 return ExprError();
4553 }
4554 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004555 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004556 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004557 else {
4558 // For OpenCL, when the number of initializers is a single value,
4559 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004560 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004561 VTy->getVectorKind() == VectorType::GenericVector &&
4562 numExprs == 1) {
4563 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004564 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4565 if (Literal.isInvalid())
4566 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004567 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004568 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004569 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4570 }
4571
Benjamin Kramer14c59822012-02-14 12:06:21 +00004572 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004573 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004574 // FIXME: This means that pretty-printing the final AST will produce curly
4575 // braces instead of the original commas.
4576 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4577 &initExprs[0],
4578 initExprs.size(), RParenLoc);
4579 initE->setType(Ty);
4580 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4581}
4582
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004583/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4584/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004585ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004586Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4587 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004588 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004589 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004590
John McCall60d7b3a2010-08-24 06:29:42 +00004591 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Nate Begeman2ef13e52009-08-10 23:49:36 +00004593 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004594 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4595 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004596
John McCall9ae2f072010-08-23 23:25:46 +00004597 if (Result.isInvalid()) return ExprError();
4598
4599 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004600}
4601
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004602ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4603 SourceLocation R,
4604 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004605 unsigned nexprs = Val.size();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004606 Expr **exprs = Val.get();
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004607 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004608 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004609 return Owned(expr);
4610}
4611
Chandler Carruth82214a82011-02-18 23:54:50 +00004612/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004613/// constant and the other is not a pointer. Returns true if a diagnostic is
4614/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004615bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004616 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004617 Expr *NullExpr = LHSExpr;
4618 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004619 Expr::NullPointerConstantKind NullKind =
4620 NullExpr->isNullPointerConstant(Context,
4621 Expr::NPC_ValueDependentIsNotNull);
4622
4623 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004624 NullExpr = RHSExpr;
4625 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004626 NullKind =
4627 NullExpr->isNullPointerConstant(Context,
4628 Expr::NPC_ValueDependentIsNotNull);
4629 }
4630
4631 if (NullKind == Expr::NPCK_NotNull)
4632 return false;
4633
David Blaikie50800fc2012-08-08 17:33:31 +00004634 if (NullKind == Expr::NPCK_ZeroExpression)
4635 return false;
4636
4637 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004638 // In this case, check to make sure that we got here from a "NULL"
4639 // string in the source code.
4640 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004641 SourceLocation loc = NullExpr->getExprLoc();
4642 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004643 return false;
4644 }
4645
4646 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4647 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4648 << NonPointerExpr->getType() << DiagType
4649 << NonPointerExpr->getSourceRange();
4650 return true;
4651}
4652
Richard Trieu26f96072011-09-02 01:51:02 +00004653/// \brief Return false if the condition expression is valid, true otherwise.
4654static bool checkCondition(Sema &S, Expr *Cond) {
4655 QualType CondTy = Cond->getType();
4656
4657 // C99 6.5.15p2
4658 if (CondTy->isScalarType()) return false;
4659
4660 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004661 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004662 return false;
4663
4664 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004665 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004666 diag::err_typecheck_cond_expect_scalar :
4667 diag::err_typecheck_cond_expect_scalar_or_vector)
4668 << CondTy;
4669 return true;
4670}
4671
4672/// \brief Return false if the two expressions can be converted to a vector,
4673/// true otherwise
4674static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4675 ExprResult &RHS,
4676 QualType CondTy) {
4677 // Both operands should be of scalar type.
4678 if (!LHS.get()->getType()->isScalarType()) {
4679 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4680 << CondTy;
4681 return true;
4682 }
4683 if (!RHS.get()->getType()->isScalarType()) {
4684 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4685 << CondTy;
4686 return true;
4687 }
4688
4689 // Implicity convert these scalars to the type of the condition.
4690 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4691 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4692 return false;
4693}
4694
4695/// \brief Handle when one or both operands are void type.
4696static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4697 ExprResult &RHS) {
4698 Expr *LHSExpr = LHS.get();
4699 Expr *RHSExpr = RHS.get();
4700
4701 if (!LHSExpr->getType()->isVoidType())
4702 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4703 << RHSExpr->getSourceRange();
4704 if (!RHSExpr->getType()->isVoidType())
4705 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4706 << LHSExpr->getSourceRange();
4707 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4708 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4709 return S.Context.VoidTy;
4710}
4711
4712/// \brief Return false if the NullExpr can be promoted to PointerTy,
4713/// true otherwise.
4714static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4715 QualType PointerTy) {
4716 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4717 !NullExpr.get()->isNullPointerConstant(S.Context,
4718 Expr::NPC_ValueDependentIsNull))
4719 return true;
4720
4721 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4722 return false;
4723}
4724
4725/// \brief Checks compatibility between two pointers and return the resulting
4726/// type.
4727static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4728 ExprResult &RHS,
4729 SourceLocation Loc) {
4730 QualType LHSTy = LHS.get()->getType();
4731 QualType RHSTy = RHS.get()->getType();
4732
4733 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4734 // Two identical pointers types are always compatible.
4735 return LHSTy;
4736 }
4737
4738 QualType lhptee, rhptee;
4739
4740 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004741 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4742 lhptee = LHSBTy->getPointeeType();
4743 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004744 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004745 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4746 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004747 }
4748
Eli Friedmanae916a12012-04-05 22:30:04 +00004749 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4750 // differently qualified versions of compatible types, the result type is
4751 // a pointer to an appropriately qualified version of the composite
4752 // type.
4753
4754 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4755 // clause doesn't make sense for our extensions. E.g. address space 2 should
4756 // be incompatible with address space 3: they may live on different devices or
4757 // anything.
4758 Qualifiers lhQual = lhptee.getQualifiers();
4759 Qualifiers rhQual = rhptee.getQualifiers();
4760
4761 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4762 lhQual.removeCVRQualifiers();
4763 rhQual.removeCVRQualifiers();
4764
4765 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4766 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4767
4768 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4769
4770 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004771 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4772 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4773 << RHS.get()->getSourceRange();
4774 // In this situation, we assume void* type. No especially good
4775 // reason, but this is what gcc does, and we do have to pick
4776 // to get a consistent AST.
4777 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4778 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4779 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4780 return incompatTy;
4781 }
4782
4783 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004784 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4785 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004786
Eli Friedmanae916a12012-04-05 22:30:04 +00004787 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4788 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4789 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004790}
4791
4792/// \brief Return the resulting type when the operands are both block pointers.
4793static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4794 ExprResult &LHS,
4795 ExprResult &RHS,
4796 SourceLocation Loc) {
4797 QualType LHSTy = LHS.get()->getType();
4798 QualType RHSTy = RHS.get()->getType();
4799
4800 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4801 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4802 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4803 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4804 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4805 return destType;
4806 }
4807 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4808 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4809 << RHS.get()->getSourceRange();
4810 return QualType();
4811 }
4812
4813 // We have 2 block pointer types.
4814 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4815}
4816
4817/// \brief Return the resulting type when the operands are both pointers.
4818static QualType
4819checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4820 ExprResult &RHS,
4821 SourceLocation Loc) {
4822 // get the pointer types
4823 QualType LHSTy = LHS.get()->getType();
4824 QualType RHSTy = RHS.get()->getType();
4825
4826 // get the "pointed to" types
4827 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4828 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4829
4830 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4831 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4832 // Figure out necessary qualifiers (C99 6.5.15p6)
4833 QualType destPointee
4834 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4835 QualType destType = S.Context.getPointerType(destPointee);
4836 // Add qualifiers if necessary.
4837 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4838 // Promote to void*.
4839 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4840 return destType;
4841 }
4842 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4843 QualType destPointee
4844 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4845 QualType destType = S.Context.getPointerType(destPointee);
4846 // Add qualifiers if necessary.
4847 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4848 // Promote to void*.
4849 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4850 return destType;
4851 }
4852
4853 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4854}
4855
4856/// \brief Return false if the first expression is not an integer and the second
4857/// expression is not a pointer, true otherwise.
4858static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4859 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004860 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004861 if (!PointerExpr->getType()->isPointerType() ||
4862 !Int.get()->getType()->isIntegerType())
4863 return false;
4864
Richard Trieuccd891a2011-09-09 01:45:06 +00004865 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4866 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004867
4868 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4869 << Expr1->getType() << Expr2->getType()
4870 << Expr1->getSourceRange() << Expr2->getSourceRange();
4871 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4872 CK_IntegralToPointer);
4873 return true;
4874}
4875
Richard Trieu33fc7572011-09-06 20:06:39 +00004876/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4877/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004878/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004879QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4880 ExprResult &RHS, ExprValueKind &VK,
4881 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004882 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004883
Richard Trieu33fc7572011-09-06 20:06:39 +00004884 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4885 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004886 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004887
Richard Trieu33fc7572011-09-06 20:06:39 +00004888 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4889 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004890 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004891
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004892 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004893 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004894 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004895
4896 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004897 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004898
John Wiegley429bb272011-04-08 18:41:53 +00004899 Cond = UsualUnaryConversions(Cond.take());
4900 if (Cond.isInvalid())
4901 return QualType();
4902 LHS = UsualUnaryConversions(LHS.take());
4903 if (LHS.isInvalid())
4904 return QualType();
4905 RHS = UsualUnaryConversions(RHS.take());
4906 if (RHS.isInvalid())
4907 return QualType();
4908
4909 QualType CondTy = Cond.get()->getType();
4910 QualType LHSTy = LHS.get()->getType();
4911 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004912
Reid Spencer5f016e22007-07-11 17:01:13 +00004913 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004914 if (checkCondition(*this, Cond.get()))
4915 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004916
Chris Lattner70d67a92008-01-06 22:42:25 +00004917 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004918 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004919 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004920
Nate Begeman6155d732010-09-20 22:41:17 +00004921 // OpenCL: If the condition is a vector, and both operands are scalar,
4922 // attempt to implicity convert them to the vector type to act like the
4923 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004924 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004925 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004926 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004927
Chris Lattner70d67a92008-01-06 22:42:25 +00004928 // If both operands have arithmetic type, do the usual arithmetic conversions
4929 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004930 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4931 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004932 if (LHS.isInvalid() || RHS.isInvalid())
4933 return QualType();
4934 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004935 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004936
Chris Lattner70d67a92008-01-06 22:42:25 +00004937 // If both operands are the same structure or union type, the result is that
4938 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004939 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4940 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004941 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004942 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004943 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004944 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004945 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004946 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004947
Chris Lattner70d67a92008-01-06 22:42:25 +00004948 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004949 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004950 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004951 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004952 }
Richard Trieu26f96072011-09-02 01:51:02 +00004953
Steve Naroffb6d54e52008-01-08 01:11:38 +00004954 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4955 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004956 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4957 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004958
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004959 // All objective-c pointer type analysis is done here.
4960 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4961 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004962 if (LHS.isInvalid() || RHS.isInvalid())
4963 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004964 if (!compositeType.isNull())
4965 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004966
4967
Steve Naroff7154a772009-07-01 14:36:47 +00004968 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004969 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4970 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4971 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004972
Steve Naroff7154a772009-07-01 14:36:47 +00004973 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004974 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4975 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4976 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004977
John McCall404cd162010-11-13 01:35:44 +00004978 // GCC compatibility: soften pointer/integer mismatch. Note that
4979 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004980 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4981 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004982 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004983 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4984 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004985 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004986
Chandler Carruth82214a82011-02-18 23:54:50 +00004987 // Emit a better diagnostic if one of the expressions is a null pointer
4988 // constant and the other is not a pointer type. In this case, the user most
4989 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004990 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004991 return QualType();
4992
Chris Lattner70d67a92008-01-06 22:42:25 +00004993 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004994 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004995 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4996 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004997 return QualType();
4998}
4999
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005000/// FindCompositeObjCPointerType - Helper method to find composite type of
5001/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005002QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005003 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005004 QualType LHSTy = LHS.get()->getType();
5005 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005006
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005007 // Handle things like Class and struct objc_class*. Here we case the result
5008 // to the pseudo-builtin, because that will be implicitly cast back to the
5009 // redefinition type if an attempt is made to access its fields.
5010 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005011 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005012 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005013 return LHSTy;
5014 }
5015 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005016 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005017 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005018 return RHSTy;
5019 }
5020 // And the same for struct objc_object* / id
5021 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005022 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005023 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005024 return LHSTy;
5025 }
5026 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005027 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005028 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005029 return RHSTy;
5030 }
5031 // And the same for struct objc_selector* / SEL
5032 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005033 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005034 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005035 return LHSTy;
5036 }
5037 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005038 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005039 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005040 return RHSTy;
5041 }
5042 // Check constraints for Objective-C object pointers types.
5043 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005044
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005045 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5046 // Two identical object pointer types are always compatible.
5047 return LHSTy;
5048 }
John McCall1d9b3b22011-09-09 05:25:32 +00005049 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5050 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005051 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005052
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005053 // If both operands are interfaces and either operand can be
5054 // assigned to the other, use that type as the composite
5055 // type. This allows
5056 // xxx ? (A*) a : (B*) b
5057 // where B is a subclass of A.
5058 //
5059 // Additionally, as for assignment, if either type is 'id'
5060 // allow silent coercion. Finally, if the types are
5061 // incompatible then make sure to use 'id' as the composite
5062 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005063
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005064 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5065 // It could return the composite type.
5066 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5067 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5068 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5069 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5070 } else if ((LHSTy->isObjCQualifiedIdType() ||
5071 RHSTy->isObjCQualifiedIdType()) &&
5072 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5073 // Need to handle "id<xx>" explicitly.
5074 // GCC allows qualified id and any Objective-C type to devolve to
5075 // id. Currently localizing to here until clear this should be
5076 // part of ObjCQualifiedIdTypesAreCompatible.
5077 compositeType = Context.getObjCIdType();
5078 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5079 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005080 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005081 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5082 ;
5083 else {
5084 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5085 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005086 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005087 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005088 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5089 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005090 return incompatTy;
5091 }
5092 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005093 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5094 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005095 return compositeType;
5096 }
5097 // Check Objective-C object pointer types and 'void *'
5098 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005099 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005100 // ARC forbids the implicit conversion of object pointers to 'void *',
5101 // so these types are not compatible.
5102 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5103 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5104 LHS = RHS = true;
5105 return QualType();
5106 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005107 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5108 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5109 QualType destPointee
5110 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5111 QualType destType = Context.getPointerType(destPointee);
5112 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005113 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005114 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005115 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005116 return destType;
5117 }
5118 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005119 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005120 // ARC forbids the implicit conversion of object pointers to 'void *',
5121 // so these types are not compatible.
5122 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5123 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5124 LHS = RHS = true;
5125 return QualType();
5126 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005127 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5128 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5129 QualType destPointee
5130 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5131 QualType destType = Context.getPointerType(destPointee);
5132 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005133 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005134 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005135 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005136 return destType;
5137 }
5138 return QualType();
5139}
5140
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005141/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005142/// ParenRange in parentheses.
5143static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005144 const PartialDiagnostic &Note,
5145 SourceRange ParenRange) {
5146 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5147 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5148 EndLoc.isValid()) {
5149 Self.Diag(Loc, Note)
5150 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5151 << FixItHint::CreateInsertion(EndLoc, ")");
5152 } else {
5153 // We can't display the parentheses, so just show the bare note.
5154 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005155 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005156}
5157
5158static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5159 return Opc >= BO_Mul && Opc <= BO_Shr;
5160}
5161
Hans Wennborg2f072b42011-06-09 17:06:51 +00005162/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5163/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005164/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5165/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005166static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005167 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005168 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5169 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005170 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005171 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005172
5173 // Built-in binary operator.
5174 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5175 if (IsArithmeticOp(OP->getOpcode())) {
5176 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005177 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005178 return true;
5179 }
5180 }
5181
5182 // Overloaded operator.
5183 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5184 if (Call->getNumArgs() != 2)
5185 return false;
5186
5187 // Make sure this is really a binary operator that is safe to pass into
5188 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5189 OverloadedOperatorKind OO = Call->getOperator();
5190 if (OO < OO_Plus || OO > OO_Arrow)
5191 return false;
5192
5193 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5194 if (IsArithmeticOp(OpKind)) {
5195 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005196 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005197 return true;
5198 }
5199 }
5200
5201 return false;
5202}
5203
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005204static bool IsLogicOp(BinaryOperatorKind Opc) {
5205 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5206}
5207
Hans Wennborg2f072b42011-06-09 17:06:51 +00005208/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5209/// or is a logical expression such as (x==y) which has int type, but is
5210/// commonly interpreted as boolean.
5211static bool ExprLooksBoolean(Expr *E) {
5212 E = E->IgnoreParenImpCasts();
5213
5214 if (E->getType()->isBooleanType())
5215 return true;
5216 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5217 return IsLogicOp(OP->getOpcode());
5218 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5219 return OP->getOpcode() == UO_LNot;
5220
5221 return false;
5222}
5223
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005224/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5225/// and binary operator are mixed in a way that suggests the programmer assumed
5226/// the conditional operator has higher precedence, for example:
5227/// "int x = a + someBinaryCondition ? 1 : 2".
5228static void DiagnoseConditionalPrecedence(Sema &Self,
5229 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005230 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005231 Expr *LHSExpr,
5232 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005233 BinaryOperatorKind CondOpcode;
5234 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005235
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005236 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005237 return;
5238 if (!ExprLooksBoolean(CondRHS))
5239 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005240
Hans Wennborg2f072b42011-06-09 17:06:51 +00005241 // The condition is an arithmetic binary expression, with a right-
5242 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005243
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005244 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005245 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005246 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005247
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005248 SuggestParentheses(Self, OpLoc,
5249 Self.PDiag(diag::note_precedence_conditional_silence)
5250 << BinaryOperator::getOpcodeStr(CondOpcode),
5251 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005252
5253 SuggestParentheses(Self, OpLoc,
5254 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005255 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005256}
5257
Steve Narofff69936d2007-09-16 03:34:24 +00005258/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005259/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005260ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005261 SourceLocation ColonLoc,
5262 Expr *CondExpr, Expr *LHSExpr,
5263 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005264 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5265 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005266 OpaqueValueExpr *opaqueValue = 0;
5267 Expr *commonExpr = 0;
5268 if (LHSExpr == 0) {
5269 commonExpr = CondExpr;
5270
5271 // We usually want to apply unary conversions *before* saving, except
5272 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005273 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005274 && !commonExpr->isTypeDependent()
5275 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5276 && commonExpr->isGLValue()
5277 && commonExpr->isOrdinaryOrBitFieldObject()
5278 && RHSExpr->isOrdinaryOrBitFieldObject()
5279 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005280 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5281 if (commonRes.isInvalid())
5282 return ExprError();
5283 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005284 }
5285
5286 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5287 commonExpr->getType(),
5288 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005289 commonExpr->getObjectKind(),
5290 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005291 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005292 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005293
John McCallf89e55a2010-11-18 06:31:45 +00005294 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005295 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005296 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5297 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005298 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005299 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5300 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005301 return ExprError();
5302
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005303 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5304 RHS.get());
5305
John McCall56ca35d2011-02-17 10:25:35 +00005306 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005307 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5308 LHS.take(), ColonLoc,
5309 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005310
5311 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005312 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005313 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5314 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005315}
5316
John McCalle4be87e2011-01-31 23:13:11 +00005317// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005318// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005319// routine is it effectively iqnores the qualifiers on the top level pointee.
5320// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5321// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005322static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005323checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5324 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5325 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005326
Reid Spencer5f016e22007-07-11 17:01:13 +00005327 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005328 const Type *lhptee, *rhptee;
5329 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005330 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5331 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332
John McCalle4be87e2011-01-31 23:13:11 +00005333 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005334
5335 // C99 6.5.16.1p1: This following citation is common to constraints
5336 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5337 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005338 Qualifiers lq;
5339
John McCallf85e1932011-06-15 23:02:42 +00005340 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5341 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5342 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5343 // Ignore lifetime for further calculation.
5344 lhq.removeObjCLifetime();
5345 rhq.removeObjCLifetime();
5346 }
5347
John McCall86c05f32011-02-01 00:10:29 +00005348 if (!lhq.compatiblyIncludes(rhq)) {
5349 // Treat address-space mismatches as fatal. TODO: address subspaces
5350 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5351 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5352
John McCallf85e1932011-06-15 23:02:42 +00005353 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005354 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005355 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005356 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005357 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005358 && (lhptee->isVoidType() || rhptee->isVoidType()))
5359 ; // keep old
5360
John McCallf85e1932011-06-15 23:02:42 +00005361 // Treat lifetime mismatches as fatal.
5362 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5363 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5364
John McCall86c05f32011-02-01 00:10:29 +00005365 // For GCC compatibility, other qualifier mismatches are treated
5366 // as still compatible in C.
5367 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5368 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005369
Mike Stumpeed9cac2009-02-19 03:04:26 +00005370 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5371 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005372 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005373 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005374 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005375 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005376
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005377 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005378 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005379 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005380 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005381
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005382 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005383 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005384 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005385
5386 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005387 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005388 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005389 }
John McCall86c05f32011-02-01 00:10:29 +00005390
Mike Stumpeed9cac2009-02-19 03:04:26 +00005391 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005392 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005393 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5394 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005395 // Check if the pointee types are compatible ignoring the sign.
5396 // We explicitly check for char so that we catch "char" vs
5397 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005398 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005399 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005400 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005401 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005402
Chris Lattner6a2b9262009-10-17 20:33:28 +00005403 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005404 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005405 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005406 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005407
John McCall86c05f32011-02-01 00:10:29 +00005408 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005409 // Types are compatible ignoring the sign. Qualifier incompatibility
5410 // takes priority over sign incompatibility because the sign
5411 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005412 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005413 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005414
John McCalle4be87e2011-01-31 23:13:11 +00005415 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005416 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005417
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005418 // If we are a multi-level pointer, it's possible that our issue is simply
5419 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5420 // the eventual target type is the same and the pointers have the same
5421 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005422 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005423 do {
John McCall86c05f32011-02-01 00:10:29 +00005424 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5425 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005426 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005427
John McCall86c05f32011-02-01 00:10:29 +00005428 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005429 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005430 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005431
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005432 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005433 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005434 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005435 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005436 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5437 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005438 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005439}
5440
John McCalle4be87e2011-01-31 23:13:11 +00005441/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005442/// block pointer types are compatible or whether a block and normal pointer
5443/// are compatible. It is more restrict than comparing two function pointer
5444// types.
John McCalle4be87e2011-01-31 23:13:11 +00005445static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005446checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5447 QualType RHSType) {
5448 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5449 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005450
Steve Naroff1c7d0672008-09-04 15:10:53 +00005451 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005452
Steve Naroff1c7d0672008-09-04 15:10:53 +00005453 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005454 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5455 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005456
John McCalle4be87e2011-01-31 23:13:11 +00005457 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005458 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005459 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005460
John McCalle4be87e2011-01-31 23:13:11 +00005461 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005462
Steve Naroff1c7d0672008-09-04 15:10:53 +00005463 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005464 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5465 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005466
Richard Trieu1da27a12011-09-06 20:21:22 +00005467 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005468 return Sema::IncompatibleBlockPointer;
5469
Steve Naroff1c7d0672008-09-04 15:10:53 +00005470 return ConvTy;
5471}
5472
John McCalle4be87e2011-01-31 23:13:11 +00005473/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005474/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005475static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005476checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5477 QualType RHSType) {
5478 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5479 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005480
Richard Trieu1da27a12011-09-06 20:21:22 +00005481 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005482 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005483 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5484 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005485 return Sema::IncompatiblePointer;
5486 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005487 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005488 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005489 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5490 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005491 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005492 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005493 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005494 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5495 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005496
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005497 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5498 // make an exception for id<P>
5499 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005500 return Sema::CompatiblePointerDiscardsQualifiers;
5501
Richard Trieu1da27a12011-09-06 20:21:22 +00005502 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005503 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005504 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005505 return Sema::IncompatibleObjCQualifiedId;
5506 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005507}
5508
John McCall1c23e912010-11-16 02:32:08 +00005509Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005510Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005511 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005512 // Fake up an opaque expression. We don't actually care about what
5513 // cast operations are required, so if CheckAssignmentConstraints
5514 // adds casts to this they'll be wasted, but fortunately that doesn't
5515 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005516 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5517 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005518 CastKind K = CK_Invalid;
5519
Richard Trieu1da27a12011-09-06 20:21:22 +00005520 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005521}
5522
Mike Stumpeed9cac2009-02-19 03:04:26 +00005523/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5524/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005525/// pointers. Here are some objectionable examples that GCC considers warnings:
5526///
5527/// int a, *pint;
5528/// short *pshort;
5529/// struct foo *pfoo;
5530///
5531/// pint = pshort; // warning: assignment from incompatible pointer type
5532/// a = pint; // warning: assignment makes integer from pointer without a cast
5533/// pint = a; // warning: assignment makes pointer from integer without a cast
5534/// pint = pfoo; // warning: assignment from incompatible pointer type
5535///
5536/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005537/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005538///
John McCalldaa8e4e2010-11-15 09:13:47 +00005539/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005540Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005541Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005542 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005543 QualType RHSType = RHS.get()->getType();
5544 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005545
Chris Lattnerfc144e22008-01-04 23:18:45 +00005546 // Get canonical types. We're not formatting these types, just comparing
5547 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005548 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5549 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005550
Eli Friedmanb001de72011-10-06 23:00:33 +00005551
John McCallb6cfa242011-01-31 22:28:28 +00005552 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005553 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005554 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005555 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005556 }
5557
Eli Friedman860a3192012-06-16 02:19:17 +00005558 // If we have an atomic type, try a non-atomic assignment, then just add an
5559 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005560 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005561 Sema::AssignConvertType result =
5562 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5563 if (result != Compatible)
5564 return result;
5565 if (Kind != CK_NoOp)
5566 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5567 Kind = CK_NonAtomicToAtomic;
5568 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005569 }
5570
Douglas Gregor9d293df2008-10-28 00:22:11 +00005571 // If the left-hand side is a reference type, then we are in a
5572 // (rare!) case where we've allowed the use of references in C,
5573 // e.g., as a parameter type in a built-in function. In this case,
5574 // just make sure that the type referenced is compatible with the
5575 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005576 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005577 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005578 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5579 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005580 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005581 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005582 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005583 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005584 }
John McCallb6cfa242011-01-31 22:28:28 +00005585
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005586 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5587 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005588 if (LHSType->isExtVectorType()) {
5589 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005590 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005591 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005592 // CK_VectorSplat does T -> vector T, so first cast to the
5593 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005594 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5595 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005596 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005597 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005598 }
5599 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005600 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005601 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005602 }
Mike Stump1eb44332009-09-09 15:08:12 +00005603
John McCallb6cfa242011-01-31 22:28:28 +00005604 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005605 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5606 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005607 // Allow assignments of an AltiVec vector type to an equivalent GCC
5608 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005609 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005610 Kind = CK_BitCast;
5611 return Compatible;
5612 }
5613
Douglas Gregor255210e2010-08-06 10:14:59 +00005614 // If we are allowing lax vector conversions, and LHS and RHS are both
5615 // vectors, the total size only needs to be the same. This is a bitcast;
5616 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005617 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005618 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005619 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005620 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005621 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005622 }
5623 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005624 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005625
John McCallb6cfa242011-01-31 22:28:28 +00005626 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005627 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005628 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005629 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005630 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005631 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005632
John McCallb6cfa242011-01-31 22:28:28 +00005633 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005634 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005635 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005636 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005637 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005638 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005639 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005640
John McCallb6cfa242011-01-31 22:28:28 +00005641 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005642 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005643 Kind = CK_IntegralToPointer; // FIXME: null?
5644 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005645 }
John McCallb6cfa242011-01-31 22:28:28 +00005646
5647 // C pointers are not compatible with ObjC object pointers,
5648 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005649 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005650 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005651 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005652 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005653 return Compatible;
5654 }
5655
5656 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005657 if (RHSType->isObjCClassType() &&
5658 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005659 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005660 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005661 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005662 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005663
John McCallb6cfa242011-01-31 22:28:28 +00005664 Kind = CK_BitCast;
5665 return IncompatiblePointer;
5666 }
5667
5668 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005669 if (RHSType->getAs<BlockPointerType>()) {
5670 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005671 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005672 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005673 }
Steve Naroffb4406862008-09-29 18:10:17 +00005674 }
John McCallb6cfa242011-01-31 22:28:28 +00005675
Steve Naroff1c7d0672008-09-04 15:10:53 +00005676 return Incompatible;
5677 }
5678
John McCallb6cfa242011-01-31 22:28:28 +00005679 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005680 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005681 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005682 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005683 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005684 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005685 }
5686
5687 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005688 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005689 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005690 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005691 }
5692
John McCallb6cfa242011-01-31 22:28:28 +00005693 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005694 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005695 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005696 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005697 }
Steve Naroffb4406862008-09-29 18:10:17 +00005698
John McCallb6cfa242011-01-31 22:28:28 +00005699 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005700 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005701 if (RHSPT->getPointeeType()->isVoidType()) {
5702 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005703 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005704 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005705
Chris Lattnerfc144e22008-01-04 23:18:45 +00005706 return Incompatible;
5707 }
5708
John McCallb6cfa242011-01-31 22:28:28 +00005709 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005710 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005711 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005712 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005713 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005714 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005715 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005716 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005717 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005718 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005719 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005720 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005721 }
5722
5723 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005724 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005725 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005726 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005727 }
5728
John McCallb6cfa242011-01-31 22:28:28 +00005729 // In general, C pointers are not compatible with ObjC object pointers,
5730 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005731 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005732 Kind = CK_CPointerToObjCPointerCast;
5733
John McCallb6cfa242011-01-31 22:28:28 +00005734 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005735 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005736 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005737 }
5738
5739 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005740 if (LHSType->isObjCClassType() &&
5741 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005742 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005743 return Compatible;
5744 }
5745
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005746 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005747 }
John McCallb6cfa242011-01-31 22:28:28 +00005748
5749 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005750 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005751 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005752 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005753 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005754 }
5755
Steve Naroff14108da2009-07-10 23:34:53 +00005756 return Incompatible;
5757 }
John McCallb6cfa242011-01-31 22:28:28 +00005758
5759 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005760 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005761 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005762 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005763 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005764 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005765 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005766
John McCallb6cfa242011-01-31 22:28:28 +00005767 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005768 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005769 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005770 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005771 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005772
Chris Lattnerfc144e22008-01-04 23:18:45 +00005773 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005774 }
John McCallb6cfa242011-01-31 22:28:28 +00005775
5776 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005777 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005778 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005779 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005780 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005781 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005782 }
Steve Naroff14108da2009-07-10 23:34:53 +00005783
John McCallb6cfa242011-01-31 22:28:28 +00005784 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005785 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005786 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005787 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005788 }
5789
Steve Naroff14108da2009-07-10 23:34:53 +00005790 return Incompatible;
5791 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005792
John McCallb6cfa242011-01-31 22:28:28 +00005793 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005794 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5795 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005796 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005797 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005798 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005799 }
John McCallb6cfa242011-01-31 22:28:28 +00005800
Reid Spencer5f016e22007-07-11 17:01:13 +00005801 return Incompatible;
5802}
5803
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005804/// \brief Constructs a transparent union from an expression that is
5805/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005806static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5807 ExprResult &EResult, QualType UnionType,
5808 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005809 // Build an initializer list that designates the appropriate member
5810 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005811 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005812 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005813 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005814 SourceLocation());
5815 Initializer->setType(UnionType);
5816 Initializer->setInitializedFieldInUnion(Field);
5817
5818 // Build a compound literal constructing a value of the transparent
5819 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005820 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005821 EResult = S.Owned(
5822 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5823 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005824}
5825
5826Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005827Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005828 ExprResult &RHS) {
5829 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005830
Mike Stump1eb44332009-09-09 15:08:12 +00005831 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005832 // transparent_union GCC extension.
5833 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005834 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005835 return Incompatible;
5836
5837 // The field to initialize within the transparent union.
5838 RecordDecl *UD = UT->getDecl();
5839 FieldDecl *InitField = 0;
5840 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005841 for (RecordDecl::field_iterator it = UD->field_begin(),
5842 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005843 it != itend; ++it) {
5844 if (it->getType()->isPointerType()) {
5845 // If the transparent union contains a pointer type, we allow:
5846 // 1) void pointer
5847 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005848 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005849 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005850 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005851 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005852 break;
5853 }
Mike Stump1eb44332009-09-09 15:08:12 +00005854
Richard Trieuf7720da2011-09-06 20:40:12 +00005855 if (RHS.get()->isNullPointerConstant(Context,
5856 Expr::NPC_ValueDependentIsNull)) {
5857 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5858 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005859 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005860 break;
5861 }
5862 }
5863
John McCalldaa8e4e2010-11-15 09:13:47 +00005864 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005865 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005866 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005867 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005868 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005869 break;
5870 }
5871 }
5872
5873 if (!InitField)
5874 return Incompatible;
5875
Richard Trieuf7720da2011-09-06 20:40:12 +00005876 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005877 return Compatible;
5878}
5879
Chris Lattner5cf216b2008-01-04 18:04:52 +00005880Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005881Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5882 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005883 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005884 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005885 // C++ 5.17p3: If the left operand is not of class type, the
5886 // expression is implicitly converted (C++ 4) to the
5887 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005888 ExprResult Res;
5889 if (Diagnose) {
5890 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5891 AA_Assigning);
5892 } else {
5893 ImplicitConversionSequence ICS =
5894 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5895 /*SuppressUserConversions=*/false,
5896 /*AllowExplicit=*/false,
5897 /*InOverloadResolution=*/false,
5898 /*CStyle=*/false,
5899 /*AllowObjCWritebackConversion=*/false);
5900 if (ICS.isFailure())
5901 return Incompatible;
5902 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5903 ICS, AA_Assigning);
5904 }
John Wiegley429bb272011-04-08 18:41:53 +00005905 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005906 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005907 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005908 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005909 !CheckObjCARCUnavailableWeakConversion(LHSType,
5910 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005911 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005912 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005913 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005914 }
5915
5916 // FIXME: Currently, we fall through and treat C++ classes like C
5917 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005918 // FIXME: We also fall through for atomics; not sure what should
5919 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005920 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005921
Steve Naroff529a4ad2007-11-27 17:58:44 +00005922 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5923 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005924 if ((LHSType->isPointerType() ||
5925 LHSType->isObjCObjectPointerType() ||
5926 LHSType->isBlockPointerType())
5927 && RHS.get()->isNullPointerConstant(Context,
5928 Expr::NPC_ValueDependentIsNull)) {
5929 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005930 return Compatible;
5931 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005932
Chris Lattner943140e2007-10-16 02:55:40 +00005933 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005934 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005935 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005936 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005937 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005938 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005939 if (!LHSType->isReferenceType()) {
5940 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5941 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005942 return Incompatible;
5943 }
Steve Narofff1120de2007-08-24 22:33:52 +00005944
John McCalldaa8e4e2010-11-15 09:13:47 +00005945 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005946 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005947 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005948
Steve Narofff1120de2007-08-24 22:33:52 +00005949 // C99 6.5.16.1p2: The value of the right operand is converted to the
5950 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005951 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5952 // so that we can use references in built-in functions even in C.
5953 // The getNonReferenceType() call makes sure that the resulting expression
5954 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005955 if (result != Incompatible && RHS.get()->getType() != LHSType)
5956 RHS = ImpCastExprToType(RHS.take(),
5957 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005958 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005959}
5960
Richard Trieuf7720da2011-09-06 20:40:12 +00005961QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5962 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005963 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005964 << LHS.get()->getType() << RHS.get()->getType()
5965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005966 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005967}
5968
Richard Trieu08062aa2011-09-06 21:01:04 +00005969QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005970 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005971 if (!IsCompAssign) {
5972 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5973 if (LHS.isInvalid())
5974 return QualType();
5975 }
5976 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5977 if (RHS.isInvalid())
5978 return QualType();
5979
Mike Stumpeed9cac2009-02-19 03:04:26 +00005980 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005981 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005982 QualType LHSType =
5983 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5984 QualType RHSType =
5985 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005986
Nate Begemanbe2341d2008-07-14 18:02:46 +00005987 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005988 if (LHSType == RHSType)
5989 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005990
Douglas Gregor255210e2010-08-06 10:14:59 +00005991 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005992 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5993 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5994 if (LHSType->isExtVectorType()) {
5995 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5996 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005997 }
5998
Richard Trieuccd891a2011-09-09 01:45:06 +00005999 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006000 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6001 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006002 }
6003
David Blaikie4e4d0842012-03-11 07:00:24 +00006004 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006005 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006006 // If we are allowing lax vector conversions, and LHS and RHS are both
6007 // vectors, the total size only needs to be the same. This is a
6008 // bitcast; no bits are changed but the result type is different.
6009 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006010 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6011 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006012 }
6013
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006014 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6015 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6016 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006017 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006018 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006019 std::swap(RHS, LHS);
6020 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006021 }
Mike Stump1eb44332009-09-09 15:08:12 +00006022
Nate Begemandde25982009-06-28 19:12:57 +00006023 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006024 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006025 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006026 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6027 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006028 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006029 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006030 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006031 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6032 if (swapped) std::swap(RHS, LHS);
6033 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006034 }
6035 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006036 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6037 RHSType->isRealFloatingType()) {
6038 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006039 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006040 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006041 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006042 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6043 if (swapped) std::swap(RHS, LHS);
6044 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006045 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006046 }
6047 }
Mike Stump1eb44332009-09-09 15:08:12 +00006048
Nate Begemandde25982009-06-28 19:12:57 +00006049 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006050 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006051 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006052 << LHS.get()->getType() << RHS.get()->getType()
6053 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006054 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006055}
6056
Richard Trieu481037f2011-09-16 00:53:10 +00006057// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6058// expression. These are mainly cases where the null pointer is used as an
6059// integer instead of a pointer.
6060static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6061 SourceLocation Loc, bool IsCompare) {
6062 // The canonical way to check for a GNU null is with isNullPointerConstant,
6063 // but we use a bit of a hack here for speed; this is a relatively
6064 // hot path, and isNullPointerConstant is slow.
6065 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6066 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6067
6068 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6069
6070 // Avoid analyzing cases where the result will either be invalid (and
6071 // diagnosed as such) or entirely valid and not something to warn about.
6072 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6073 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6074 return;
6075
6076 // Comparison operations would not make sense with a null pointer no matter
6077 // what the other expression is.
6078 if (!IsCompare) {
6079 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6080 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6081 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6082 return;
6083 }
6084
6085 // The rest of the operations only make sense with a null pointer
6086 // if the other expression is a pointer.
6087 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6088 NonNullType->canDecayToPointerType())
6089 return;
6090
6091 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6092 << LHSNull /* LHS is NULL */ << NonNullType
6093 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6094}
6095
Richard Trieu08062aa2011-09-06 21:01:04 +00006096QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006097 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006098 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006099 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6100
Richard Trieu08062aa2011-09-06 21:01:04 +00006101 if (LHS.get()->getType()->isVectorType() ||
6102 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006103 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006104
Richard Trieuccd891a2011-09-09 01:45:06 +00006105 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006106 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006107 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006108
David Chisnall7a7ee302012-01-16 17:27:18 +00006109
Eli Friedman860a3192012-06-16 02:19:17 +00006110 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006111 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006112
Chris Lattner7ef655a2010-01-12 21:23:57 +00006113 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006114 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006115 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006116 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006117 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6118 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006119
Chris Lattner7ef655a2010-01-12 21:23:57 +00006120 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006121}
6122
Chris Lattner7ef655a2010-01-12 21:23:57 +00006123QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006124 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006125 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6126
Richard Trieu08062aa2011-09-06 21:01:04 +00006127 if (LHS.get()->getType()->isVectorType() ||
6128 RHS.get()->getType()->isVectorType()) {
6129 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6130 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006131 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006132 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006133 }
Steve Naroff90045e82007-07-13 23:32:42 +00006134
Richard Trieuccd891a2011-09-09 01:45:06 +00006135 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006136 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006137 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006138
Eli Friedman860a3192012-06-16 02:19:17 +00006139 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006140 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006141
Chris Lattner7ef655a2010-01-12 21:23:57 +00006142 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006143 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006144 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006145 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6146 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006147
Chris Lattner7ef655a2010-01-12 21:23:57 +00006148 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006149}
6150
Chandler Carruth13b21be2011-06-27 08:02:19 +00006151/// \brief Diagnose invalid arithmetic on two void pointers.
6152static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006153 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006154 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006155 ? diag::err_typecheck_pointer_arith_void_type
6156 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006157 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6158 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006159}
6160
6161/// \brief Diagnose invalid arithmetic on a void pointer.
6162static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6163 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006164 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006165 ? diag::err_typecheck_pointer_arith_void_type
6166 : diag::ext_gnu_void_ptr)
6167 << 0 /* one pointer */ << Pointer->getSourceRange();
6168}
6169
6170/// \brief Diagnose invalid arithmetic on two function pointers.
6171static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6172 Expr *LHS, Expr *RHS) {
6173 assert(LHS->getType()->isAnyPointerType());
6174 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006175 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006176 ? diag::err_typecheck_pointer_arith_function_type
6177 : diag::ext_gnu_ptr_func_arith)
6178 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6179 // We only show the second type if it differs from the first.
6180 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6181 RHS->getType())
6182 << RHS->getType()->getPointeeType()
6183 << LHS->getSourceRange() << RHS->getSourceRange();
6184}
6185
6186/// \brief Diagnose invalid arithmetic on a function pointer.
6187static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6188 Expr *Pointer) {
6189 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006190 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006191 ? diag::err_typecheck_pointer_arith_function_type
6192 : diag::ext_gnu_ptr_func_arith)
6193 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6194 << 0 /* one pointer, so only one type */
6195 << Pointer->getSourceRange();
6196}
6197
Richard Trieud9f19342011-09-12 18:08:02 +00006198/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006199///
6200/// \returns True if pointer has incomplete type
6201static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6202 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006203 assert(Operand->getType()->isAnyPointerType() &&
6204 !Operand->getType()->isDependentType());
6205 QualType PointeeTy = Operand->getType()->getPointeeType();
6206 return S.RequireCompleteType(Loc, PointeeTy,
6207 diag::err_typecheck_arithmetic_incomplete_type,
6208 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006209}
6210
Chandler Carruth13b21be2011-06-27 08:02:19 +00006211/// \brief Check the validity of an arithmetic pointer operand.
6212///
6213/// If the operand has pointer type, this code will check for pointer types
6214/// which are invalid in arithmetic operations. These will be diagnosed
6215/// appropriately, including whether or not the use is supported as an
6216/// extension.
6217///
6218/// \returns True when the operand is valid to use (even if as an extension).
6219static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6220 Expr *Operand) {
6221 if (!Operand->getType()->isAnyPointerType()) return true;
6222
6223 QualType PointeeTy = Operand->getType()->getPointeeType();
6224 if (PointeeTy->isVoidType()) {
6225 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006226 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006227 }
6228 if (PointeeTy->isFunctionType()) {
6229 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006230 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006231 }
6232
Richard Trieu097ecd22011-09-02 02:15:37 +00006233 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006234
6235 return true;
6236}
6237
6238/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6239/// operands.
6240///
6241/// This routine will diagnose any invalid arithmetic on pointer operands much
6242/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6243/// for emitting a single diagnostic even for operations where both LHS and RHS
6244/// are (potentially problematic) pointers.
6245///
6246/// \returns True when the operand is valid to use (even if as an extension).
6247static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006248 Expr *LHSExpr, Expr *RHSExpr) {
6249 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6250 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006251 if (!isLHSPointer && !isRHSPointer) return true;
6252
6253 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006254 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6255 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006256
6257 // Check for arithmetic on pointers to incomplete types.
6258 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6259 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6260 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006261 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6262 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6263 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006264
David Blaikie4e4d0842012-03-11 07:00:24 +00006265 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006266 }
6267
6268 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6269 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6270 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006271 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6272 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6273 RHSExpr);
6274 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006275
David Blaikie4e4d0842012-03-11 07:00:24 +00006276 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006277 }
6278
John McCall1503f0d2012-07-31 05:14:30 +00006279 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6280 return false;
6281 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6282 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006283
Chandler Carruth13b21be2011-06-27 08:02:19 +00006284 return true;
6285}
6286
Nico Weber1cb2d742012-03-02 22:01:22 +00006287/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6288/// literal.
6289static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6290 Expr *LHSExpr, Expr *RHSExpr) {
6291 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6292 Expr* IndexExpr = RHSExpr;
6293 if (!StrExpr) {
6294 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6295 IndexExpr = LHSExpr;
6296 }
6297
6298 bool IsStringPlusInt = StrExpr &&
6299 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6300 if (!IsStringPlusInt)
6301 return;
6302
6303 llvm::APSInt index;
6304 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6305 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6306 if (index.isNonNegative() &&
6307 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6308 index.isUnsigned()))
6309 return;
6310 }
6311
6312 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6313 Self.Diag(OpLoc, diag::warn_string_plus_int)
6314 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6315
6316 // Only print a fixit for "str" + int, not for int + "str".
6317 if (IndexExpr == RHSExpr) {
6318 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6319 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6320 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6321 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6322 << FixItHint::CreateInsertion(EndLoc, "]");
6323 } else
6324 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6325}
6326
Richard Trieud9f19342011-09-12 18:08:02 +00006327/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006328static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006329 Expr *LHSExpr, Expr *RHSExpr) {
6330 assert(LHSExpr->getType()->isAnyPointerType());
6331 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006332 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006333 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6334 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006335}
6336
Chris Lattner7ef655a2010-01-12 21:23:57 +00006337QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006338 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6339 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006340 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6341
Richard Trieudef75842011-09-06 21:13:51 +00006342 if (LHS.get()->getType()->isVectorType() ||
6343 RHS.get()->getType()->isVectorType()) {
6344 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006345 if (CompLHSTy) *CompLHSTy = compType;
6346 return compType;
6347 }
Steve Naroff49b45262007-07-13 16:58:59 +00006348
Richard Trieudef75842011-09-06 21:13:51 +00006349 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6350 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006351 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006352
Nico Weber1cb2d742012-03-02 22:01:22 +00006353 // Diagnose "string literal" '+' int.
6354 if (Opc == BO_Add)
6355 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6356
Reid Spencer5f016e22007-07-11 17:01:13 +00006357 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006358 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006359 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006360 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006361 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006362
John McCall1503f0d2012-07-31 05:14:30 +00006363 // Type-checking. Ultimately the pointer's going to be in PExp;
6364 // note that we bias towards the LHS being the pointer.
6365 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006366
John McCall1503f0d2012-07-31 05:14:30 +00006367 bool isObjCPointer;
6368 if (PExp->getType()->isPointerType()) {
6369 isObjCPointer = false;
6370 } else if (PExp->getType()->isObjCObjectPointerType()) {
6371 isObjCPointer = true;
6372 } else {
6373 std::swap(PExp, IExp);
6374 if (PExp->getType()->isPointerType()) {
6375 isObjCPointer = false;
6376 } else if (PExp->getType()->isObjCObjectPointerType()) {
6377 isObjCPointer = true;
6378 } else {
6379 return InvalidOperands(Loc, LHS, RHS);
6380 }
6381 }
6382 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006383
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006384 if (!IExp->getType()->isIntegerType())
6385 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006386
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006387 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6388 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006389
John McCall1503f0d2012-07-31 05:14:30 +00006390 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006391 return QualType();
6392
6393 // Check array bounds for pointer arithemtic
6394 CheckArrayAccess(PExp, IExp);
6395
6396 if (CompLHSTy) {
6397 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6398 if (LHSTy.isNull()) {
6399 LHSTy = LHS.get()->getType();
6400 if (LHSTy->isPromotableIntegerType())
6401 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006402 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006403 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006404 }
6405
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006406 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006407}
6408
Chris Lattnereca7be62008-04-07 05:30:13 +00006409// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006410QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006411 SourceLocation Loc,
6412 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006413 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6414
Richard Trieudef75842011-09-06 21:13:51 +00006415 if (LHS.get()->getType()->isVectorType() ||
6416 RHS.get()->getType()->isVectorType()) {
6417 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006418 if (CompLHSTy) *CompLHSTy = compType;
6419 return compType;
6420 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006421
Richard Trieudef75842011-09-06 21:13:51 +00006422 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6423 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006424 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006425
Chris Lattner6e4ab612007-12-09 21:53:25 +00006426 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006427
Chris Lattner6e4ab612007-12-09 21:53:25 +00006428 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006429 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006430 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006431 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006432 }
Mike Stump1eb44332009-09-09 15:08:12 +00006433
Chris Lattner6e4ab612007-12-09 21:53:25 +00006434 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006435 if (LHS.get()->getType()->isAnyPointerType()) {
6436 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006437
Chris Lattnerb5f15622009-04-24 23:50:08 +00006438 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006439 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6440 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006441 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006442
Chris Lattner6e4ab612007-12-09 21:53:25 +00006443 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006444 if (RHS.get()->getType()->isIntegerType()) {
6445 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006446 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006447
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006448 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006449 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6450 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006451
Richard Trieudef75842011-09-06 21:13:51 +00006452 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6453 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006454 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006455
Chris Lattner6e4ab612007-12-09 21:53:25 +00006456 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006457 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006458 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006459 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006460
David Blaikie4e4d0842012-03-11 07:00:24 +00006461 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006462 // Pointee types must be the same: C++ [expr.add]
6463 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006464 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006465 }
6466 } else {
6467 // Pointee types must be compatible C99 6.5.6p3
6468 if (!Context.typesAreCompatible(
6469 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6470 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006471 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006472 return QualType();
6473 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006474 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006475
Chandler Carruth13b21be2011-06-27 08:02:19 +00006476 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006477 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006478 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006479
Richard Trieudef75842011-09-06 21:13:51 +00006480 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006481 return Context.getPointerDiffType();
6482 }
6483 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006484
Richard Trieudef75842011-09-06 21:13:51 +00006485 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006486}
6487
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006488static bool isScopedEnumerationType(QualType T) {
6489 if (const EnumType *ET = dyn_cast<EnumType>(T))
6490 return ET->getDecl()->isScoped();
6491 return false;
6492}
6493
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006494static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006495 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006496 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006497 llvm::APSInt Right;
6498 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006499 if (RHS.get()->isValueDependent() ||
6500 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006501 return;
6502
6503 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006504 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006505 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006506 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006507 return;
6508 }
6509 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006510 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006511 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006512 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006513 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006514 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006515 return;
6516 }
6517 if (Opc != BO_Shl)
6518 return;
6519
6520 // When left shifting an ICE which is signed, we can check for overflow which
6521 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6522 // integers have defined behavior modulo one more than the maximum value
6523 // representable in the result type, so never warn for those.
6524 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006525 if (LHS.get()->isValueDependent() ||
6526 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6527 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006528 return;
6529 llvm::APInt ResultBits =
6530 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6531 if (LeftBits.uge(ResultBits))
6532 return;
6533 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6534 Result = Result.shl(Right);
6535
Ted Kremenekfa821382011-06-15 00:54:52 +00006536 // Print the bit representation of the signed integer as an unsigned
6537 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006538 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006539 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6540
Chandler Carruth21206d52011-02-23 23:34:11 +00006541 // If we are only missing a sign bit, this is less likely to result in actual
6542 // bugs -- if the result is cast back to an unsigned type, it will have the
6543 // expected value. Thus we place this behind a different warning that can be
6544 // turned off separately if needed.
6545 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006546 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006547 << HexResult.str() << LHSType
6548 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006549 return;
6550 }
6551
6552 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006553 << HexResult.str() << Result.getMinSignedBits() << LHSType
6554 << Left.getBitWidth() << LHS.get()->getSourceRange()
6555 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006556}
6557
Chris Lattnereca7be62008-04-07 05:30:13 +00006558// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006559QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006560 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006561 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006562 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6563
Chris Lattnerca5eede2007-12-12 05:47:28 +00006564 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006565 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6566 !RHS.get()->getType()->hasIntegerRepresentation())
6567 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006568
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006569 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6570 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006571 if (isScopedEnumerationType(LHS.get()->getType()) ||
6572 isScopedEnumerationType(RHS.get()->getType())) {
6573 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006574 }
6575
Nate Begeman2207d792009-10-25 02:26:48 +00006576 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006577 if (LHS.get()->getType()->isVectorType() ||
6578 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006579 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006580
Chris Lattnerca5eede2007-12-12 05:47:28 +00006581 // Shifts don't perform usual arithmetic conversions, they just do integer
6582 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006583
John McCall1bc80af2010-12-16 19:28:59 +00006584 // For the LHS, do usual unary conversions, but then reset them away
6585 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006586 ExprResult OldLHS = LHS;
6587 LHS = UsualUnaryConversions(LHS.take());
6588 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006589 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006590 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006591 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006592
6593 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006594 RHS = UsualUnaryConversions(RHS.take());
6595 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006596 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006597
Ryan Flynnd0439682009-08-07 16:20:20 +00006598 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006599 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006600
Chris Lattnerca5eede2007-12-12 05:47:28 +00006601 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006602 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006603}
6604
Chandler Carruth99919472010-07-10 12:30:03 +00006605static bool IsWithinTemplateSpecialization(Decl *D) {
6606 if (DeclContext *DC = D->getDeclContext()) {
6607 if (isa<ClassTemplateSpecializationDecl>(DC))
6608 return true;
6609 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6610 return FD->isFunctionTemplateSpecialization();
6611 }
6612 return false;
6613}
6614
Richard Trieue648ac32011-09-02 03:48:46 +00006615/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006616static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6617 ExprResult &RHS) {
6618 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6619 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006620
6621 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6622 if (!LHSEnumType)
6623 return;
6624 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6625 if (!RHSEnumType)
6626 return;
6627
6628 // Ignore anonymous enums.
6629 if (!LHSEnumType->getDecl()->getIdentifier())
6630 return;
6631 if (!RHSEnumType->getDecl()->getIdentifier())
6632 return;
6633
6634 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6635 return;
6636
6637 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6638 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006639 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006640}
6641
Richard Trieu7be1be02011-09-02 02:55:45 +00006642/// \brief Diagnose bad pointer comparisons.
6643static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006644 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006645 bool IsError) {
6646 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006647 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006648 << LHS.get()->getType() << RHS.get()->getType()
6649 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006650}
6651
6652/// \brief Returns false if the pointers are converted to a composite type,
6653/// true otherwise.
6654static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006655 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006656 // C++ [expr.rel]p2:
6657 // [...] Pointer conversions (4.10) and qualification
6658 // conversions (4.4) are performed on pointer operands (or on
6659 // a pointer operand and a null pointer constant) to bring
6660 // them to their composite pointer type. [...]
6661 //
6662 // C++ [expr.eq]p1 uses the same notion for (in)equality
6663 // comparisons of pointers.
6664
6665 // C++ [expr.eq]p2:
6666 // In addition, pointers to members can be compared, or a pointer to
6667 // member and a null pointer constant. Pointer to member conversions
6668 // (4.11) and qualification conversions (4.4) are performed to bring
6669 // them to a common type. If one operand is a null pointer constant,
6670 // the common type is the type of the other operand. Otherwise, the
6671 // common type is a pointer to member type similar (4.4) to the type
6672 // of one of the operands, with a cv-qualification signature (4.4)
6673 // that is the union of the cv-qualification signatures of the operand
6674 // types.
6675
Richard Trieuba261492011-09-06 21:27:33 +00006676 QualType LHSType = LHS.get()->getType();
6677 QualType RHSType = RHS.get()->getType();
6678 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6679 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006680
6681 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006682 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006683 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006684 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006685 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006686 return true;
6687 }
6688
6689 if (NonStandardCompositeType)
6690 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006691 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6692 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006693
Richard Trieuba261492011-09-06 21:27:33 +00006694 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6695 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006696 return false;
6697}
6698
6699static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006700 ExprResult &LHS,
6701 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006702 bool IsError) {
6703 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6704 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006705 << LHS.get()->getType() << RHS.get()->getType()
6706 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006707}
6708
Jordan Rose9f63a452012-06-08 21:14:25 +00006709static bool isObjCObjectLiteral(ExprResult &E) {
6710 switch (E.get()->getStmtClass()) {
6711 case Stmt::ObjCArrayLiteralClass:
6712 case Stmt::ObjCDictionaryLiteralClass:
6713 case Stmt::ObjCStringLiteralClass:
6714 case Stmt::ObjCBoxedExprClass:
6715 return true;
6716 default:
6717 // Note that ObjCBoolLiteral is NOT an object literal!
6718 return false;
6719 }
6720}
6721
Jordan Rose8d872ca2012-07-17 17:46:40 +00006722static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6723 // Get the LHS object's interface type.
6724 QualType Type = LHS->getType();
6725 QualType InterfaceType;
6726 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6727 InterfaceType = PTy->getPointeeType();
6728 if (const ObjCObjectType *iQFaceTy =
6729 InterfaceType->getAsObjCQualifiedInterfaceType())
6730 InterfaceType = iQFaceTy->getBaseType();
6731 } else {
6732 // If this is not actually an Objective-C object, bail out.
6733 return false;
6734 }
6735
6736 // If the RHS isn't an Objective-C object, bail out.
6737 if (!RHS->getType()->isObjCObjectPointerType())
6738 return false;
6739
6740 // Try to find the -isEqual: method.
6741 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6742 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6743 InterfaceType,
6744 /*instance=*/true);
6745 if (!Method) {
6746 if (Type->isObjCIdType()) {
6747 // For 'id', just check the global pool.
6748 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6749 /*receiverId=*/true,
6750 /*warn=*/false);
6751 } else {
6752 // Check protocols.
6753 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6754 cast<ObjCObjectPointerType>(Type),
6755 /*instance=*/true);
6756 }
6757 }
6758
6759 if (!Method)
6760 return false;
6761
6762 QualType T = Method->param_begin()[0]->getType();
6763 if (!T->isObjCObjectPointerType())
6764 return false;
6765
6766 QualType R = Method->getResultType();
6767 if (!R->isScalarType())
6768 return false;
6769
6770 return true;
6771}
6772
6773static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6774 ExprResult &LHS, ExprResult &RHS,
6775 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006776 Expr *Literal;
6777 Expr *Other;
6778 if (isObjCObjectLiteral(LHS)) {
6779 Literal = LHS.get();
6780 Other = RHS.get();
6781 } else {
6782 Literal = RHS.get();
6783 Other = LHS.get();
6784 }
6785
6786 // Don't warn on comparisons against nil.
6787 Other = Other->IgnoreParenCasts();
6788 if (Other->isNullPointerConstant(S.getASTContext(),
6789 Expr::NPC_ValueDependentIsNotNull))
6790 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006791
Jordan Roseeec207f2012-07-17 17:46:44 +00006792 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006793 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006794 enum {
6795 LK_Array,
6796 LK_Dictionary,
6797 LK_Numeric,
6798 LK_Boxed,
6799 LK_String
6800 } LiteralKind;
6801
Jordan Rose9f63a452012-06-08 21:14:25 +00006802 switch (Literal->getStmtClass()) {
6803 case Stmt::ObjCStringLiteralClass:
6804 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006805 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006806 break;
6807 case Stmt::ObjCArrayLiteralClass:
6808 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006809 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006810 break;
6811 case Stmt::ObjCDictionaryLiteralClass:
6812 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006813 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006814 break;
6815 case Stmt::ObjCBoxedExprClass: {
6816 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6817 switch (Inner->getStmtClass()) {
6818 case Stmt::IntegerLiteralClass:
6819 case Stmt::FloatingLiteralClass:
6820 case Stmt::CharacterLiteralClass:
6821 case Stmt::ObjCBoolLiteralExprClass:
6822 case Stmt::CXXBoolLiteralExprClass:
6823 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006824 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006825 break;
6826 case Stmt::ImplicitCastExprClass: {
6827 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6828 // Boolean literals can be represented by implicit casts.
6829 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006830 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006831 break;
6832 }
6833 // FALLTHROUGH
6834 }
6835 default:
6836 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006837 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006838 break;
6839 }
6840 break;
6841 }
6842 default:
6843 llvm_unreachable("Unknown Objective-C object literal kind");
6844 }
6845
Jordan Roseeec207f2012-07-17 17:46:44 +00006846 if (LiteralKind == LK_String)
6847 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6848 << Literal->getSourceRange();
6849 else
6850 S.Diag(Loc, diag::warn_objc_literal_comparison)
6851 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006852
Jordan Rose8d872ca2012-07-17 17:46:40 +00006853 if (BinaryOperator::isEqualityOp(Opc) &&
6854 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6855 SourceLocation Start = LHS.get()->getLocStart();
6856 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6857 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006858
Jordan Rose8d872ca2012-07-17 17:46:40 +00006859 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6860 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6861 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6862 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006863 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006864}
6865
Douglas Gregor0c6db942009-05-04 06:07:12 +00006866// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006867QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006868 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006869 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006870 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6871
John McCall2de56d12010-08-25 11:45:40 +00006872 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006873
Chris Lattner02dd4b12009-12-05 05:40:13 +00006874 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006875 if (LHS.get()->getType()->isVectorType() ||
6876 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006877 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006878
Richard Trieuf1775fb2011-09-06 21:43:51 +00006879 QualType LHSType = LHS.get()->getType();
6880 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006881
Richard Trieuf1775fb2011-09-06 21:43:51 +00006882 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6883 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006884
Richard Trieuf1775fb2011-09-06 21:43:51 +00006885 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006886
Richard Trieuf1775fb2011-09-06 21:43:51 +00006887 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006888 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006889 !LHS.get()->getLocStart().isMacroID() &&
6890 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006891 // For non-floating point types, check for self-comparisons of the form
6892 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6893 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006894 //
6895 // NOTE: Don't warn about comparison expressions resulting from macro
6896 // expansion. Also don't warn about comparisons which are only self
6897 // comparisons within a template specialization. The warnings should catch
6898 // obvious cases in the definition of the template anyways. The idea is to
6899 // warn when the typed comparison operator will always evaluate to the same
6900 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006901 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006902 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006903 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006904 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006905 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006906 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006907 << (Opc == BO_EQ
6908 || Opc == BO_LE
6909 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006910 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006911 !DRL->getDecl()->getType()->isReferenceType() &&
6912 !DRR->getDecl()->getType()->isReferenceType()) {
6913 // what is it always going to eval to?
6914 char always_evals_to;
6915 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006916 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006917 always_evals_to = 0; // false
6918 break;
John McCall2de56d12010-08-25 11:45:40 +00006919 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006920 always_evals_to = 1; // true
6921 break;
6922 default:
6923 // best we can say is 'a constant'
6924 always_evals_to = 2; // e.g. array1 <= array2
6925 break;
6926 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006927 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006928 << 1 // array
6929 << always_evals_to);
6930 }
6931 }
Chandler Carruth99919472010-07-10 12:30:03 +00006932 }
Mike Stump1eb44332009-09-09 15:08:12 +00006933
Chris Lattner55660a72009-03-08 19:39:53 +00006934 if (isa<CastExpr>(LHSStripped))
6935 LHSStripped = LHSStripped->IgnoreParenCasts();
6936 if (isa<CastExpr>(RHSStripped))
6937 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006938
Chris Lattner55660a72009-03-08 19:39:53 +00006939 // Warn about comparisons against a string constant (unless the other
6940 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006941 Expr *literalString = 0;
6942 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006943 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006944 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006945 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006946 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006947 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006948 } else if ((isa<StringLiteral>(RHSStripped) ||
6949 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006950 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006951 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006952 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006953 literalStringStripped = RHSStripped;
6954 }
6955
6956 if (literalString) {
6957 std::string resultComparison;
6958 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006959 case BO_LT: resultComparison = ") < 0"; break;
6960 case BO_GT: resultComparison = ") > 0"; break;
6961 case BO_LE: resultComparison = ") <= 0"; break;
6962 case BO_GE: resultComparison = ") >= 0"; break;
6963 case BO_EQ: resultComparison = ") == 0"; break;
6964 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006965 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006966 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006967
Ted Kremenek351ba912011-02-23 01:52:04 +00006968 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006969 PDiag(diag::warn_stringcompare)
6970 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006971 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006972 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006973 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006974
Douglas Gregord64fdd02010-06-08 19:50:34 +00006975 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006976 if (LHS.get()->getType()->isArithmeticType() &&
6977 RHS.get()->getType()->isArithmeticType()) {
6978 UsualArithmeticConversions(LHS, RHS);
6979 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006980 return QualType();
6981 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006982 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006983 LHS = UsualUnaryConversions(LHS.take());
6984 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006985 return QualType();
6986
Richard Trieuf1775fb2011-09-06 21:43:51 +00006987 RHS = UsualUnaryConversions(RHS.take());
6988 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006989 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006990 }
6991
Richard Trieuf1775fb2011-09-06 21:43:51 +00006992 LHSType = LHS.get()->getType();
6993 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006994
Douglas Gregor447b69e2008-11-19 03:25:36 +00006995 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006996 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006997
Richard Trieuccd891a2011-09-09 01:45:06 +00006998 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006999 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007000 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007001 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007002 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007003 if (LHSType->hasFloatingRepresentation())
7004 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007005
Richard Trieuf1775fb2011-09-06 21:43:51 +00007006 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007007 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007008 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007009
Richard Trieuf1775fb2011-09-06 21:43:51 +00007010 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007011 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007012 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007013 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007014
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007015 // All of the following pointer-related warnings are GCC extensions, except
7016 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007017 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007018 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007019 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007020 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007021 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007022
David Blaikie4e4d0842012-03-11 07:00:24 +00007023 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007024 if (LCanPointeeTy == RCanPointeeTy)
7025 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007026 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007027 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7028 // Valid unless comparison between non-null pointer and function pointer
7029 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007030 // In a SFINAE context, we treat this as a hard error to maintain
7031 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007032 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7033 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007034 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007035 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007036
7037 if (isSFINAEContext())
7038 return QualType();
7039
Richard Trieuf1775fb2011-09-06 21:43:51 +00007040 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007041 return ResultTy;
7042 }
7043 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007044
Richard Trieuf1775fb2011-09-06 21:43:51 +00007045 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007046 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007047 else
7048 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007049 }
Eli Friedman3075e762009-08-23 00:27:47 +00007050 // C99 6.5.9p2 and C99 6.5.8p2
7051 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7052 RCanPointeeTy.getUnqualifiedType())) {
7053 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007054 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007055 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007056 << LHSType << RHSType << LHS.get()->getSourceRange()
7057 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007058 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007059 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007060 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7061 // Valid unless comparison between non-null pointer and function pointer
7062 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007063 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007064 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007065 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007066 } else {
7067 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007068 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007069 }
John McCall34d6f932011-03-11 04:25:25 +00007070 if (LCanPointeeTy != RCanPointeeTy) {
7071 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007072 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007073 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007074 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007075 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007076 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007077 }
Mike Stump1eb44332009-09-09 15:08:12 +00007078
David Blaikie4e4d0842012-03-11 07:00:24 +00007079 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007080 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007081 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007082 return ResultTy;
7083
Mike Stump1eb44332009-09-09 15:08:12 +00007084 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007085 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007086 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007087 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007088 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007089 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7090 RHS = ImpCastExprToType(RHS.take(), LHSType,
7091 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007092 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007093 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007094 return ResultTy;
7095 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007096 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007097 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007098 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007099 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7100 LHS = ImpCastExprToType(LHS.take(), RHSType,
7101 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007102 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007103 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007104 return ResultTy;
7105 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007106
7107 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007108 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007109 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7110 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007111 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007112 else
7113 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007114 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007115
7116 // Handle scoped enumeration types specifically, since they don't promote
7117 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007118 if (LHS.get()->getType()->isEnumeralType() &&
7119 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7120 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007121 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007122 }
Mike Stump1eb44332009-09-09 15:08:12 +00007123
Steve Naroff1c7d0672008-09-04 15:10:53 +00007124 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007125 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007126 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007127 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7128 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007129
Steve Naroff1c7d0672008-09-04 15:10:53 +00007130 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007131 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007132 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007133 << LHSType << RHSType << LHS.get()->getSourceRange()
7134 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007135 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007136 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007137 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007138 }
John Wiegley429bb272011-04-08 18:41:53 +00007139
Steve Naroff59f53942008-09-28 01:11:11 +00007140 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007141 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007142 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7143 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007144 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007145 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007146 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007147 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007148 ->getPointeeType()->isVoidType())))
7149 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007150 << LHSType << RHSType << LHS.get()->getSourceRange()
7151 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007152 }
John McCall34d6f932011-03-11 04:25:25 +00007153 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007154 LHS = ImpCastExprToType(LHS.take(), RHSType,
7155 RHSType->isPointerType() ? CK_BitCast
7156 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007157 else
John McCall1d9b3b22011-09-09 05:25:32 +00007158 RHS = ImpCastExprToType(RHS.take(), LHSType,
7159 LHSType->isPointerType() ? CK_BitCast
7160 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007161 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007162 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007163
Richard Trieuf1775fb2011-09-06 21:43:51 +00007164 if (LHSType->isObjCObjectPointerType() ||
7165 RHSType->isObjCObjectPointerType()) {
7166 const PointerType *LPT = LHSType->getAs<PointerType>();
7167 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007168 if (LPT || RPT) {
7169 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7170 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007171
Steve Naroffa8069f12008-11-17 19:49:16 +00007172 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007173 !Context.typesAreCompatible(LHSType, RHSType)) {
7174 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007175 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007176 }
John McCall34d6f932011-03-11 04:25:25 +00007177 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007178 LHS = ImpCastExprToType(LHS.take(), RHSType,
7179 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007180 else
John McCall1d9b3b22011-09-09 05:25:32 +00007181 RHS = ImpCastExprToType(RHS.take(), LHSType,
7182 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007183 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007184 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007185 if (LHSType->isObjCObjectPointerType() &&
7186 RHSType->isObjCObjectPointerType()) {
7187 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7188 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007189 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007190 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007191 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007192
John McCall34d6f932011-03-11 04:25:25 +00007193 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007194 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007195 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007196 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007197 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007198 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007199 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007200 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7201 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007202 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007203 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00007204 if ((LHSIsNull && LHSType->isIntegerType()) ||
7205 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007206 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007207 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007208 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007209 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007210 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007211 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7212 isError = true;
7213 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007214 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007215
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007216 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007217 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007218 << LHSType << RHSType << LHS.get()->getSourceRange()
7219 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007220 if (isError)
7221 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007222 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007223
Richard Trieuf1775fb2011-09-06 21:43:51 +00007224 if (LHSType->isIntegerType())
7225 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007226 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007227 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007228 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007229 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007230 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007231 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007232
Steve Naroff39218df2008-09-04 16:56:14 +00007233 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007234 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007235 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7236 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007237 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007238 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007239 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007240 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7241 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007242 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007243 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007244
Richard Trieuf1775fb2011-09-06 21:43:51 +00007245 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007246}
7247
Tanya Lattner4f692c22012-01-16 21:02:28 +00007248
7249// Return a signed type that is of identical size and number of elements.
7250// For floating point vectors, return an integer type of identical size
7251// and number of elements.
7252QualType Sema::GetSignedVectorType(QualType V) {
7253 const VectorType *VTy = V->getAs<VectorType>();
7254 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7255 if (TypeSize == Context.getTypeSize(Context.CharTy))
7256 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7257 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7258 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7259 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7260 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7261 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7262 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7263 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7264 "Unhandled vector element size in vector compare");
7265 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7266}
7267
Nate Begemanbe2341d2008-07-14 18:02:46 +00007268/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007269/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007270/// like a scalar comparison, a vector comparison produces a vector of integer
7271/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007272QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007273 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007274 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007275 // Check to make sure we're operating on vectors of the same type and width,
7276 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007277 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007278 if (vType.isNull())
7279 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007280
Richard Trieu9f60dee2011-09-07 01:19:57 +00007281 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007282
Anton Yartsev7870b132011-03-27 15:36:07 +00007283 // If AltiVec, the comparison results in a numeric type, i.e.
7284 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007285 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007286 return Context.getLogicalOperationType();
7287
Nate Begemanbe2341d2008-07-14 18:02:46 +00007288 // For non-floating point types, check for self-comparisons of the form
7289 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7290 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007291 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007292 if (DeclRefExpr* DRL
7293 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7294 if (DeclRefExpr* DRR
7295 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007296 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007297 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007298 PDiag(diag::warn_comparison_always)
7299 << 0 // self-
7300 << 2 // "a constant"
7301 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007302 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007303
Nate Begemanbe2341d2008-07-14 18:02:46 +00007304 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007305 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007306 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007307 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007308 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007309
7310 // Return a signed type for the vector.
7311 return GetSignedVectorType(LHSType);
7312}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007313
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007314QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7315 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007316 // Ensure that either both operands are of the same vector type, or
7317 // one operand is of a vector type and the other is of its element type.
7318 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7319 if (vType.isNull() || vType->isFloatingType())
7320 return InvalidOperands(Loc, LHS, RHS);
7321
7322 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007323}
7324
Reid Spencer5f016e22007-07-11 17:01:13 +00007325inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007326 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007327 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7328
Richard Trieu9f60dee2011-09-07 01:19:57 +00007329 if (LHS.get()->getType()->isVectorType() ||
7330 RHS.get()->getType()->isVectorType()) {
7331 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7332 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007333 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007334
Richard Trieu9f60dee2011-09-07 01:19:57 +00007335 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007336 }
Steve Naroff90045e82007-07-13 23:32:42 +00007337
Richard Trieu9f60dee2011-09-07 01:19:57 +00007338 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7339 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007340 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007341 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007342 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007343 LHS = LHSResult.take();
7344 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007345
Eli Friedman860a3192012-06-16 02:19:17 +00007346 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007347 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007348 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007349}
7350
7351inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007352 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007353
Tanya Lattner4f692c22012-01-16 21:02:28 +00007354 // Check vector operands differently.
7355 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7356 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7357
Chris Lattner90a8f272010-07-13 19:41:32 +00007358 // Diagnose cases where the user write a logical and/or but probably meant a
7359 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7360 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007361 if (LHS.get()->getType()->isIntegerType() &&
7362 !LHS.get()->getType()->isBooleanType() &&
7363 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007364 // Don't warn in macros or template instantiations.
7365 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007366 // If the RHS can be constant folded, and if it constant folds to something
7367 // that isn't 0 or 1 (which indicate a potential logical operation that
7368 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007369 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007370 llvm::APSInt Result;
7371 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007372 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007373 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007374 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007375 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007376 << (Opc == BO_LAnd ? "&&" : "||");
7377 // Suggest replacing the logical operator with the bitwise version
7378 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7379 << (Opc == BO_LAnd ? "&" : "|")
7380 << FixItHint::CreateReplacement(SourceRange(
7381 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007382 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007383 Opc == BO_LAnd ? "&" : "|");
7384 if (Opc == BO_LAnd)
7385 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7386 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7387 << FixItHint::CreateRemoval(
7388 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007389 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007390 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007391 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007392 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007393 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007394 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007395
David Blaikie4e4d0842012-03-11 07:00:24 +00007396 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007397 LHS = UsualUnaryConversions(LHS.take());
7398 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007399 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007400
Richard Trieu9f60dee2011-09-07 01:19:57 +00007401 RHS = UsualUnaryConversions(RHS.take());
7402 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007403 return QualType();
7404
Richard Trieu9f60dee2011-09-07 01:19:57 +00007405 if (!LHS.get()->getType()->isScalarType() ||
7406 !RHS.get()->getType()->isScalarType())
7407 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007408
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007409 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007410 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007411
John McCall75f7c0f2010-06-04 00:29:51 +00007412 // The following is safe because we only use this method for
7413 // non-overloadable operands.
7414
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007415 // C++ [expr.log.and]p1
7416 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007417 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007418 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7419 if (LHSRes.isInvalid())
7420 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007421 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007422
Richard Trieu9f60dee2011-09-07 01:19:57 +00007423 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7424 if (RHSRes.isInvalid())
7425 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007426 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007427
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007428 // C++ [expr.log.and]p2
7429 // C++ [expr.log.or]p2
7430 // The result is a bool.
7431 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007432}
7433
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007434/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7435/// is a read-only property; return true if so. A readonly property expression
7436/// depends on various declarations and thus must be treated specially.
7437///
Mike Stump1eb44332009-09-09 15:08:12 +00007438static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007439 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7440 if (!PropExpr) return false;
7441 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007442
John McCall3c3b7f92011-10-25 17:37:35 +00007443 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7444 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007445 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007446 PropExpr->getBase()->getType();
7447
John McCall3c3b7f92011-10-25 17:37:35 +00007448 if (const ObjCObjectPointerType *OPT =
7449 BaseType->getAsObjCInterfacePointerType())
7450 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7451 if (S.isPropertyReadonly(PDecl, IFace))
7452 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007453 return false;
7454}
7455
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007456static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007457 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7458 if (!ME) return false;
7459 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7460 ObjCMessageExpr *Base =
7461 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7462 if (!Base) return false;
7463 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007464}
7465
John McCall78dae242012-03-13 00:37:01 +00007466/// Is the given expression (which must be 'const') a reference to a
7467/// variable which was originally non-const, but which has become
7468/// 'const' due to being captured within a block?
7469enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7470static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7471 assert(E->isLValue() && E->getType().isConstQualified());
7472 E = E->IgnoreParens();
7473
7474 // Must be a reference to a declaration from an enclosing scope.
7475 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7476 if (!DRE) return NCCK_None;
7477 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7478
7479 // The declaration must be a variable which is not declared 'const'.
7480 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7481 if (!var) return NCCK_None;
7482 if (var->getType().isConstQualified()) return NCCK_None;
7483 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7484
7485 // Decide whether the first capture was for a block or a lambda.
7486 DeclContext *DC = S.CurContext;
7487 while (DC->getParent() != var->getDeclContext())
7488 DC = DC->getParent();
7489 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7490}
7491
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007492/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7493/// emit an error and return true. If so, return false.
7494static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007495 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007496 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007497 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007498 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007499 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7500 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007501 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7502 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007503 if (IsLV == Expr::MLV_Valid)
7504 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007505
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007506 unsigned Diag = 0;
7507 bool NeedType = false;
7508 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007509 case Expr::MLV_ConstQualified:
7510 Diag = diag::err_typecheck_assign_const;
7511
John McCall78dae242012-03-13 00:37:01 +00007512 // Use a specialized diagnostic when we're assigning to an object
7513 // from an enclosing function or block.
7514 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7515 if (NCCK == NCCK_Block)
7516 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7517 else
7518 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7519 break;
7520 }
7521
John McCall7acddac2011-06-17 06:42:21 +00007522 // In ARC, use some specialized diagnostics for occasions where we
7523 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007524 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007525 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7526 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7527 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7528
John McCall7acddac2011-06-17 06:42:21 +00007529 // Use the normal diagnostic if it's pseudo-__strong but the
7530 // user actually wrote 'const'.
7531 if (var->isARCPseudoStrong() &&
7532 (!var->getTypeSourceInfo() ||
7533 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7534 // There are two pseudo-strong cases:
7535 // - self
John McCallf85e1932011-06-15 23:02:42 +00007536 ObjCMethodDecl *method = S.getCurMethodDecl();
7537 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007538 Diag = method->isClassMethod()
7539 ? diag::err_typecheck_arc_assign_self_class_method
7540 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007541
7542 // - fast enumeration variables
7543 else
John McCallf85e1932011-06-15 23:02:42 +00007544 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007545
John McCallf85e1932011-06-15 23:02:42 +00007546 SourceRange Assign;
7547 if (Loc != OrigLoc)
7548 Assign = SourceRange(OrigLoc, OrigLoc);
7549 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7550 // We need to preserve the AST regardless, so migration tool
7551 // can do its job.
7552 return false;
7553 }
7554 }
7555 }
7556
7557 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007558 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007559 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007560 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7561 NeedType = true;
7562 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007563 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007564 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7565 NeedType = true;
7566 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007567 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007568 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7569 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007570 case Expr::MLV_Valid:
7571 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007572 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007573 case Expr::MLV_MemberFunction:
7574 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007575 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7576 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007577 case Expr::MLV_IncompleteType:
7578 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007579 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007580 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007581 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007582 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7583 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007584 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007585 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007586 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007587 case Expr::MLV_InvalidMessageExpression:
7588 Diag = diag::error_readonly_message_assignment;
7589 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007590 case Expr::MLV_SubObjCPropertySetting:
7591 Diag = diag::error_no_subobject_property_setting;
7592 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007593 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007594
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007595 SourceRange Assign;
7596 if (Loc != OrigLoc)
7597 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007598 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007599 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007600 else
Mike Stump1eb44332009-09-09 15:08:12 +00007601 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007602 return true;
7603}
7604
Nico Weber7c81b432012-07-03 02:03:06 +00007605static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7606 SourceLocation Loc,
7607 Sema &Sema) {
7608 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007609 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7610 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7611 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7612 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007613 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007614 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007615
Nico Weber7c81b432012-07-03 02:03:06 +00007616 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007617 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7618 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7619 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7620 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7621 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7622 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007623 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007624 }
7625}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007626
7627// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007628QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007629 SourceLocation Loc,
7630 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007631 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7632
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007633 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007634 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007635 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007636
Richard Trieu268942b2011-09-07 01:33:52 +00007637 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007638 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7639 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007640 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007641 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007642 Expr *RHSCheck = RHS.get();
7643
Nico Weber7c81b432012-07-03 02:03:06 +00007644 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007645
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007646 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007647 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007648 if (RHS.isInvalid())
7649 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007650 // Special case of NSObject attributes on c-style pointer types.
7651 if (ConvTy == IncompatiblePointer &&
7652 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007653 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007654 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007655 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007656 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007657
John McCallf89e55a2010-11-18 06:31:45 +00007658 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007659 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007660 Diag(Loc, diag::err_objc_object_assignment)
7661 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007662
Chris Lattner2c156472008-08-21 18:04:13 +00007663 // If the RHS is a unary plus or minus, check to see if they = and + are
7664 // right next to each other. If so, the user may have typo'd "x =+ 4"
7665 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007666 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7667 RHSCheck = ICE->getSubExpr();
7668 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007669 if ((UO->getOpcode() == UO_Plus ||
7670 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007671 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007672 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007673 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007674 // And there is a space or other character before the subexpr of the
7675 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007676 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007677 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007678 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007679 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007680 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007681 }
Chris Lattner2c156472008-08-21 18:04:13 +00007682 }
John McCallf85e1932011-06-15 23:02:42 +00007683
7684 if (ConvTy == Compatible) {
7685 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007686 checkRetainCycles(LHSExpr, RHS.get());
David Blaikie4e4d0842012-03-11 07:00:24 +00007687 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007688 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007689 }
Chris Lattner2c156472008-08-21 18:04:13 +00007690 } else {
7691 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007692 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007693 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007694
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007695 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007696 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007697 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007698
Richard Trieu268942b2011-09-07 01:33:52 +00007699 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007700
Reid Spencer5f016e22007-07-11 17:01:13 +00007701 // C99 6.5.16p3: The type of an assignment expression is the type of the
7702 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007703 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007704 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7705 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007706 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007707 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007708 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007709 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007710}
7711
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007712// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007713static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007714 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007715 LHS = S.CheckPlaceholderExpr(LHS.take());
7716 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007717 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007718 return QualType();
7719
John McCallcf2e5062010-10-12 07:14:40 +00007720 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7721 // operands, but not unary promotions.
7722 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007723
John McCallf6a16482010-12-04 03:47:34 +00007724 // So we treat the LHS as a ignored value, and in C++ we allow the
7725 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007726 LHS = S.IgnoredValueConversions(LHS.take());
7727 if (LHS.isInvalid())
7728 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007729
Eli Friedmana6115062012-05-24 00:47:05 +00007730 S.DiagnoseUnusedExprResult(LHS.get());
7731
David Blaikie4e4d0842012-03-11 07:00:24 +00007732 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007733 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7734 if (RHS.isInvalid())
7735 return QualType();
7736 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007737 S.RequireCompleteType(Loc, RHS.get()->getType(),
7738 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007739 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007740
John Wiegley429bb272011-04-08 18:41:53 +00007741 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007742}
7743
Steve Naroff49b45262007-07-13 16:58:59 +00007744/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7745/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007746static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7747 ExprValueKind &VK,
7748 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007749 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007750 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007751 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007752
Chris Lattner3528d352008-11-21 07:05:48 +00007753 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007754 // Atomic types can be used for increment / decrement where the non-atomic
7755 // versions can, so ignore the _Atomic() specifier for the purpose of
7756 // checking.
7757 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7758 ResType = ResAtomicType->getValueType();
7759
Chris Lattner3528d352008-11-21 07:05:48 +00007760 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007761
David Blaikie4e4d0842012-03-11 07:00:24 +00007762 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007763 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007764 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007765 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007766 return QualType();
7767 }
7768 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007769 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007770 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007771 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007772 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007773 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007774 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007775 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007776 } else if (ResType->isObjCObjectPointerType()) {
7777 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7778 // Otherwise, we just need a complete type.
7779 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7780 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7781 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007782 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007783 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007784 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007785 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007786 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007787 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007788 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007789 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007790 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007791 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007792 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007793 } else {
John McCall09431682010-11-18 19:01:18 +00007794 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007795 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007796 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007797 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007798 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007799 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007800 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007801 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007802 // In C++, a prefix increment is the same type as the operand. Otherwise
7803 // (in C or with postfix), the increment is the unqualified type of the
7804 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007805 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007806 VK = VK_LValue;
7807 return ResType;
7808 } else {
7809 VK = VK_RValue;
7810 return ResType.getUnqualifiedType();
7811 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007812}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007813
7814
Anders Carlsson369dee42008-02-01 07:15:58 +00007815/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007816/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007817/// where the declaration is needed for type checking. We only need to
7818/// handle cases when the expression references a function designator
7819/// or is an lvalue. Here are some examples:
7820/// - &(x) => x
7821/// - &*****f => f for f a function designator.
7822/// - &s.xx => s
7823/// - &s.zz[1].yy -> s, if zz is an array
7824/// - *(x + 1) -> x, if x is an array
7825/// - &"123"[2] -> 0
7826/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007827static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007828 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007829 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007830 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007831 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007832 // If this is an arrow operator, the address is an offset from
7833 // the base's value, so the object the base refers to is
7834 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007835 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007836 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007837 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007838 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007839 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007840 // FIXME: This code shouldn't be necessary! We should catch the implicit
7841 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007842 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7843 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7844 if (ICE->getSubExpr()->getType()->isArrayType())
7845 return getPrimaryDecl(ICE->getSubExpr());
7846 }
7847 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007848 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007849 case Stmt::UnaryOperatorClass: {
7850 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007851
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007852 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007853 case UO_Real:
7854 case UO_Imag:
7855 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007856 return getPrimaryDecl(UO->getSubExpr());
7857 default:
7858 return 0;
7859 }
7860 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007861 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007862 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007863 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007864 // If the result of an implicit cast is an l-value, we care about
7865 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007866 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007867 default:
7868 return 0;
7869 }
7870}
7871
Richard Trieu5520f232011-09-07 21:46:33 +00007872namespace {
7873 enum {
7874 AO_Bit_Field = 0,
7875 AO_Vector_Element = 1,
7876 AO_Property_Expansion = 2,
7877 AO_Register_Variable = 3,
7878 AO_No_Error = 4
7879 };
7880}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007881/// \brief Diagnose invalid operand for address of operations.
7882///
7883/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007884static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7885 Expr *E, unsigned Type) {
7886 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7887}
7888
Reid Spencer5f016e22007-07-11 17:01:13 +00007889/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007890/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007891/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007892/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007893/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007894/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007895/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007896static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007897 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007898 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7899 if (PTy->getKind() == BuiltinType::Overload) {
7900 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7901 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7902 << OrigOp.get()->getSourceRange();
7903 return QualType();
7904 }
7905
7906 return S.Context.OverloadTy;
7907 }
7908
7909 if (PTy->getKind() == BuiltinType::UnknownAny)
7910 return S.Context.UnknownAnyTy;
7911
7912 if (PTy->getKind() == BuiltinType::BoundMember) {
7913 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7914 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007915 return QualType();
7916 }
John McCall3c3b7f92011-10-25 17:37:35 +00007917
7918 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7919 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007920 }
John McCall9c72c602010-08-27 09:08:28 +00007921
John McCall3c3b7f92011-10-25 17:37:35 +00007922 if (OrigOp.get()->isTypeDependent())
7923 return S.Context.DependentTy;
7924
7925 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007926
John McCall9c72c602010-08-27 09:08:28 +00007927 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007928 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007929
David Blaikie4e4d0842012-03-11 07:00:24 +00007930 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007931 // Implement C99-only parts of addressof rules.
7932 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007933 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007934 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7935 // (assuming the deref expression is valid).
7936 return uOp->getSubExpr()->getType();
7937 }
7938 // Technically, there should be a check for array subscript
7939 // expressions here, but the result of one is always an lvalue anyway.
7940 }
John McCall5808ce42011-02-03 08:15:49 +00007941 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007942 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007943 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007944
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007945 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007946 bool sfinae = S.isSFINAEContext();
7947 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7948 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007949 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007950 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007951 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007952 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007953 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007954 } else if (lval == Expr::LV_MemberFunction) {
7955 // If it's an instance method, make a member pointer.
7956 // The expression must have exactly the form &A::foo.
7957
7958 // If the underlying expression isn't a decl ref, give up.
7959 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007960 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007961 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007962 return QualType();
7963 }
7964 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7965 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7966
7967 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007968 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007969 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007970 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007971
7972 // The method was named without a qualifier.
7973 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007974 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007975 << op->getSourceRange();
7976 }
7977
John McCall09431682010-11-18 19:01:18 +00007978 return S.Context.getMemberPointerType(op->getType(),
7979 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007980 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007981 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007982 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007983 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007984 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007985 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007986 AddressOfError = AO_Property_Expansion;
7987 } else {
7988 // FIXME: emit more specific diag...
7989 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7990 << op->getSourceRange();
7991 return QualType();
7992 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007993 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007994 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007995 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007996 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007997 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007998 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007999 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008000 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008001 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008002 // with the register storage-class specifier.
8003 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008004 // in C++ it is not error to take address of a register
8005 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008006 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008007 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008008 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008009 }
John McCallba135432009-11-21 08:51:07 +00008010 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008011 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008012 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008013 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008014 // Could be a pointer to member, though, if there is an explicit
8015 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008016 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008017 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008018 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008019 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008020 S.Diag(OpLoc,
8021 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008022 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008023 return QualType();
8024 }
Mike Stump1eb44332009-09-09 15:08:12 +00008025
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008026 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8027 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008028 return S.Context.getMemberPointerType(op->getType(),
8029 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008030 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008031 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008032 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008033 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008034 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008035
Richard Trieu5520f232011-09-07 21:46:33 +00008036 if (AddressOfError != AO_No_Error) {
8037 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8038 return QualType();
8039 }
8040
Eli Friedman441cf102009-05-16 23:27:50 +00008041 if (lval == Expr::LV_IncompleteVoidType) {
8042 // Taking the address of a void variable is technically illegal, but we
8043 // allow it in cases which are otherwise valid.
8044 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008045 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008046 }
8047
Reid Spencer5f016e22007-07-11 17:01:13 +00008048 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008049 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008050 return S.Context.getObjCObjectPointerType(op->getType());
8051 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008052}
8053
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008054/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008055static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8056 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008057 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008058 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008059
John Wiegley429bb272011-04-08 18:41:53 +00008060 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8061 if (ConvResult.isInvalid())
8062 return QualType();
8063 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008064 QualType OpTy = Op->getType();
8065 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008066
8067 if (isa<CXXReinterpretCastExpr>(Op)) {
8068 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8069 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8070 Op->getSourceRange());
8071 }
8072
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008073 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8074 // is an incomplete type or void. It would be possible to warn about
8075 // dereferencing a void pointer, but it's completely well-defined, and such a
8076 // warning is unlikely to catch any mistakes.
8077 if (const PointerType *PT = OpTy->getAs<PointerType>())
8078 Result = PT->getPointeeType();
8079 else if (const ObjCObjectPointerType *OPT =
8080 OpTy->getAs<ObjCObjectPointerType>())
8081 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008082 else {
John McCallfb8721c2011-04-10 19:13:55 +00008083 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008084 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008085 if (PR.take() != Op)
8086 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008087 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008088
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008089 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008090 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008091 << OpTy << Op->getSourceRange();
8092 return QualType();
8093 }
John McCall09431682010-11-18 19:01:18 +00008094
8095 // Dereferences are usually l-values...
8096 VK = VK_LValue;
8097
8098 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008099 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008100 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008101
8102 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008103}
8104
John McCall2de56d12010-08-25 11:45:40 +00008105static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008106 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008107 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008108 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008109 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008110 case tok::periodstar: Opc = BO_PtrMemD; break;
8111 case tok::arrowstar: Opc = BO_PtrMemI; break;
8112 case tok::star: Opc = BO_Mul; break;
8113 case tok::slash: Opc = BO_Div; break;
8114 case tok::percent: Opc = BO_Rem; break;
8115 case tok::plus: Opc = BO_Add; break;
8116 case tok::minus: Opc = BO_Sub; break;
8117 case tok::lessless: Opc = BO_Shl; break;
8118 case tok::greatergreater: Opc = BO_Shr; break;
8119 case tok::lessequal: Opc = BO_LE; break;
8120 case tok::less: Opc = BO_LT; break;
8121 case tok::greaterequal: Opc = BO_GE; break;
8122 case tok::greater: Opc = BO_GT; break;
8123 case tok::exclaimequal: Opc = BO_NE; break;
8124 case tok::equalequal: Opc = BO_EQ; break;
8125 case tok::amp: Opc = BO_And; break;
8126 case tok::caret: Opc = BO_Xor; break;
8127 case tok::pipe: Opc = BO_Or; break;
8128 case tok::ampamp: Opc = BO_LAnd; break;
8129 case tok::pipepipe: Opc = BO_LOr; break;
8130 case tok::equal: Opc = BO_Assign; break;
8131 case tok::starequal: Opc = BO_MulAssign; break;
8132 case tok::slashequal: Opc = BO_DivAssign; break;
8133 case tok::percentequal: Opc = BO_RemAssign; break;
8134 case tok::plusequal: Opc = BO_AddAssign; break;
8135 case tok::minusequal: Opc = BO_SubAssign; break;
8136 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8137 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8138 case tok::ampequal: Opc = BO_AndAssign; break;
8139 case tok::caretequal: Opc = BO_XorAssign; break;
8140 case tok::pipeequal: Opc = BO_OrAssign; break;
8141 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008142 }
8143 return Opc;
8144}
8145
John McCall2de56d12010-08-25 11:45:40 +00008146static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008147 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008148 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008149 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008150 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008151 case tok::plusplus: Opc = UO_PreInc; break;
8152 case tok::minusminus: Opc = UO_PreDec; break;
8153 case tok::amp: Opc = UO_AddrOf; break;
8154 case tok::star: Opc = UO_Deref; break;
8155 case tok::plus: Opc = UO_Plus; break;
8156 case tok::minus: Opc = UO_Minus; break;
8157 case tok::tilde: Opc = UO_Not; break;
8158 case tok::exclaim: Opc = UO_LNot; break;
8159 case tok::kw___real: Opc = UO_Real; break;
8160 case tok::kw___imag: Opc = UO_Imag; break;
8161 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008162 }
8163 return Opc;
8164}
8165
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008166/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8167/// This warning is only emitted for builtin assignment operations. It is also
8168/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008169static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008170 SourceLocation OpLoc) {
8171 if (!S.ActiveTemplateInstantiations.empty())
8172 return;
8173 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8174 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008175 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8176 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8177 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8178 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8179 if (!LHSDeclRef || !RHSDeclRef ||
8180 LHSDeclRef->getLocation().isMacroID() ||
8181 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008182 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008183 const ValueDecl *LHSDecl =
8184 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8185 const ValueDecl *RHSDecl =
8186 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8187 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008188 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008189 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008190 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008191 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008192 if (RefTy->getPointeeType().isVolatileQualified())
8193 return;
8194
8195 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008196 << LHSDeclRef->getType()
8197 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008198}
8199
Douglas Gregoreaebc752008-11-06 23:29:22 +00008200/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8201/// operator @p Opc at location @c TokLoc. This routine only supports
8202/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008203ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008204 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008205 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008206 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008207 // The syntax only allows initializer lists on the RHS of assignment,
8208 // so we don't need to worry about accepting invalid code for
8209 // non-assignment operators.
8210 // C++11 5.17p9:
8211 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8212 // of x = {} is x = T().
8213 InitializationKind Kind =
8214 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8215 InitializedEntity Entity =
8216 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8217 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8218 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8219 MultiExprArg(&RHSExpr, 1));
8220 if (Init.isInvalid())
8221 return Init;
8222 RHSExpr = Init.take();
8223 }
8224
Richard Trieu78ea78b2011-09-07 01:49:20 +00008225 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008226 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008227 // The following two variables are used for compound assignment operators
8228 QualType CompLHSTy; // Type of LHS after promotions for computation
8229 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008230 ExprValueKind VK = VK_RValue;
8231 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008232
8233 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008234 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008235 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008236 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008237 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8238 VK = LHS.get()->getValueKind();
8239 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008240 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008241 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008242 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008243 break;
John McCall2de56d12010-08-25 11:45:40 +00008244 case BO_PtrMemD:
8245 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008246 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008247 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008248 break;
John McCall2de56d12010-08-25 11:45:40 +00008249 case BO_Mul:
8250 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008251 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008252 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008253 break;
John McCall2de56d12010-08-25 11:45:40 +00008254 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008255 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008256 break;
John McCall2de56d12010-08-25 11:45:40 +00008257 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008258 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008259 break;
John McCall2de56d12010-08-25 11:45:40 +00008260 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008261 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008262 break;
John McCall2de56d12010-08-25 11:45:40 +00008263 case BO_Shl:
8264 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008265 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008266 break;
John McCall2de56d12010-08-25 11:45:40 +00008267 case BO_LE:
8268 case BO_LT:
8269 case BO_GE:
8270 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008271 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008272 break;
John McCall2de56d12010-08-25 11:45:40 +00008273 case BO_EQ:
8274 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008275 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008276 break;
John McCall2de56d12010-08-25 11:45:40 +00008277 case BO_And:
8278 case BO_Xor:
8279 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008280 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008281 break;
John McCall2de56d12010-08-25 11:45:40 +00008282 case BO_LAnd:
8283 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008284 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008285 break;
John McCall2de56d12010-08-25 11:45:40 +00008286 case BO_MulAssign:
8287 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008288 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008289 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008290 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008291 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8292 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008293 break;
John McCall2de56d12010-08-25 11:45:40 +00008294 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008295 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008296 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008297 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8298 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008299 break;
John McCall2de56d12010-08-25 11:45:40 +00008300 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008301 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008302 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8303 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008304 break;
John McCall2de56d12010-08-25 11:45:40 +00008305 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008306 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8307 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8308 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008309 break;
John McCall2de56d12010-08-25 11:45:40 +00008310 case BO_ShlAssign:
8311 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008312 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008313 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008314 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8315 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008316 break;
John McCall2de56d12010-08-25 11:45:40 +00008317 case BO_AndAssign:
8318 case BO_XorAssign:
8319 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008320 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008321 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008322 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8323 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008324 break;
John McCall2de56d12010-08-25 11:45:40 +00008325 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008326 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008327 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008328 VK = RHS.get()->getValueKind();
8329 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008330 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008331 break;
8332 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008333 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008334 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008335
8336 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008337 CheckArrayAccess(LHS.get());
8338 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008339
Eli Friedmanab3a8522009-03-28 01:22:36 +00008340 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008341 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008342 ResultTy, VK, OK, OpLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00008343 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008344 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008345 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008346 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008347 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008348 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008349 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008350 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008351}
8352
Sebastian Redlaee3c932009-10-27 12:10:02 +00008353/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8354/// operators are mixed in a way that suggests that the programmer forgot that
8355/// comparison operators have higher precedence. The most typical example of
8356/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008357static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008358 SourceLocation OpLoc, Expr *LHSExpr,
8359 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008360 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008361 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8362 RHSopc = static_cast<BinOp::Opcode>(-1);
8363 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8364 LHSopc = BO->getOpcode();
8365 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8366 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008367
8368 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008369 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008370 return;
8371
8372 // Bitwise operations are sometimes used as eager logical ops.
8373 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008374 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8375 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008376 return;
8377
Richard Trieu78ea78b2011-09-07 01:49:20 +00008378 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8379 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008380 if (!isLeftComp && !isRightComp) return;
8381
Richard Trieu78ea78b2011-09-07 01:49:20 +00008382 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8383 OpLoc)
8384 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8385 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8386 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008387 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008388 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8389 RHSExpr->getLocEnd())
8390 : SourceRange(LHSExpr->getLocStart(),
8391 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008392
8393 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8394 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8395 SuggestParentheses(Self, OpLoc,
8396 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008397 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008398 SuggestParentheses(Self, OpLoc,
8399 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8400 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008401}
8402
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008403/// \brief It accepts a '&' expr that is inside a '|' one.
8404/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8405/// in parentheses.
8406static void
8407EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8408 BinaryOperator *Bop) {
8409 assert(Bop->getOpcode() == BO_And);
8410 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8411 << Bop->getSourceRange() << OpLoc;
8412 SuggestParentheses(Self, Bop->getOperatorLoc(),
8413 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8414 Bop->getSourceRange());
8415}
8416
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008417/// \brief It accepts a '&&' expr that is inside a '||' one.
8418/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8419/// in parentheses.
8420static void
8421EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008422 BinaryOperator *Bop) {
8423 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008424 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8425 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008426 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008427 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008428 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008429}
8430
8431/// \brief Returns true if the given expression can be evaluated as a constant
8432/// 'true'.
8433static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8434 bool Res;
8435 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8436}
8437
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008438/// \brief Returns true if the given expression can be evaluated as a constant
8439/// 'false'.
8440static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8441 bool Res;
8442 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8443}
8444
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008445/// \brief Look for '&&' in the left hand of a '||' expr.
8446static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008447 Expr *LHSExpr, Expr *RHSExpr) {
8448 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008449 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008450 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008451 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008452 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008453 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8454 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8455 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8456 } else if (Bop->getOpcode() == BO_LOr) {
8457 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8458 // If it's "a || b && 1 || c" we didn't warn earlier for
8459 // "a || b && 1", but warn now.
8460 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8461 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8462 }
8463 }
8464 }
8465}
8466
8467/// \brief Look for '&&' in the right hand of a '||' expr.
8468static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008469 Expr *LHSExpr, Expr *RHSExpr) {
8470 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008471 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008472 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008473 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008474 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008475 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8476 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8477 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008478 }
8479 }
8480}
8481
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008482/// \brief Look for '&' in the left or right hand of a '|' expr.
8483static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8484 Expr *OrArg) {
8485 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8486 if (Bop->getOpcode() == BO_And)
8487 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8488 }
8489}
8490
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008491/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008492/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008493static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008494 SourceLocation OpLoc, Expr *LHSExpr,
8495 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008496 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008497 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008498 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008499
8500 // Diagnose "arg1 & arg2 | arg3"
8501 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008502 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8503 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008504 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008505
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008506 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8507 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008508 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008509 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8510 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008511 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008512}
8513
Reid Spencer5f016e22007-07-11 17:01:13 +00008514// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008515ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008516 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008517 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008518 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008519 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8520 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008521
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008522 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008523 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008524
Richard Trieubefece12011-09-07 02:02:10 +00008525 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008526}
8527
John McCall3c3b7f92011-10-25 17:37:35 +00008528/// Build an overloaded binary operator expression in the given scope.
8529static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8530 BinaryOperatorKind Opc,
8531 Expr *LHS, Expr *RHS) {
8532 // Find all of the overloaded operators visible from this
8533 // point. We perform both an operator-name lookup from the local
8534 // scope and an argument-dependent lookup based on the types of
8535 // the arguments.
8536 UnresolvedSet<16> Functions;
8537 OverloadedOperatorKind OverOp
8538 = BinaryOperator::getOverloadedOperator(Opc);
8539 if (Sc && OverOp != OO_None)
8540 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8541 RHS->getType(), Functions);
8542
8543 // Build the (potentially-overloaded, potentially-dependent)
8544 // binary operation.
8545 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8546}
8547
John McCall60d7b3a2010-08-24 06:29:42 +00008548ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008549 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008550 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008551 // We want to end up calling one of checkPseudoObjectAssignment
8552 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8553 // both expressions are overloadable or either is type-dependent),
8554 // or CreateBuiltinBinOp (in any other case). We also want to get
8555 // any placeholder types out of the way.
8556
John McCall3c3b7f92011-10-25 17:37:35 +00008557 // Handle pseudo-objects in the LHS.
8558 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8559 // Assignments with a pseudo-object l-value need special analysis.
8560 if (pty->getKind() == BuiltinType::PseudoObject &&
8561 BinaryOperator::isAssignmentOp(Opc))
8562 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8563
8564 // Don't resolve overloads if the other type is overloadable.
8565 if (pty->getKind() == BuiltinType::Overload) {
8566 // We can't actually test that if we still have a placeholder,
8567 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008568 // code below are valid when the LHS is an overload set. Note
8569 // that an overload set can be dependently-typed, but it never
8570 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008571 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8572 if (resolvedRHS.isInvalid()) return ExprError();
8573 RHSExpr = resolvedRHS.take();
8574
John McCallac516502011-10-28 01:04:34 +00008575 if (RHSExpr->isTypeDependent() ||
8576 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008577 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8578 }
8579
8580 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8581 if (LHS.isInvalid()) return ExprError();
8582 LHSExpr = LHS.take();
8583 }
8584
8585 // Handle pseudo-objects in the RHS.
8586 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8587 // An overload in the RHS can potentially be resolved by the type
8588 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008589 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8590 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8591 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8592
Eli Friedman87884912012-01-17 21:27:43 +00008593 if (LHSExpr->getType()->isOverloadableType())
8594 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8595
John McCall3c3b7f92011-10-25 17:37:35 +00008596 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008597 }
John McCall3c3b7f92011-10-25 17:37:35 +00008598
8599 // Don't resolve overloads if the other type is overloadable.
8600 if (pty->getKind() == BuiltinType::Overload &&
8601 LHSExpr->getType()->isOverloadableType())
8602 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8603
8604 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8605 if (!resolvedRHS.isUsable()) return ExprError();
8606 RHSExpr = resolvedRHS.take();
8607 }
8608
David Blaikie4e4d0842012-03-11 07:00:24 +00008609 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008610 // If either expression is type-dependent, always build an
8611 // overloaded op.
8612 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8613 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008614
John McCallac516502011-10-28 01:04:34 +00008615 // Otherwise, build an overloaded op if either expression has an
8616 // overloadable type.
8617 if (LHSExpr->getType()->isOverloadableType() ||
8618 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008619 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008620 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008621
Douglas Gregoreaebc752008-11-06 23:29:22 +00008622 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008623 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008624}
8625
John McCall60d7b3a2010-08-24 06:29:42 +00008626ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008627 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008628 Expr *InputExpr) {
8629 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008630 ExprValueKind VK = VK_RValue;
8631 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008632 QualType resultType;
8633 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008634 case UO_PreInc:
8635 case UO_PreDec:
8636 case UO_PostInc:
8637 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008638 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008639 Opc == UO_PreInc ||
8640 Opc == UO_PostInc,
8641 Opc == UO_PreInc ||
8642 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008643 break;
John McCall2de56d12010-08-25 11:45:40 +00008644 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008645 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008646 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008647 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008648 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8649 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008650 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008651 }
John McCall2de56d12010-08-25 11:45:40 +00008652 case UO_Plus:
8653 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008654 Input = UsualUnaryConversions(Input.take());
8655 if (Input.isInvalid()) return ExprError();
8656 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008657 if (resultType->isDependentType())
8658 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008659 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8660 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008661 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008662 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008663 resultType->isEnumeralType())
8664 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008665 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008666 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008667 resultType->isPointerType())
8668 break;
8669
Sebastian Redl0eb23302009-01-19 00:08:26 +00008670 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008671 << resultType << Input.get()->getSourceRange());
8672
John McCall2de56d12010-08-25 11:45:40 +00008673 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008674 Input = UsualUnaryConversions(Input.take());
8675 if (Input.isInvalid()) return ExprError();
8676 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008677 if (resultType->isDependentType())
8678 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008679 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8680 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8681 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008682 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008683 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008684 else if (resultType->hasIntegerRepresentation())
8685 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008686 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008687 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008688 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008689 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008690 break;
John Wiegley429bb272011-04-08 18:41:53 +00008691
John McCall2de56d12010-08-25 11:45:40 +00008692 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008693 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008694 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8695 if (Input.isInvalid()) return ExprError();
8696 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008697
8698 // Though we still have to promote half FP to float...
8699 if (resultType->isHalfType()) {
8700 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8701 resultType = Context.FloatTy;
8702 }
8703
Sebastian Redl28507842009-02-26 14:39:58 +00008704 if (resultType->isDependentType())
8705 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008706 if (resultType->isScalarType()) {
8707 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008708 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008709 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8710 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008711 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8712 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008713 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008714 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008715 // Vector logical not returns the signed variant of the operand type.
8716 resultType = GetSignedVectorType(resultType);
8717 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008718 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008719 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008720 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008721 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008722
Reid Spencer5f016e22007-07-11 17:01:13 +00008723 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008724 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008725 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008726 break;
John McCall2de56d12010-08-25 11:45:40 +00008727 case UO_Real:
8728 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008729 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008730 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8731 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008732 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008733 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8734 if (Input.get()->getValueKind() != VK_RValue &&
8735 Input.get()->getObjectKind() == OK_Ordinary)
8736 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008737 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008738 // In C, a volatile scalar is read by __imag. In C++, it is not.
8739 Input = DefaultLvalueConversion(Input.take());
8740 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008741 break;
John McCall2de56d12010-08-25 11:45:40 +00008742 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008743 resultType = Input.get()->getType();
8744 VK = Input.get()->getValueKind();
8745 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008746 break;
8747 }
John Wiegley429bb272011-04-08 18:41:53 +00008748 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008749 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008750
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008751 // Check for array bounds violations in the operand of the UnaryOperator,
8752 // except for the '*' and '&' operators that have to be handled specially
8753 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8754 // that are explicitly defined as valid by the standard).
8755 if (Opc != UO_AddrOf && Opc != UO_Deref)
8756 CheckArrayAccess(Input.get());
8757
John Wiegley429bb272011-04-08 18:41:53 +00008758 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008759 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008760}
8761
Douglas Gregord3d08532011-12-14 21:23:13 +00008762/// \brief Determine whether the given expression is a qualified member
8763/// access expression, of a form that could be turned into a pointer to member
8764/// with the address-of operator.
8765static bool isQualifiedMemberAccess(Expr *E) {
8766 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8767 if (!DRE->getQualifier())
8768 return false;
8769
8770 ValueDecl *VD = DRE->getDecl();
8771 if (!VD->isCXXClassMember())
8772 return false;
8773
8774 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8775 return true;
8776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8777 return Method->isInstance();
8778
8779 return false;
8780 }
8781
8782 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8783 if (!ULE->getQualifier())
8784 return false;
8785
8786 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8787 DEnd = ULE->decls_end();
8788 D != DEnd; ++D) {
8789 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8790 if (Method->isInstance())
8791 return true;
8792 } else {
8793 // Overload set does not contain methods.
8794 break;
8795 }
8796 }
8797
8798 return false;
8799 }
8800
8801 return false;
8802}
8803
John McCall60d7b3a2010-08-24 06:29:42 +00008804ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008805 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008806 // First things first: handle placeholders so that the
8807 // overloaded-operator check considers the right type.
8808 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8809 // Increment and decrement of pseudo-object references.
8810 if (pty->getKind() == BuiltinType::PseudoObject &&
8811 UnaryOperator::isIncrementDecrementOp(Opc))
8812 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8813
8814 // extension is always a builtin operator.
8815 if (Opc == UO_Extension)
8816 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8817
8818 // & gets special logic for several kinds of placeholder.
8819 // The builtin code knows what to do.
8820 if (Opc == UO_AddrOf &&
8821 (pty->getKind() == BuiltinType::Overload ||
8822 pty->getKind() == BuiltinType::UnknownAny ||
8823 pty->getKind() == BuiltinType::BoundMember))
8824 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8825
8826 // Anything else needs to be handled now.
8827 ExprResult Result = CheckPlaceholderExpr(Input);
8828 if (Result.isInvalid()) return ExprError();
8829 Input = Result.take();
8830 }
8831
David Blaikie4e4d0842012-03-11 07:00:24 +00008832 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008833 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8834 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008835 // Find all of the overloaded operators visible from this
8836 // point. We perform both an operator-name lookup from the local
8837 // scope and an argument-dependent lookup based on the types of
8838 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008839 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008840 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008841 if (S && OverOp != OO_None)
8842 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8843 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008844
John McCall9ae2f072010-08-23 23:25:46 +00008845 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008846 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008847
John McCall9ae2f072010-08-23 23:25:46 +00008848 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008849}
8850
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008851// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008852ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008853 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008854 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008855}
8856
Steve Naroff1b273c42007-09-16 14:56:35 +00008857/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008858ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008859 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008860 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008861 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008862 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008863 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008864}
8865
John McCallf85e1932011-06-15 23:02:42 +00008866/// Given the last statement in a statement-expression, check whether
8867/// the result is a producing expression (like a call to an
8868/// ns_returns_retained function) and, if so, rebuild it to hoist the
8869/// release out of the full-expression. Otherwise, return null.
8870/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008871static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008872 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008873 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008874 if (!cleanups) return 0;
8875
8876 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008877 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008878 return 0;
8879
8880 // Splice out the cast. This shouldn't modify any interesting
8881 // features of the statement.
8882 Expr *producer = cast->getSubExpr();
8883 assert(producer->getType() == cast->getType());
8884 assert(producer->getValueKind() == cast->getValueKind());
8885 cleanups->setSubExpr(producer);
8886 return cleanups;
8887}
8888
John McCall73f428c2012-04-04 01:27:53 +00008889void Sema::ActOnStartStmtExpr() {
8890 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8891}
8892
8893void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008894 // Note that function is also called by TreeTransform when leaving a
8895 // StmtExpr scope without rebuilding anything.
8896
John McCall73f428c2012-04-04 01:27:53 +00008897 DiscardCleanupsInEvaluationContext();
8898 PopExpressionEvaluationContext();
8899}
8900
John McCall60d7b3a2010-08-24 06:29:42 +00008901ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008902Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008903 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008904 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8905 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8906
John McCall73f428c2012-04-04 01:27:53 +00008907 if (hasAnyUnrecoverableErrorsInThisFunction())
8908 DiscardCleanupsInEvaluationContext();
8909 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8910 PopExpressionEvaluationContext();
8911
Douglas Gregordd8f5692010-03-10 04:54:39 +00008912 bool isFileScope
8913 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008914 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008915 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008916
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008917 // FIXME: there are a variety of strange constraints to enforce here, for
8918 // example, it is not possible to goto into a stmt expression apparently.
8919 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008920
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008921 // If there are sub stmts in the compound stmt, take the type of the last one
8922 // as the type of the stmtexpr.
8923 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008924 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008925 if (!Compound->body_empty()) {
8926 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008927 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008928 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008929 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8930 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008931 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008932 }
John McCallf85e1932011-06-15 23:02:42 +00008933
John Wiegley429bb272011-04-08 18:41:53 +00008934 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008935 // Do function/array conversion on the last expression, but not
8936 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008937 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8938 if (LastExpr.isInvalid())
8939 return ExprError();
8940 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008941
John Wiegley429bb272011-04-08 18:41:53 +00008942 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008943 // In ARC, if the final expression ends in a consume, splice
8944 // the consume out and bind it later. In the alternate case
8945 // (when dealing with a retainable type), the result
8946 // initialization will create a produce. In both cases the
8947 // result will be +1, and we'll need to balance that out with
8948 // a bind.
8949 if (Expr *rebuiltLastStmt
8950 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8951 LastExpr = rebuiltLastStmt;
8952 } else {
8953 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008954 InitializedEntity::InitializeResult(LPLoc,
8955 Ty,
8956 false),
8957 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008958 LastExpr);
8959 }
8960
John Wiegley429bb272011-04-08 18:41:53 +00008961 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008962 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008963 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008964 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008965 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008966 else
John Wiegley429bb272011-04-08 18:41:53 +00008967 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008968 StmtExprMayBindToTemp = true;
8969 }
8970 }
8971 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008972 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008973
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008974 // FIXME: Check that expression type is complete/non-abstract; statement
8975 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008976 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8977 if (StmtExprMayBindToTemp)
8978 return MaybeBindToTemporary(ResStmtExpr);
8979 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008980}
Steve Naroffd34e9152007-08-01 22:05:33 +00008981
John McCall60d7b3a2010-08-24 06:29:42 +00008982ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008983 TypeSourceInfo *TInfo,
8984 OffsetOfComponent *CompPtr,
8985 unsigned NumComponents,
8986 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008987 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008988 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008989 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008990
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008991 // We must have at least one component that refers to the type, and the first
8992 // one is known to be a field designator. Verify that the ArgTy represents
8993 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008994 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008995 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8996 << ArgTy << TypeRange);
8997
8998 // Type must be complete per C99 7.17p3 because a declaring a variable
8999 // with an incomplete type would be ill-formed.
9000 if (!Dependent
9001 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009002 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009003 return ExprError();
9004
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009005 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9006 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009007 // FIXME: This diagnostic isn't actually visible because the location is in
9008 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009009 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009010 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9011 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009012
9013 bool DidWarnAboutNonPOD = false;
9014 QualType CurrentType = ArgTy;
9015 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009016 SmallVector<OffsetOfNode, 4> Comps;
9017 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009018 for (unsigned i = 0; i != NumComponents; ++i) {
9019 const OffsetOfComponent &OC = CompPtr[i];
9020 if (OC.isBrackets) {
9021 // Offset of an array sub-field. TODO: Should we allow vector elements?
9022 if (!CurrentType->isDependentType()) {
9023 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9024 if(!AT)
9025 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9026 << CurrentType);
9027 CurrentType = AT->getElementType();
9028 } else
9029 CurrentType = Context.DependentTy;
9030
Richard Smithea011432011-10-17 23:29:39 +00009031 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9032 if (IdxRval.isInvalid())
9033 return ExprError();
9034 Expr *Idx = IdxRval.take();
9035
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009036 // The expression must be an integral expression.
9037 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009038 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9039 !Idx->getType()->isIntegerType())
9040 return ExprError(Diag(Idx->getLocStart(),
9041 diag::err_typecheck_subscript_not_integer)
9042 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009043
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009044 // Record this array index.
9045 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009046 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009047 continue;
9048 }
9049
9050 // Offset of a field.
9051 if (CurrentType->isDependentType()) {
9052 // We have the offset of a field, but we can't look into the dependent
9053 // type. Just record the identifier of the field.
9054 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9055 CurrentType = Context.DependentTy;
9056 continue;
9057 }
9058
9059 // We need to have a complete type to look into.
9060 if (RequireCompleteType(OC.LocStart, CurrentType,
9061 diag::err_offsetof_incomplete_type))
9062 return ExprError();
9063
9064 // Look for the designated field.
9065 const RecordType *RC = CurrentType->getAs<RecordType>();
9066 if (!RC)
9067 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9068 << CurrentType);
9069 RecordDecl *RD = RC->getDecl();
9070
9071 // C++ [lib.support.types]p5:
9072 // The macro offsetof accepts a restricted set of type arguments in this
9073 // International Standard. type shall be a POD structure or a POD union
9074 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009075 // C++11 [support.types]p4:
9076 // If type is not a standard-layout class (Clause 9), the results are
9077 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009078 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009079 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9080 unsigned DiagID =
9081 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9082 : diag::warn_offsetof_non_pod_type;
9083
9084 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009085 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009086 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009087 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9088 << CurrentType))
9089 DidWarnAboutNonPOD = true;
9090 }
9091
9092 // Look for the field.
9093 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9094 LookupQualifiedName(R, RD);
9095 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009096 IndirectFieldDecl *IndirectMemberDecl = 0;
9097 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009098 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009099 MemberDecl = IndirectMemberDecl->getAnonField();
9100 }
9101
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009102 if (!MemberDecl)
9103 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9104 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9105 OC.LocEnd));
9106
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009107 // C99 7.17p3:
9108 // (If the specified member is a bit-field, the behavior is undefined.)
9109 //
9110 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009111 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009112 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9113 << MemberDecl->getDeclName()
9114 << SourceRange(BuiltinLoc, RParenLoc);
9115 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9116 return ExprError();
9117 }
Eli Friedman19410a72010-08-05 10:11:36 +00009118
9119 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009120 if (IndirectMemberDecl)
9121 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009122
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009123 // If the member was found in a base class, introduce OffsetOfNodes for
9124 // the base class indirections.
9125 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9126 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009127 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009128 CXXBasePath &Path = Paths.front();
9129 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9130 B != BEnd; ++B)
9131 Comps.push_back(OffsetOfNode(B->Base));
9132 }
Eli Friedman19410a72010-08-05 10:11:36 +00009133
Francois Pichet87c2e122010-11-21 06:08:52 +00009134 if (IndirectMemberDecl) {
9135 for (IndirectFieldDecl::chain_iterator FI =
9136 IndirectMemberDecl->chain_begin(),
9137 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9138 assert(isa<FieldDecl>(*FI));
9139 Comps.push_back(OffsetOfNode(OC.LocStart,
9140 cast<FieldDecl>(*FI), OC.LocEnd));
9141 }
9142 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009143 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009144
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009145 CurrentType = MemberDecl->getType().getNonReferenceType();
9146 }
9147
9148 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9149 TInfo, Comps.data(), Comps.size(),
9150 Exprs.data(), Exprs.size(), RParenLoc));
9151}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009152
John McCall60d7b3a2010-08-24 06:29:42 +00009153ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009154 SourceLocation BuiltinLoc,
9155 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009156 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009157 OffsetOfComponent *CompPtr,
9158 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009159 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009160
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009161 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009162 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009163 if (ArgTy.isNull())
9164 return ExprError();
9165
Eli Friedman5a15dc12010-08-05 10:15:45 +00009166 if (!ArgTInfo)
9167 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9168
9169 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009170 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009171}
9172
9173
John McCall60d7b3a2010-08-24 06:29:42 +00009174ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009175 Expr *CondExpr,
9176 Expr *LHSExpr, Expr *RHSExpr,
9177 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009178 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9179
John McCallf89e55a2010-11-18 06:31:45 +00009180 ExprValueKind VK = VK_RValue;
9181 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009182 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009183 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009184 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009185 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009186 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009187 } else {
9188 // The conditional expression is required to be a constant expression.
9189 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009190 ExprResult CondICE
9191 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9192 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009193 if (CondICE.isInvalid())
9194 return ExprError();
9195 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009196
Sebastian Redl28507842009-02-26 14:39:58 +00009197 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009198 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9199
9200 resType = ActiveExpr->getType();
9201 ValueDependent = ActiveExpr->isValueDependent();
9202 VK = ActiveExpr->getValueKind();
9203 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009204 }
9205
Sebastian Redlf53597f2009-03-15 17:47:39 +00009206 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009207 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009208 resType->isDependentType(),
9209 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009210}
9211
Steve Naroff4eb206b2008-09-03 18:15:37 +00009212//===----------------------------------------------------------------------===//
9213// Clang Extensions.
9214//===----------------------------------------------------------------------===//
9215
9216/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009217void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009218 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009219 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009220 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009221 if (CurScope)
9222 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009223 else
9224 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009225
Eli Friedman84b007f2012-01-26 03:00:14 +00009226 getCurBlock()->HasImplicitReturnType = true;
9227
John McCall538773c2011-11-11 03:19:12 +00009228 // Enter a new evaluation context to insulate the block from any
9229 // cleanups from the enclosing full-expression.
9230 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009231}
9232
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009233void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9234 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009235 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009236 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009237 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009238
John McCallbf1a0282010-06-04 23:28:52 +00009239 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009240 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009241
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009242 // FIXME: We should allow unexpanded parameter packs here, but that would,
9243 // in turn, make the block expression contain unexpanded parameter packs.
9244 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9245 // Drop the parameters.
9246 FunctionProtoType::ExtProtoInfo EPI;
9247 EPI.HasTrailingReturn = false;
9248 EPI.TypeQuals |= DeclSpec::TQ_const;
9249 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9250 EPI);
9251 Sig = Context.getTrivialTypeSourceInfo(T);
9252 }
9253
John McCall711c52b2011-01-05 12:14:39 +00009254 // GetTypeForDeclarator always produces a function type for a block
9255 // literal signature. Furthermore, it is always a FunctionProtoType
9256 // unless the function was written with a typedef.
9257 assert(T->isFunctionType() &&
9258 "GetTypeForDeclarator made a non-function block signature");
9259
9260 // Look for an explicit signature in that function type.
9261 FunctionProtoTypeLoc ExplicitSignature;
9262
9263 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9264 if (isa<FunctionProtoTypeLoc>(tmp)) {
9265 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9266
9267 // Check whether that explicit signature was synthesized by
9268 // GetTypeForDeclarator. If so, don't save that as part of the
9269 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009270 if (ExplicitSignature.getLocalRangeBegin() ==
9271 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009272 // This would be much cheaper if we stored TypeLocs instead of
9273 // TypeSourceInfos.
9274 TypeLoc Result = ExplicitSignature.getResultLoc();
9275 unsigned Size = Result.getFullDataSize();
9276 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9277 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9278
9279 ExplicitSignature = FunctionProtoTypeLoc();
9280 }
John McCall82dc0092010-06-04 11:21:44 +00009281 }
Mike Stump1eb44332009-09-09 15:08:12 +00009282
John McCall711c52b2011-01-05 12:14:39 +00009283 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9284 CurBlock->FunctionType = T;
9285
9286 const FunctionType *Fn = T->getAs<FunctionType>();
9287 QualType RetTy = Fn->getResultType();
9288 bool isVariadic =
9289 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9290
John McCallc71a4912010-06-04 19:02:56 +00009291 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009292
John McCall82dc0092010-06-04 11:21:44 +00009293 // Don't allow returning a objc interface by value.
9294 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009295 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009296 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9297 return;
9298 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009299
John McCall82dc0092010-06-04 11:21:44 +00009300 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009301 // return type. TODO: what should we do with declarators like:
9302 // ^ * { ... }
9303 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009304 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009305 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009306 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009307 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009308 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009309
John McCall82dc0092010-06-04 11:21:44 +00009310 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009311 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009312 if (ExplicitSignature) {
9313 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9314 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009315 if (Param->getIdentifier() == 0 &&
9316 !Param->isImplicit() &&
9317 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009318 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009319 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009320 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009321 }
John McCall82dc0092010-06-04 11:21:44 +00009322
9323 // Fake up parameter variables if we have a typedef, like
9324 // ^ fntype { ... }
9325 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9326 for (FunctionProtoType::arg_type_iterator
9327 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9328 ParmVarDecl *Param =
9329 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009330 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009331 *I);
John McCallc71a4912010-06-04 19:02:56 +00009332 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009333 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009334 }
John McCall82dc0092010-06-04 11:21:44 +00009335
John McCallc71a4912010-06-04 19:02:56 +00009336 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009337 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009338 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009339 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9340 CurBlock->TheDecl->param_end(),
9341 /*CheckParameterNames=*/false);
9342 }
9343
John McCall82dc0092010-06-04 11:21:44 +00009344 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009345 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009346
John McCall82dc0092010-06-04 11:21:44 +00009347 // Put the parameter variables in scope. We can bail out immediately
9348 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009349 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009350 return;
9351
Steve Naroff090276f2008-10-10 01:28:17 +00009352 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009353 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9354 (*AI)->setOwningFunction(CurBlock->TheDecl);
9355
Steve Naroff090276f2008-10-10 01:28:17 +00009356 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009357 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009358 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009359
Steve Naroff090276f2008-10-10 01:28:17 +00009360 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009361 }
John McCall7a9813c2010-01-22 00:28:27 +00009362 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009363}
9364
9365/// ActOnBlockError - If there is an error parsing a block, this callback
9366/// is invoked to pop the information about the block from the action impl.
9367void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009368 // Leave the expression-evaluation context.
9369 DiscardCleanupsInEvaluationContext();
9370 PopExpressionEvaluationContext();
9371
Steve Naroff4eb206b2008-09-03 18:15:37 +00009372 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009373 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009374 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009375}
9376
9377/// ActOnBlockStmtExpr - This is called when the body of a block statement
9378/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009379ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009380 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009381 // If blocks are disabled, emit an error.
9382 if (!LangOpts.Blocks)
9383 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009384
John McCall538773c2011-11-11 03:19:12 +00009385 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009386 if (hasAnyUnrecoverableErrorsInThisFunction())
9387 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009388 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9389 PopExpressionEvaluationContext();
9390
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009391 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009392
9393 if (BSI->HasImplicitReturnType)
9394 deduceClosureReturnType(*BSI);
9395
Steve Naroff090276f2008-10-10 01:28:17 +00009396 PopDeclContext();
9397
Steve Naroff4eb206b2008-09-03 18:15:37 +00009398 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009399 if (!BSI->ReturnType.isNull())
9400 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009401
Mike Stump56925862009-07-28 22:04:01 +00009402 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009403 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009404
John McCall469a1eb2011-02-02 13:00:07 +00009405 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009406 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9407 SmallVector<BlockDecl::Capture, 4> Captures;
9408 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9409 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9410 if (Cap.isThisCapture())
9411 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009412 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009413 Cap.isNested(), Cap.getCopyExpr());
9414 Captures.push_back(NewCap);
9415 }
9416 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9417 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009418
John McCallc71a4912010-06-04 19:02:56 +00009419 // If the user wrote a function type in some form, try to use that.
9420 if (!BSI->FunctionType.isNull()) {
9421 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9422
9423 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9424 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9425
9426 // Turn protoless block types into nullary block types.
9427 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009428 FunctionProtoType::ExtProtoInfo EPI;
9429 EPI.ExtInfo = Ext;
9430 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009431
9432 // Otherwise, if we don't need to change anything about the function type,
9433 // preserve its sugar structure.
9434 } else if (FTy->getResultType() == RetTy &&
9435 (!NoReturn || FTy->getNoReturnAttr())) {
9436 BlockTy = BSI->FunctionType;
9437
9438 // Otherwise, make the minimal modifications to the function type.
9439 } else {
9440 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009441 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9442 EPI.TypeQuals = 0; // FIXME: silently?
9443 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009444 BlockTy = Context.getFunctionType(RetTy,
9445 FPT->arg_type_begin(),
9446 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009447 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009448 }
9449
9450 // If we don't have a function type, just build one from nothing.
9451 } else {
John McCalle23cf432010-12-14 08:05:40 +00009452 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009453 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009454 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009455 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009456
John McCallc71a4912010-06-04 19:02:56 +00009457 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9458 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009459 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009460
Chris Lattner17a78302009-04-19 05:28:12 +00009461 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009462 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009463 !hasAnyUnrecoverableErrorsInThisFunction() &&
9464 !PP.isCodeCompletionEnabled())
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}