blob: 840a71461e264bd5ba24f15c98e153363882db15 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "TreeTransform.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000016#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/ASTContext.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000035#include "clang/Sema/DelayedDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000036#include "clang/Sema/Designator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000037#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
John McCall19510852010-08-20 18:27:03 +000040#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000041#include "clang/Sema/ScopeInfo.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"
Reid Spencer5f016e22007-07-11 17:01:13 +000044using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000045using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000046
Sebastian Redl14b0c192011-09-24 17:48:00 +000047/// \brief Determine whether the use of this declaration is valid, without
48/// emitting diagnostics.
49bool Sema::CanUseDecl(NamedDecl *D) {
50 // See if this is an auto-typed variable whose initializer we are parsing.
51 if (ParsingInitForAutoVars.count(D))
52 return false;
53
54 // See if this is a deleted function.
55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56 if (FD->isDeleted())
57 return false;
58 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000059
60 // See if this function is unavailable.
61 if (D->getAvailability() == AR_Unavailable &&
62 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
63 return false;
64
Sebastian Redl14b0c192011-09-24 17:48:00 +000065 return true;
66}
David Chisnall0f436562009-08-17 16:35:33 +000067
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000068static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
69 // Warn if this is used but marked unused.
70 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000071 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000072 if (!DC->hasAttr<UnusedAttr>())
73 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
74 }
75}
76
Ted Kremenekd6cf9122012-02-10 02:45:47 +000077static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000078 NamedDecl *D, SourceLocation Loc,
79 const ObjCInterfaceDecl *UnknownObjCClass) {
80 // See if this declaration is unavailable or deprecated.
81 std::string Message;
82 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000083 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
84 if (Result == AR_Available) {
85 const DeclContext *DC = ECD->getDeclContext();
86 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
87 Result = TheEnumDecl->getAvailability(&Message);
88 }
Jordan Rose04bec392012-10-10 16:42:54 +000089
Fariborz Jahanianfd090882012-09-21 20:46:37 +000090 const ObjCPropertyDecl *ObjCPDecl = 0;
Jordan Rose04bec392012-10-10 16:42:54 +000091 if (Result == AR_Deprecated || Result == AR_Unavailable) {
92 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
93 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
94 AvailabilityResult PDeclResult = PD->getAvailability(0);
95 if (PDeclResult == Result)
96 ObjCPDecl = PD;
97 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +000098 }
Jordan Rose04bec392012-10-10 16:42:54 +000099 }
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +0000100
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000101 switch (Result) {
102 case AR_Available:
103 case AR_NotYetIntroduced:
104 break;
105
106 case AR_Deprecated:
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000107 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000108 break;
109
110 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000111 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000112 if (Message.empty()) {
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000113 if (!UnknownObjCClass) {
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000114 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000115 if (ObjCPDecl)
116 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
117 << ObjCPDecl->getDeclName() << 1;
118 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000119 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000120 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000121 << D->getDeclName();
122 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000123 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000124 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000125 << D->getDeclName() << Message;
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000126 S.Diag(D->getLocation(), diag::note_unavailable_here)
127 << isa<FunctionDecl>(D) << false;
128 if (ObjCPDecl)
129 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
130 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000131 }
132 break;
133 }
134 return Result;
135}
136
Richard Smith6c4c36c2012-03-30 20:53:28 +0000137/// \brief Emit a note explaining that this function is deleted or unavailable.
138void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
139 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
140
Richard Smith5bdaac52012-04-02 20:59:25 +0000141 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
142 // If the method was explicitly defaulted, point at that declaration.
143 if (!Method->isImplicit())
144 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
145
146 // Try to diagnose why this special member function was implicitly
147 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000148 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000149 if (CSM != CXXInvalid)
150 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
151
152 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000153 }
154
155 Diag(Decl->getLocation(), diag::note_unavailable_here)
156 << 1 << Decl->isDeleted();
157}
158
Jordan Rose0eb3f452012-06-18 22:09:19 +0000159/// \brief Determine whether a FunctionDecl was ever declared with an
160/// explicit storage class.
161static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
162 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
163 E = D->redecls_end();
164 I != E; ++I) {
165 if (I->getStorageClassAsWritten() != SC_None)
166 return true;
167 }
168 return false;
169}
170
171/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000172/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000173///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000175/// in many cases it will not behave correctly. This is not enabled in C++ mode
176/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
177/// and so while there may still be user mistakes, most of the time we can't
178/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000179static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
180 const NamedDecl *D,
181 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000182 // This is disabled under C++; there are too many ways for this to fire in
183 // contexts where the warning is a false positive, or where it is technically
184 // correct but benign.
185 if (S.getLangOpts().CPlusPlus)
186 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000187
188 // Check if this is an inlined function or method.
189 FunctionDecl *Current = S.getCurFunctionDecl();
190 if (!Current)
191 return;
192 if (!Current->isInlined())
193 return;
194 if (Current->getLinkage() != ExternalLinkage)
195 return;
196
197 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000198 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000199 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000200
Jordan Rose05233272012-06-21 05:54:50 +0000201 // Downgrade from ExtWarn to Extension if
202 // (1) the supposedly external inline function is in the main file,
203 // and probably won't be included anywhere else.
204 // (2) the thing we're referencing is a pure function.
205 // (3) the thing we're referencing is another inline function.
206 // This last can give us false negatives, but it's better than warning on
207 // wrappers for simple C library functions.
208 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
209 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
210 if (!DowngradeWarning && UsedFn)
211 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
212
213 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
214 : diag::warn_internal_in_extern_inline)
215 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000216
217 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000218 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000219 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
220 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
221 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
222 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
223 }
224
225 S.Diag(D->getCanonicalDecl()->getLocation(),
226 diag::note_internal_decl_declared_here)
227 << D;
228}
229
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000230/// \brief Determine whether the use of this declaration is valid, and
231/// emit any corresponding diagnostics.
232///
233/// This routine diagnoses various problems with referencing
234/// declarations that can occur when using a declaration. For example,
235/// it might warn if a deprecated or unavailable declaration is being
236/// used, or produce an error (and return true) if a C++0x deleted
237/// function is being used.
238///
239/// \returns true if there was an error (this declaration cannot be
240/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000241///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000242bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000243 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000244 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000245 // If there were any diagnostics suppressed by template argument deduction,
246 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000247 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000248 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
249 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000250 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000251 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
252 Diag(Suppressed[I].first, Suppressed[I].second);
253
254 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000255 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000256 // entry from the table, because we want to avoid ever emitting these
257 // diagnostics again.
258 Suppressed.clear();
259 }
260 }
261
Richard Smith34b41d92011-02-20 03:19:35 +0000262 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000263 if (ParsingInitForAutoVars.count(D)) {
264 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
265 << D->getDeclName();
266 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000267 }
268
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000269 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000271 if (FD->isDeleted()) {
272 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000273 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000274 return true;
275 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000276 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000277 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000278
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000279 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000280
Jordan Rose0eb3f452012-06-18 22:09:19 +0000281 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000282
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000283 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000284}
285
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000286/// \brief Retrieve the message suffix that should be added to a
287/// diagnostic complaining about the given function being deleted or
288/// unavailable.
289std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000290 std::string Message;
291 if (FD->getAvailability(&Message))
292 return ": " + Message;
293
294 return std::string();
295}
296
John McCall3323fad2011-09-09 07:56:05 +0000297/// DiagnoseSentinelCalls - This routine checks whether a call or
298/// message-send is to a declaration with the sentinel attribute, and
299/// if so, it checks that the requirements of the sentinel are
300/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000301void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000302 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000303 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000304 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000305 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000306
John McCall3323fad2011-09-09 07:56:05 +0000307 // The number of formal parameters of the declaration.
308 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000309
John McCall3323fad2011-09-09 07:56:05 +0000310 // The kind of declaration. This is also an index into a %select in
311 // the diagnostic.
312 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
313
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000314 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000315 numFormalParams = MD->param_size();
316 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000317 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000318 numFormalParams = FD->param_size();
319 calleeType = CT_Function;
320 } else if (isa<VarDecl>(D)) {
321 QualType type = cast<ValueDecl>(D)->getType();
322 const FunctionType *fn = 0;
323 if (const PointerType *ptr = type->getAs<PointerType>()) {
324 fn = ptr->getPointeeType()->getAs<FunctionType>();
325 if (!fn) return;
326 calleeType = CT_Function;
327 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
328 fn = ptr->getPointeeType()->castAs<FunctionType>();
329 calleeType = CT_Block;
330 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000331 return;
John McCall3323fad2011-09-09 07:56:05 +0000332 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000333
John McCall3323fad2011-09-09 07:56:05 +0000334 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
335 numFormalParams = proto->getNumArgs();
336 } else {
337 numFormalParams = 0;
338 }
339 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000340 return;
341 }
John McCall3323fad2011-09-09 07:56:05 +0000342
343 // "nullPos" is the number of formal parameters at the end which
344 // effectively count as part of the variadic arguments. This is
345 // useful if you would prefer to not have *any* formal parameters,
346 // but the language forces you to have at least one.
347 unsigned nullPos = attr->getNullPos();
348 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
349 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
350
351 // The number of arguments which should follow the sentinel.
352 unsigned numArgsAfterSentinel = attr->getSentinel();
353
354 // If there aren't enough arguments for all the formal parameters,
355 // the sentinel, and the args after the sentinel, complain.
356 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000357 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000358 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000359 return;
360 }
John McCall3323fad2011-09-09 07:56:05 +0000361
362 // Otherwise, find the sentinel expression.
363 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000364 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000365 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000366 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000367
John McCall3323fad2011-09-09 07:56:05 +0000368 // Pick a reasonable string to insert. Optimistically use 'nil' or
369 // 'NULL' if those are actually defined in the context. Only use
370 // 'nil' for ObjC methods, where it's much more likely that the
371 // variadic arguments form a list of object pointers.
372 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000373 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
374 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000375 if (calleeType == CT_Method &&
376 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000377 NullValue = "nil";
378 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
379 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000380 else
John McCall3323fad2011-09-09 07:56:05 +0000381 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000382
383 if (MissingNilLoc.isInvalid())
384 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
385 else
386 Diag(MissingNilLoc, diag::warn_missing_sentinel)
387 << calleeType
388 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000389 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000390}
391
Richard Trieuccd891a2011-09-09 01:45:06 +0000392SourceRange Sema::getExprRange(Expr *E) const {
393 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000394}
395
Chris Lattnere7a2e912008-07-25 21:10:04 +0000396//===----------------------------------------------------------------------===//
397// Standard Promotions and Conversions
398//===----------------------------------------------------------------------===//
399
Chris Lattnere7a2e912008-07-25 21:10:04 +0000400/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000401ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000402 // Handle any placeholder expressions which made it here.
403 if (E->getType()->isPlaceholderType()) {
404 ExprResult result = CheckPlaceholderExpr(E);
405 if (result.isInvalid()) return ExprError();
406 E = result.take();
407 }
408
Chris Lattnere7a2e912008-07-25 21:10:04 +0000409 QualType Ty = E->getType();
410 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
411
Chris Lattnere7a2e912008-07-25 21:10:04 +0000412 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000413 E = ImpCastExprToType(E, Context.getPointerType(Ty),
414 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000415 else if (Ty->isArrayType()) {
416 // In C90 mode, arrays only promote to pointers if the array expression is
417 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
418 // type 'array of type' is converted to an expression that has type 'pointer
419 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
420 // that has type 'array of type' ...". The relevant change is "an lvalue"
421 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000422 //
423 // C++ 4.2p1:
424 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
425 // T" can be converted to an rvalue of type "pointer to T".
426 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000427 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000428 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
429 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000430 }
John Wiegley429bb272011-04-08 18:41:53 +0000431 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000432}
433
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000434static void CheckForNullPointerDereference(Sema &S, Expr *E) {
435 // Check to see if we are dereferencing a null pointer. If so,
436 // and if not volatile-qualified, this is undefined behavior that the
437 // optimizer will delete, so warn about it. People sometimes try to use this
438 // to get a deterministic trap and are surprised by clang's behavior. This
439 // only handles the pattern "*null", which is a very syntactic check.
440 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
441 if (UO->getOpcode() == UO_Deref &&
442 UO->getSubExpr()->IgnoreParenCasts()->
443 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
444 !UO->getType().isVolatileQualified()) {
445 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
446 S.PDiag(diag::warn_indirection_through_null)
447 << UO->getSubExpr()->getSourceRange());
448 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449 S.PDiag(diag::note_indirection_through_null));
450 }
451}
452
John Wiegley429bb272011-04-08 18:41:53 +0000453ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000454 // Handle any placeholder expressions which made it here.
455 if (E->getType()->isPlaceholderType()) {
456 ExprResult result = CheckPlaceholderExpr(E);
457 if (result.isInvalid()) return ExprError();
458 E = result.take();
459 }
460
John McCall0ae287a2010-12-01 04:43:34 +0000461 // C++ [conv.lval]p1:
462 // A glvalue of a non-function, non-array type T can be
463 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000464 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000465
John McCall409fa9a2010-12-06 20:48:59 +0000466 QualType T = E->getType();
467 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000468
John McCall409fa9a2010-12-06 20:48:59 +0000469 // We don't want to throw lvalue-to-rvalue casts on top of
470 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000471 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000472 (E->getType() == Context.OverloadTy ||
473 T->isDependentType() ||
474 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000475 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000476
477 // The C standard is actually really unclear on this point, and
478 // DR106 tells us what the result should be but not why. It's
479 // generally best to say that void types just doesn't undergo
480 // lvalue-to-rvalue at all. Note that expressions of unqualified
481 // 'void' type are never l-values, but qualified void can be.
482 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000483 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000484
John McCall9dd74c52013-02-12 01:29:43 +0000485 // OpenCL usually rejects direct accesses to values of 'half' type.
486 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
487 T->isHalfType()) {
488 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
489 << 0 << T;
490 return ExprError();
491 }
492
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000493 CheckForNullPointerDereference(*this, E);
494
John McCall409fa9a2010-12-06 20:48:59 +0000495 // C++ [conv.lval]p1:
496 // [...] If T is a non-class type, the type of the prvalue is the
497 // cv-unqualified version of T. Otherwise, the type of the
498 // rvalue is T.
499 //
500 // C99 6.3.2.1p2:
501 // If the lvalue has qualified type, the value has the unqualified
502 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000503 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000504 if (T.hasQualifiers())
505 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000506
Eli Friedmand2cce132012-02-02 23:15:15 +0000507 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +0000508
509 // Loading a __weak object implicitly retains the value, so we need a cleanup to
510 // balance that.
511 if (getLangOpts().ObjCAutoRefCount &&
512 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
513 ExprNeedsCleanups = true;
Eli Friedmand2cce132012-02-02 23:15:15 +0000514
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000515 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
516 E, 0, VK_RValue));
517
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000518 // C11 6.3.2.1p2:
519 // ... if the lvalue has atomic type, the value has the non-atomic version
520 // of the type of the lvalue ...
521 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
522 T = Atomic->getValueType().getUnqualifiedType();
523 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
524 Res.get(), 0, VK_RValue));
525 }
526
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000527 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000528}
529
John Wiegley429bb272011-04-08 18:41:53 +0000530ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
531 ExprResult Res = DefaultFunctionArrayConversion(E);
532 if (Res.isInvalid())
533 return ExprError();
534 Res = DefaultLvalueConversion(Res.take());
535 if (Res.isInvalid())
536 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000537 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000538}
539
540
Chris Lattnere7a2e912008-07-25 21:10:04 +0000541/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000542/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000543/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000544/// apply if the array is an argument to the sizeof or address (&) operators.
545/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000546ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000547 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000548 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
549 if (Res.isInvalid())
Fariborz Jahanian75525c42013-03-06 00:37:40 +0000550 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +0000551 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000552
John McCall0ae287a2010-12-01 04:43:34 +0000553 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000554 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000555
Joey Gouly19dbb202013-01-23 11:56:20 +0000556 // Half FP have to be promoted to float unless it is natively supported
557 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000558 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
559
John McCall0ae287a2010-12-01 04:43:34 +0000560 // Try to perform integral promotions if the object has a theoretically
561 // promotable type.
562 if (Ty->isIntegralOrUnscopedEnumerationType()) {
563 // C99 6.3.1.1p2:
564 //
565 // The following may be used in an expression wherever an int or
566 // unsigned int may be used:
567 // - an object or expression with an integer type whose integer
568 // conversion rank is less than or equal to the rank of int
569 // and unsigned int.
570 // - A bit-field of type _Bool, int, signed int, or unsigned int.
571 //
572 // If an int can represent all values of the original type, the
573 // value is converted to an int; otherwise, it is converted to an
574 // unsigned int. These are called the integer promotions. All
575 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000576
John McCall0ae287a2010-12-01 04:43:34 +0000577 QualType PTy = Context.isPromotableBitField(E);
578 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000579 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
580 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000581 }
582 if (Ty->isPromotableIntegerType()) {
583 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000584 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
585 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000586 }
Eli Friedman04e83572009-08-20 04:21:42 +0000587 }
John Wiegley429bb272011-04-08 18:41:53 +0000588 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000589}
590
Chris Lattner05faf172008-07-25 22:25:12 +0000591/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Tim Northovere1ac4ae2013-01-30 09:46:55 +0000592/// do not have a prototype. Arguments that have type float or __fp16
593/// are promoted to double. All other argument types are converted by
594/// UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000595ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
596 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000597 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000598
John Wiegley429bb272011-04-08 18:41:53 +0000599 ExprResult Res = UsualUnaryConversions(E);
600 if (Res.isInvalid())
Fariborz Jahanian75525c42013-03-06 00:37:40 +0000601 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +0000602 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000603
Tim Northovere1ac4ae2013-01-30 09:46:55 +0000604 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
605 // double.
606 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
607 if (BTy && (BTy->getKind() == BuiltinType::Half ||
608 BTy->getKind() == BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000609 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
610
John McCall96a914a2011-08-27 22:06:17 +0000611 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000612 // promotion, even on class types, but note:
613 // C++11 [conv.lval]p2:
614 // When an lvalue-to-rvalue conversion occurs in an unevaluated
615 // operand or a subexpression thereof the value contained in the
616 // referenced object is not accessed. Otherwise, if the glvalue
617 // has a class type, the conversion copy-initializes a temporary
618 // of type T from the glvalue and the result of the conversion
619 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000620 // FIXME: add some way to gate this entire thing for correctness in
621 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000622 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000623 ExprResult Temp = PerformCopyInitialization(
624 InitializedEntity::InitializeTemporary(E->getType()),
625 E->getExprLoc(),
626 Owned(E));
627 if (Temp.isInvalid())
628 return ExprError();
629 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000630 }
631
John Wiegley429bb272011-04-08 18:41:53 +0000632 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000633}
634
Richard Smith831421f2012-06-25 20:30:08 +0000635/// Determine the degree of POD-ness for an expression.
636/// Incomplete types are considered POD, since this check can be performed
637/// when we're in an unevaluated context.
638Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000639 if (Ty->isIncompleteType()) {
640 if (Ty->isObjCObjectType())
641 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000642 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000643 }
644
645 if (Ty.isCXX98PODType(Context))
646 return VAK_Valid;
647
Richard Smith426391c2012-11-16 00:53:38 +0000648 // C++11 [expr.call]p7:
649 // Passing a potentially-evaluated argument of class type (Clause 9)
Richard Smith831421f2012-06-25 20:30:08 +0000650 // having a non-trivial copy constructor, a non-trivial move constructor,
Richard Smith426391c2012-11-16 00:53:38 +0000651 // or a non-trivial destructor, with no corresponding parameter,
Richard Smith831421f2012-06-25 20:30:08 +0000652 // is conditionally-supported with implementation-defined semantics.
Richard Smith80ad52f2013-01-02 11:42:31 +0000653 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
Richard Smith831421f2012-06-25 20:30:08 +0000654 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
Richard Smith426391c2012-11-16 00:53:38 +0000655 if (!Record->hasNonTrivialCopyConstructor() &&
656 !Record->hasNonTrivialMoveConstructor() &&
657 !Record->hasNonTrivialDestructor())
Richard Smith831421f2012-06-25 20:30:08 +0000658 return VAK_ValidInCXX11;
659
660 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
661 return VAK_Valid;
662 return VAK_Invalid;
663}
664
665bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
666 // Don't allow one to pass an Objective-C interface to a vararg.
667 const QualType & Ty = E->getType();
668
669 // Complain about passing non-POD types through varargs.
670 switch (isValidVarArgType(Ty)) {
671 case VAK_Valid:
672 break;
673 case VAK_ValidInCXX11:
674 DiagRuntimeBehavior(E->getLocStart(), 0,
675 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
676 << E->getType() << CT);
677 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000678 case VAK_Invalid: {
679 if (Ty->isObjCObjectType())
680 return DiagRuntimeBehavior(E->getLocStart(), 0,
681 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
682 << Ty << CT);
683
Richard Smith831421f2012-06-25 20:30:08 +0000684 return DiagRuntimeBehavior(E->getLocStart(), 0,
685 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Richard Smith80ad52f2013-01-02 11:42:31 +0000686 << getLangOpts().CPlusPlus11 << Ty << CT);
Richard Smith831421f2012-06-25 20:30:08 +0000687 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000688 }
Richard Smith831421f2012-06-25 20:30:08 +0000689 // c++ rules are enforced elsewhere.
690 return false;
691}
692
Chris Lattner312531a2009-04-12 08:11:20 +0000693/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000694/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000695ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000696 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000697 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000698 // Strip the unbridged-cast placeholder expression off, if applicable.
699 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
700 (CT == VariadicMethod ||
701 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
702 E = stripARCUnbridgedCast(E);
703
704 // Otherwise, do normal placeholder checking.
705 } else {
706 ExprResult ExprRes = CheckPlaceholderExpr(E);
707 if (ExprRes.isInvalid())
708 return ExprError();
709 E = ExprRes.take();
710 }
711 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000712
John McCall5acb0c92011-10-17 18:40:02 +0000713 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000714 if (ExprRes.isInvalid())
715 return ExprError();
716 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Richard Smith831421f2012-06-25 20:30:08 +0000718 // Diagnostics regarding non-POD argument types are
719 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000720 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000721 // Turn this into a trap.
722 CXXScopeSpec SS;
723 SourceLocation TemplateKWLoc;
724 UnqualifiedId Name;
725 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
726 E->getLocStart());
727 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
728 Name, true, false);
729 if (TrapFn.isInvalid())
730 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000731
Richard Smith831421f2012-06-25 20:30:08 +0000732 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
733 E->getLocStart(), MultiExprArg(),
734 E->getLocEnd());
735 if (Call.isInvalid())
736 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000737
Richard Smith831421f2012-06-25 20:30:08 +0000738 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
739 Call.get(), E);
740 if (Comma.isInvalid())
741 return ExprError();
742 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000743 }
Richard Smith831421f2012-06-25 20:30:08 +0000744
David Blaikie4e4d0842012-03-11 07:00:24 +0000745 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000746 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000747 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000748 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000749
John Wiegley429bb272011-04-08 18:41:53 +0000750 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000751}
752
Richard Trieu8289f492011-09-02 20:58:51 +0000753/// \brief Converts an integer to complex float type. Helper function of
754/// UsualArithmeticConversions()
755///
756/// \return false if the integer expression is an integer type and is
757/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000758static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
759 ExprResult &ComplexExpr,
760 QualType IntTy,
761 QualType ComplexTy,
762 bool SkipCast) {
763 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
764 if (SkipCast) return false;
765 if (IntTy->isIntegerType()) {
766 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
767 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
768 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000769 CK_FloatingRealToComplex);
770 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000771 assert(IntTy->isComplexIntegerType());
772 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000773 CK_IntegralComplexToFloatingComplex);
774 }
775 return false;
776}
777
778/// \brief Takes two complex float types and converts them to the same type.
779/// Helper function of UsualArithmeticConversions()
780static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000781handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
782 ExprResult &RHS, QualType LHSType,
783 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000784 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000785 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000786
787 if (order < 0) {
788 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000789 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000790 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
791 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000792 }
793 if (order > 0)
794 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000795 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
796 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000797}
798
799/// \brief Converts otherExpr to complex float and promotes complexExpr if
800/// necessary. Helper function of UsualArithmeticConversions()
801static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000802 ExprResult &ComplexExpr,
803 ExprResult &OtherExpr,
804 QualType ComplexTy,
805 QualType OtherTy,
806 bool ConvertComplexExpr,
807 bool ConvertOtherExpr) {
808 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000809
810 // If just the complexExpr is complex, the otherExpr needs to be converted,
811 // and the complexExpr might need to be promoted.
812 if (order > 0) { // complexExpr is wider
813 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000814 if (ConvertOtherExpr) {
815 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
816 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
817 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000818 CK_FloatingRealToComplex);
819 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000820 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000821 }
822
823 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000824 QualType result = (order == 0 ? ComplexTy :
825 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000826
827 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000828 if (ConvertOtherExpr)
829 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000830 CK_FloatingRealToComplex);
831
832 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000833 if (ConvertComplexExpr && order < 0)
834 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000835 CK_FloatingComplexCast);
836
837 return result;
838}
839
840/// \brief Handle arithmetic conversion with complex types. Helper function of
841/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000842static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
843 ExprResult &RHS, QualType LHSType,
844 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000845 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000846 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000847 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000848 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000849 return LHSType;
850 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000851 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000852 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000853
854 // This handles complex/complex, complex/float, or float/complex.
855 // When both operands are complex, the shorter operand is converted to the
856 // type of the longer, and that is the type of the result. This corresponds
857 // to what is done when combining two real floating-point operands.
858 // The fun begins when size promotion occur across type domains.
859 // From H&S 6.3.4: When one operand is complex and the other is a real
860 // floating-point type, the less precise type is converted, within it's
861 // real or complex domain, to the precision of the other type. For example,
862 // when combining a "long double" with a "double _Complex", the
863 // "double _Complex" is promoted to "long double _Complex".
864
Richard Trieucafd30b2011-09-06 18:25:09 +0000865 bool LHSComplexFloat = LHSType->isComplexType();
866 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000867
868 // If both are complex, just cast to the more precise type.
869 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000870 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
871 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000872 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000873
874 // If only one operand is complex, promote it if necessary and convert the
875 // other operand to complex.
876 if (LHSComplexFloat)
877 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000878 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000879 /*convertOtherExpr*/ true);
880
881 assert(RHSComplexFloat);
882 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000883 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000884 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000885}
886
887/// \brief Hande arithmetic conversion from integer to float. Helper function
888/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000889static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
890 ExprResult &IntExpr,
891 QualType FloatTy, QualType IntTy,
892 bool ConvertFloat, bool ConvertInt) {
893 if (IntTy->isIntegerType()) {
894 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000895 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000896 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000897 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000898 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000899 }
900
901 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000902 assert(IntTy->isComplexIntegerType());
903 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000904
905 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000906 if (ConvertInt)
907 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000908 CK_IntegralComplexToFloatingComplex);
909
910 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000911 if (ConvertFloat)
912 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000913 CK_FloatingRealToComplex);
914
915 return result;
916}
917
918/// \brief Handle arithmethic conversion with floating point types. Helper
919/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000920static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
921 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000922 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000923 bool LHSFloat = LHSType->isRealFloatingType();
924 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000925
926 // If we have two real floating types, convert the smaller operand
927 // to the bigger result.
928 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000929 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000930 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000931 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
932 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000933 }
934
935 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000936 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000937 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
938 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000939 }
940
941 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000942 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000943 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000944 /*convertInt=*/ true);
945 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000946 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000947 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000948 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000949}
950
Bill Schmidt57dab712013-02-01 15:34:29 +0000951typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
Richard Trieu8289f492011-09-02 20:58:51 +0000952
Bill Schmidt57dab712013-02-01 15:34:29 +0000953namespace {
954/// These helper callbacks are placed in an anonymous namespace to
955/// permit their use as function template parameters.
956ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
957 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
958}
Richard Trieu8289f492011-09-02 20:58:51 +0000959
Bill Schmidt57dab712013-02-01 15:34:29 +0000960ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
961 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
962 CK_IntegralComplexCast);
963}
Richard Trieu8289f492011-09-02 20:58:51 +0000964}
965
966/// \brief Handle integer arithmetic conversions. Helper function of
967/// UsualArithmeticConversions()
Bill Schmidt57dab712013-02-01 15:34:29 +0000968template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000969static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
970 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000971 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000972 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000973 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
974 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
975 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
976 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000977 // Same signedness; use the higher-ranked type
978 if (order >= 0) {
Bill Schmidt57dab712013-02-01 15:34:29 +0000979 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000980 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000981 } else if (!IsCompAssign)
Bill Schmidt57dab712013-02-01 15:34:29 +0000982 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000983 return RHSType;
984 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000985 // The unsigned type has greater than or equal rank to the
986 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000987 if (RHSSigned) {
Bill Schmidt57dab712013-02-01 15:34:29 +0000988 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000989 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000990 } else if (!IsCompAssign)
Bill Schmidt57dab712013-02-01 15:34:29 +0000991 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000992 return RHSType;
993 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000994 // The two types are different widths; if we are here, that
995 // means the signed type is larger than the unsigned type, so
996 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000997 if (LHSSigned) {
Bill Schmidt57dab712013-02-01 15:34:29 +0000998 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000999 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001000 } else if (!IsCompAssign)
Bill Schmidt57dab712013-02-01 15:34:29 +00001001 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001002 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001003 } else {
1004 // The signed type is higher-ranked than the unsigned type,
1005 // but isn't actually any bigger (like unsigned int and long
1006 // on most 32-bit systems). Use the unsigned type corresponding
1007 // to the signed type.
1008 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001009 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
Bill Schmidt57dab712013-02-01 15:34:29 +00001010 RHS = (*doRHSCast)(S, RHS.take(), result);
Richard Trieuccd891a2011-09-09 01:45:06 +00001011 if (!IsCompAssign)
Bill Schmidt57dab712013-02-01 15:34:29 +00001012 LHS = (*doLHSCast)(S, LHS.take(), result);
Richard Trieu8289f492011-09-02 20:58:51 +00001013 return result;
1014 }
1015}
1016
Bill Schmidt57dab712013-02-01 15:34:29 +00001017/// \brief Handle conversions with GCC complex int extension. Helper function
1018/// of UsualArithmeticConversions()
1019static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1020 ExprResult &RHS, QualType LHSType,
1021 QualType RHSType,
1022 bool IsCompAssign) {
1023 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1024 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1025
1026 if (LHSComplexInt && RHSComplexInt) {
1027 QualType LHSEltType = LHSComplexInt->getElementType();
1028 QualType RHSEltType = RHSComplexInt->getElementType();
1029 QualType ScalarType =
1030 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1031 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1032
1033 return S.Context.getComplexType(ScalarType);
1034 }
1035
1036 if (LHSComplexInt) {
1037 QualType LHSEltType = LHSComplexInt->getElementType();
1038 QualType ScalarType =
1039 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1040 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1041 QualType ComplexType = S.Context.getComplexType(ScalarType);
1042 RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1043 CK_IntegralRealToComplex);
1044
1045 return ComplexType;
1046 }
1047
1048 assert(RHSComplexInt);
1049
1050 QualType RHSEltType = RHSComplexInt->getElementType();
1051 QualType ScalarType =
1052 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1053 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1054 QualType ComplexType = S.Context.getComplexType(ScalarType);
1055
1056 if (!IsCompAssign)
1057 LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1058 CK_IntegralRealToComplex);
1059 return ComplexType;
1060}
1061
Chris Lattnere7a2e912008-07-25 21:10:04 +00001062/// UsualArithmeticConversions - Performs various conversions that are common to
1063/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001064/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001065/// responsible for emitting appropriate error diagnostics.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001066QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001067 bool IsCompAssign) {
1068 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001069 LHS = UsualUnaryConversions(LHS.take());
1070 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001071 return QualType();
1072 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001073
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001074 RHS = UsualUnaryConversions(RHS.take());
1075 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001076 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001077
Mike Stump1eb44332009-09-09 15:08:12 +00001078 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001079 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001080 QualType LHSType =
1081 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1082 QualType RHSType =
1083 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001084
Eli Friedman860a3192012-06-16 02:19:17 +00001085 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1086 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1087 LHSType = AtomicLHS->getValueType();
1088
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001089 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001090 if (LHSType == RHSType)
1091 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001092
1093 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1094 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001095 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001096 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001097
John McCallcf33b242010-11-13 08:17:45 +00001098 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001099 QualType LHSUnpromotedType = LHSType;
1100 if (LHSType->isPromotableIntegerType())
1101 LHSType = Context.getPromotedIntegerType(LHSType);
1102 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001103 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001104 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001105 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001106 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001107
John McCallcf33b242010-11-13 08:17:45 +00001108 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001109 if (LHSType == RHSType)
1110 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001111
1112 // At this point, we have two different arithmetic types.
1113
1114 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001115 if (LHSType->isComplexType() || RHSType->isComplexType())
1116 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001117 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001118
1119 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001120 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1121 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001122 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001123
1124 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001125 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001126 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001127 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001128
1129 // Finally, we have two differing integer types.
Bill Schmidt57dab712013-02-01 15:34:29 +00001130 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1131 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001132}
1133
Bill Schmidt57dab712013-02-01 15:34:29 +00001134
Chris Lattnere7a2e912008-07-25 21:10:04 +00001135//===----------------------------------------------------------------------===//
1136// Semantic Analysis for various Expression Types
1137//===----------------------------------------------------------------------===//
1138
1139
Peter Collingbournef111d932011-04-15 00:35:48 +00001140ExprResult
1141Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1142 SourceLocation DefaultLoc,
1143 SourceLocation RParenLoc,
1144 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001145 MultiTypeArg ArgTypes,
1146 MultiExprArg ArgExprs) {
1147 unsigned NumAssocs = ArgTypes.size();
1148 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001149
Benjamin Kramer5354e772012-08-23 23:38:35 +00001150 ParsedType *ParsedTypes = ArgTypes.data();
1151 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001152
1153 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1154 for (unsigned i = 0; i < NumAssocs; ++i) {
1155 if (ParsedTypes[i])
1156 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1157 else
1158 Types[i] = 0;
1159 }
1160
1161 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1162 ControllingExpr, Types, Exprs,
1163 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001164 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001165 return ER;
1166}
1167
1168ExprResult
1169Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1170 SourceLocation DefaultLoc,
1171 SourceLocation RParenLoc,
1172 Expr *ControllingExpr,
1173 TypeSourceInfo **Types,
1174 Expr **Exprs,
1175 unsigned NumAssocs) {
John McCalla2905ea2013-02-12 02:08:12 +00001176 if (ControllingExpr->getType()->isPlaceholderType()) {
1177 ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1178 if (result.isInvalid()) return ExprError();
1179 ControllingExpr = result.take();
1180 }
1181
Peter Collingbournef111d932011-04-15 00:35:48 +00001182 bool TypeErrorFound = false,
1183 IsResultDependent = ControllingExpr->isTypeDependent(),
1184 ContainsUnexpandedParameterPack
1185 = ControllingExpr->containsUnexpandedParameterPack();
1186
1187 for (unsigned i = 0; i < NumAssocs; ++i) {
1188 if (Exprs[i]->containsUnexpandedParameterPack())
1189 ContainsUnexpandedParameterPack = true;
1190
1191 if (Types[i]) {
1192 if (Types[i]->getType()->containsUnexpandedParameterPack())
1193 ContainsUnexpandedParameterPack = true;
1194
1195 if (Types[i]->getType()->isDependentType()) {
1196 IsResultDependent = true;
1197 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001198 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001199 // complete object type other than a variably modified type."
1200 unsigned D = 0;
1201 if (Types[i]->getType()->isIncompleteType())
1202 D = diag::err_assoc_type_incomplete;
1203 else if (!Types[i]->getType()->isObjectType())
1204 D = diag::err_assoc_type_nonobject;
1205 else if (Types[i]->getType()->isVariablyModifiedType())
1206 D = diag::err_assoc_type_variably_modified;
1207
1208 if (D != 0) {
1209 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1210 << Types[i]->getTypeLoc().getSourceRange()
1211 << Types[i]->getType();
1212 TypeErrorFound = true;
1213 }
1214
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001215 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001216 // selection shall specify compatible types."
1217 for (unsigned j = i+1; j < NumAssocs; ++j)
1218 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1219 Context.typesAreCompatible(Types[i]->getType(),
1220 Types[j]->getType())) {
1221 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1222 diag::err_assoc_compatible_types)
1223 << Types[j]->getTypeLoc().getSourceRange()
1224 << Types[j]->getType()
1225 << Types[i]->getType();
1226 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1227 diag::note_compat_assoc)
1228 << Types[i]->getTypeLoc().getSourceRange()
1229 << Types[i]->getType();
1230 TypeErrorFound = true;
1231 }
1232 }
1233 }
1234 }
1235 if (TypeErrorFound)
1236 return ExprError();
1237
1238 // If we determined that the generic selection is result-dependent, don't
1239 // try to compute the result expression.
1240 if (IsResultDependent)
1241 return Owned(new (Context) GenericSelectionExpr(
1242 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001243 llvm::makeArrayRef(Types, NumAssocs),
1244 llvm::makeArrayRef(Exprs, NumAssocs),
1245 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001246
Chris Lattner5f9e2722011-07-23 10:55:15 +00001247 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001248 unsigned DefaultIndex = -1U;
1249 for (unsigned i = 0; i < NumAssocs; ++i) {
1250 if (!Types[i])
1251 DefaultIndex = i;
1252 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1253 Types[i]->getType()))
1254 CompatIndices.push_back(i);
1255 }
1256
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001257 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001258 // type compatible with at most one of the types named in its generic
1259 // association list."
1260 if (CompatIndices.size() > 1) {
1261 // We strip parens here because the controlling expression is typically
1262 // parenthesized in macro definitions.
1263 ControllingExpr = ControllingExpr->IgnoreParens();
1264 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1265 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1266 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001267 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001268 E = CompatIndices.end(); I != E; ++I) {
1269 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1270 diag::note_compat_assoc)
1271 << Types[*I]->getTypeLoc().getSourceRange()
1272 << Types[*I]->getType();
1273 }
1274 return ExprError();
1275 }
1276
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001277 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001278 // its controlling expression shall have type compatible with exactly one of
1279 // the types named in its generic association list."
1280 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1281 // We strip parens here because the controlling expression is typically
1282 // parenthesized in macro definitions.
1283 ControllingExpr = ControllingExpr->IgnoreParens();
1284 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1285 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1286 return ExprError();
1287 }
1288
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001289 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001290 // type name that is compatible with the type of the controlling expression,
1291 // then the result expression of the generic selection is the expression
1292 // in that generic association. Otherwise, the result expression of the
1293 // generic selection is the expression in the default generic association."
1294 unsigned ResultIndex =
1295 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1296
1297 return Owned(new (Context) GenericSelectionExpr(
1298 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001299 llvm::makeArrayRef(Types, NumAssocs),
1300 llvm::makeArrayRef(Exprs, NumAssocs),
1301 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001302 ResultIndex));
1303}
1304
Richard Smithdd66be72012-03-08 01:34:56 +00001305/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1306/// location of the token and the offset of the ud-suffix within it.
1307static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1308 unsigned Offset) {
1309 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001310 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001311}
1312
Richard Smith36f5cfe2012-03-09 08:00:36 +00001313/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1314/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1315static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1316 IdentifierInfo *UDSuffix,
1317 SourceLocation UDSuffixLoc,
1318 ArrayRef<Expr*> Args,
1319 SourceLocation LitEndLoc) {
1320 assert(Args.size() <= 2 && "too many arguments for literal operator");
1321
1322 QualType ArgTy[2];
1323 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1324 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1325 if (ArgTy[ArgIdx]->isArrayType())
1326 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1327 }
1328
1329 DeclarationName OpName =
1330 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1331 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1332 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1333
1334 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1335 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1336 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1337 return ExprError();
1338
1339 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1340}
1341
Steve Narofff69936d2007-09-16 03:34:24 +00001342/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001343/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1344/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1345/// multiple tokens. However, the common case is that StringToks points to one
1346/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001347///
John McCall60d7b3a2010-08-24 06:29:42 +00001348ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001349Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1350 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 assert(NumStringToks && "Must have at least one string!");
1352
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001353 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001355 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001356
Chris Lattner5f9e2722011-07-23 10:55:15 +00001357 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 for (unsigned i = 0; i != NumStringToks; ++i)
1359 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001360
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001361 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001362 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001363 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001364 else if (Literal.isUTF16())
1365 StrTy = Context.Char16Ty;
1366 else if (Literal.isUTF32())
1367 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001368 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001369 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001370
Douglas Gregor5cee1192011-07-27 05:40:30 +00001371 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1372 if (Literal.isWide())
1373 Kind = StringLiteral::Wide;
1374 else if (Literal.isUTF8())
1375 Kind = StringLiteral::UTF8;
1376 else if (Literal.isUTF16())
1377 Kind = StringLiteral::UTF16;
1378 else if (Literal.isUTF32())
1379 Kind = StringLiteral::UTF32;
1380
Douglas Gregor77a52232008-09-12 00:47:35 +00001381 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001382 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001383 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001384
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001385 // Get an array type for the string, according to C99 6.4.5. This includes
1386 // the nul terminator character as well as the string length for pascal
1387 // strings.
1388 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001389 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001390 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001393 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1394 Kind, Literal.Pascal, StrTy,
1395 &StringTokLocs[0],
1396 StringTokLocs.size());
1397 if (Literal.getUDSuffix().empty())
1398 return Owned(Lit);
1399
1400 // We're building a user-defined literal.
1401 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001402 SourceLocation UDSuffixLoc =
1403 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1404 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001405
Richard Smith36f5cfe2012-03-09 08:00:36 +00001406 // Make sure we're allowed user-defined literals here.
1407 if (!UDLScope)
1408 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1409
Richard Smith9fcce652012-03-07 08:35:16 +00001410 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1411 // operator "" X (str, len)
1412 QualType SizeType = Context.getSizeType();
1413 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1414 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1415 StringTokLocs[0]);
1416 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001417 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1418 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001419}
1420
John McCall60d7b3a2010-08-24 06:29:42 +00001421ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001422Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001423 SourceLocation Loc,
1424 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001425 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001426 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001427}
1428
John McCall76a40212011-02-09 01:13:10 +00001429/// BuildDeclRefExpr - Build an expression that references a
1430/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001431ExprResult
John McCall76a40212011-02-09 01:13:10 +00001432Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001433 const DeclarationNameInfo &NameInfo,
1434 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001435 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001436 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1437 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1438 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1439 CalleeTarget = IdentifyCUDATarget(Callee);
1440 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1441 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1442 << CalleeTarget << D->getIdentifier() << CallerTarget;
1443 Diag(D->getLocation(), diag::note_previous_decl)
1444 << D->getIdentifier();
1445 return ExprError();
1446 }
1447 }
1448
John McCallf4b88a42012-03-10 09:33:50 +00001449 bool refersToEnclosingScope =
1450 (CurContext != D->getDeclContext() &&
1451 D->getDeclContext()->isFunctionOrMethod());
1452
Eli Friedman5f2987c2012-02-02 03:46:19 +00001453 DeclRefExpr *E = DeclRefExpr::Create(Context,
1454 SS ? SS->getWithLocInContext(Context)
1455 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001456 SourceLocation(),
1457 D, refersToEnclosingScope,
1458 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Eli Friedman5f2987c2012-02-02 03:46:19 +00001460 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001461
Jordan Rose7a270482012-09-28 22:21:35 +00001462 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1463 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1464 DiagnosticsEngine::Level Level =
1465 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1466 E->getLocStart());
1467 if (Level != DiagnosticsEngine::Ignored)
1468 getCurFunction()->recordUseOfWeak(E);
1469 }
1470
John McCall7eb0a9e2010-11-24 05:12:34 +00001471 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001472 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1473 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001474 E->setObjectKind(OK_BitField);
1475
1476 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001477}
1478
Abramo Bagnara25777432010-08-11 22:01:17 +00001479/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001480/// possibly a list of template arguments.
1481///
1482/// If this produces template arguments, it is permitted to call
1483/// DecomposeTemplateName.
1484///
1485/// This actually loses a lot of source location information for
1486/// non-standard name kinds; we should consider preserving that in
1487/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001488void
1489Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1490 TemplateArgumentListInfo &Buffer,
1491 DeclarationNameInfo &NameInfo,
1492 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001493 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1494 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1495 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1496
Benjamin Kramer5354e772012-08-23 23:38:35 +00001497 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001498 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001499 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001500
John McCall2b5289b2010-08-23 07:28:44 +00001501 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001502 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001503 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001504 TemplateArgs = &Buffer;
1505 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001506 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001507 TemplateArgs = 0;
1508 }
1509}
1510
John McCall578b69b2009-12-16 08:11:27 +00001511/// Diagnose an empty lookup.
1512///
1513/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001514bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001515 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001516 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001517 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001518 DeclarationName Name = R.getLookupName();
1519
John McCall578b69b2009-12-16 08:11:27 +00001520 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001521 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001522 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1523 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001524 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001525 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001526 diagnostic_suggest = diag::err_undeclared_use_suggest;
1527 }
John McCall578b69b2009-12-16 08:11:27 +00001528
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001529 // If the original lookup was an unqualified lookup, fake an
1530 // unqualified lookup. This is useful when (for example) the
1531 // original lookup would not have found something because it was a
1532 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001533 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1534 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001535 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001536 if (isa<CXXRecordDecl>(DC)) {
1537 LookupQualifiedName(R, DC);
1538
1539 if (!R.empty()) {
1540 // Don't give errors about ambiguities in this lookup.
1541 R.suppressDiagnostics();
1542
Francois Pichete6226ae2011-11-17 03:44:24 +00001543 // During a default argument instantiation the CurContext points
1544 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1545 // function parameter list, hence add an explicit check.
1546 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1547 ActiveTemplateInstantiations.back().Kind ==
1548 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001549 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1550 bool isInstance = CurMethod &&
1551 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001552 DC == CurMethod->getParent() && !isDefaultArgument;
1553
John McCall578b69b2009-12-16 08:11:27 +00001554
1555 // Give a code modification hint to insert 'this->'.
1556 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1557 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001558 if (getLangOpts().MicrosoftMode)
1559 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001560 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001561 Diag(R.getNameLoc(), diagnostic) << Name
1562 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001563 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1564 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001565
1566
1567 CXXMethodDecl *DepMethod;
1568 if (CurMethod->getTemplatedKind() ==
1569 FunctionDecl::TK_FunctionTemplateSpecialization)
1570 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1571 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1572 else
1573 DepMethod = cast<CXXMethodDecl>(
1574 CurMethod->getInstantiatedFromMemberFunction());
1575 assert(DepMethod && "No template pattern found");
1576
1577 QualType DepThisType = DepMethod->getThisType(Context);
1578 CheckCXXThisCapture(R.getNameLoc());
1579 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1580 R.getNameLoc(), DepThisType, false);
1581 TemplateArgumentListInfo TList;
1582 if (ULE->hasExplicitTemplateArgs())
1583 ULE->copyTemplateArgumentsInto(TList);
1584
1585 CXXScopeSpec SS;
1586 SS.Adopt(ULE->getQualifierLoc());
1587 CXXDependentScopeMemberExpr *DepExpr =
1588 CXXDependentScopeMemberExpr::Create(
1589 Context, DepThis, DepThisType, true, SourceLocation(),
1590 SS.getWithLocInContext(Context),
1591 ULE->getTemplateKeywordLoc(), 0,
1592 R.getLookupNameInfo(),
1593 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1594 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001595 } else {
John McCall578b69b2009-12-16 08:11:27 +00001596 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001597 }
John McCall578b69b2009-12-16 08:11:27 +00001598
1599 // Do we really want to note all of these?
1600 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1601 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1602
Francois Pichete6226ae2011-11-17 03:44:24 +00001603 // Return true if we are inside a default argument instantiation
1604 // and the found name refers to an instance member function, otherwise
1605 // the function calling DiagnoseEmptyLookup will try to create an
1606 // implicit member call and this is wrong for default argument.
1607 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1608 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1609 return true;
1610 }
1611
John McCall578b69b2009-12-16 08:11:27 +00001612 // Tell the callee to try to recover.
1613 return false;
1614 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001615
1616 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001617 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001618
1619 // In Microsoft mode, if we are performing lookup from within a friend
1620 // function definition declared at class scope then we must set
1621 // DC to the lexical parent to be able to search into the parent
1622 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001623 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001624 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1625 DC->getLexicalParent()->isRecord())
1626 DC = DC->getLexicalParent();
1627 else
1628 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001629 }
1630
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001631 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001632 TypoCorrection Corrected;
1633 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001634 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001635 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1636 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001637 R.setLookupName(Corrected.getCorrection());
1638
Hans Wennborg701d1e72011-07-12 08:45:31 +00001639 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001640 if (Corrected.isOverloaded()) {
1641 OverloadCandidateSet OCS(R.getNameLoc());
1642 OverloadCandidateSet::iterator Best;
1643 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1644 CDEnd = Corrected.end();
1645 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001646 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001647 dyn_cast<FunctionTemplateDecl>(*CD))
1648 AddTemplateOverloadCandidate(
1649 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001650 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001651 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1652 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1653 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001654 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001655 }
1656 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1657 case OR_Success:
1658 ND = Best->Function;
1659 break;
1660 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001661 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001662 }
1663 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001664 R.addDecl(ND);
1665 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001666 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001667 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1668 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001669 else
1670 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001671 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001672 << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00001673 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1674 CorrectedStr);
Ted Kremenek63631bd2013-02-21 21:40:44 +00001675
Ted Kremenek94f3f542013-02-21 22:10:49 +00001676 unsigned diag = isa<ImplicitParamDecl>(ND)
1677 ? diag::note_implicit_param_decl
1678 : diag::note_previous_decl;
1679
1680 Diag(ND->getLocation(), diag)
1681 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001682
1683 // Tell the callee to try to recover.
1684 return false;
1685 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001686
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001687 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001688 // FIXME: If we ended up with a typo for a type name or
1689 // Objective-C class name, we're in trouble because the parser
1690 // is in the wrong place to recover. Suggest the typo
1691 // correction, but don't make it a fix-it since we're not going
1692 // to recover well anyway.
1693 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001694 Diag(R.getNameLoc(), diagnostic_suggest)
1695 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001696 else
1697 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001698 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001699 << SS.getRange();
1700
1701 // Don't try to recover; it won't work.
1702 return true;
1703 }
1704 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001705 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001706 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001707 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001708 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001709 else
Douglas Gregord203a162010-01-01 00:15:04 +00001710 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001711 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001712 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001713 return true;
1714 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001715 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001716 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001717
1718 // Emit a special diagnostic for failed member lookups.
1719 // FIXME: computing the declaration context might fail here (?)
1720 if (!SS.isEmpty()) {
1721 Diag(R.getNameLoc(), diag::err_no_member)
1722 << Name << computeDeclContext(SS, false)
1723 << SS.getRange();
1724 return true;
1725 }
1726
John McCall578b69b2009-12-16 08:11:27 +00001727 // Give up, we can't recover.
1728 Diag(R.getNameLoc(), diagnostic) << Name;
1729 return true;
1730}
1731
John McCall60d7b3a2010-08-24 06:29:42 +00001732ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001733 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001734 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001735 UnqualifiedId &Id,
1736 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001737 bool IsAddressOfOperand,
1738 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001739 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001740 "cannot be direct & operand and have a trailing lparen");
1741
1742 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001743 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001744
John McCall129e2df2009-11-30 22:42:35 +00001745 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001746
1747 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001748 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001749 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001750 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001751
Abramo Bagnara25777432010-08-11 22:01:17 +00001752 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001753 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001754 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001755
John McCallf7a1a742009-11-24 19:00:30 +00001756 // C++ [temp.dep.expr]p3:
1757 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001758 // -- an identifier that was declared with a dependent type,
1759 // (note: handled after lookup)
1760 // -- a template-id that is dependent,
1761 // (note: handled in BuildTemplateIdExpr)
1762 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001763 // -- a nested-name-specifier that contains a class-name that
1764 // names a dependent type.
1765 // Determine whether this is a member of an unknown specialization;
1766 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001767 bool DependentID = false;
1768 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1769 Name.getCXXNameType()->isDependentType()) {
1770 DependentID = true;
1771 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001772 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001773 if (RequireCompleteDeclContext(SS, DC))
1774 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001775 } else {
1776 DependentID = true;
1777 }
1778 }
1779
Chris Lattner337e5502011-02-18 01:27:55 +00001780 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001781 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1782 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001783
John McCallf7a1a742009-11-24 19:00:30 +00001784 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001785 LookupResult R(*this, NameInfo,
1786 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1787 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001788 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001789 // Lookup the template name again to correctly establish the context in
1790 // which it was found. This is really unfortunate as we already did the
1791 // lookup to determine that it was a template name in the first place. If
1792 // this becomes a performance hit, we can work harder to preserve those
1793 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001794 bool MemberOfUnknownSpecialization;
1795 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1796 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001797
1798 if (MemberOfUnknownSpecialization ||
1799 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001800 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1801 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001802 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001803 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001804 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001806 // If the result might be in a dependent base class, this is a dependent
1807 // id-expression.
1808 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001809 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1810 IsAddressOfOperand, TemplateArgs);
1811
John McCallf7a1a742009-11-24 19:00:30 +00001812 // If this reference is in an Objective-C method, then we need to do
1813 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001814 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001815 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001816 if (E.isInvalid())
1817 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Chris Lattner337e5502011-02-18 01:27:55 +00001819 if (Expr *Ex = E.takeAs<Expr>())
1820 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001821 }
Chris Lattner8a934232008-03-31 00:36:02 +00001822 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001823
John McCallf7a1a742009-11-24 19:00:30 +00001824 if (R.isAmbiguous())
1825 return ExprError();
1826
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001827 // Determine whether this name might be a candidate for
1828 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001829 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001830
John McCallf7a1a742009-11-24 19:00:30 +00001831 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001833 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001834 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001835 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1836 if (D) R.addDecl(D);
1837 }
1838
1839 // If this name wasn't predeclared and if this is not a function
1840 // call, diagnose the problem.
1841 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001842
1843 // In Microsoft mode, if we are inside a template class member function
1844 // and we can't resolve an identifier then assume the identifier is type
1845 // dependent. The goal is to postpone name lookup to instantiation time
1846 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001847 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001848 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001849 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1850 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001851
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001852 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001853 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001854 return ExprError();
1855
1856 assert(!R.empty() &&
1857 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001858
1859 // If we found an Objective-C instance variable, let
1860 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001861 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001862 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1863 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001864 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001865 // In a hopelessly buggy code, Objective-C instance variable
1866 // lookup fails and no expression will be built to reference it.
1867 if (!E.isInvalid() && !E.get())
1868 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001869 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001870 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 }
1872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
John McCallf7a1a742009-11-24 19:00:30 +00001874 // This is guaranteed from this point on.
1875 assert(!R.empty() || ADL);
1876
John McCallaa81e162009-12-01 22:10:20 +00001877 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001878 // C++ [class.mfct.non-static]p3:
1879 // When an id-expression that is not part of a class member access
1880 // syntax and not used to form a pointer to member is used in the
1881 // body of a non-static member function of class X, if name lookup
1882 // resolves the name in the id-expression to a non-static non-type
1883 // member of some class C, the id-expression is transformed into a
1884 // class member access expression using (*this) as the
1885 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001886 //
1887 // But we don't actually need to do this for '&' operands if R
1888 // resolved to a function or overloaded function set, because the
1889 // expression is ill-formed if it actually works out to be a
1890 // non-static member function:
1891 //
1892 // C++ [expr.ref]p4:
1893 // Otherwise, if E1.E2 refers to a non-static member function. . .
1894 // [t]he expression can be used only as the left-hand operand of a
1895 // member function call.
1896 //
1897 // There are other safeguards against such uses, but it's important
1898 // to get this right here so that we don't end up making a
1899 // spuriously dependent expression if we're inside a dependent
1900 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001901 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001902 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001903 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001904 MightBeImplicitMember = true;
1905 else if (!SS.isEmpty())
1906 MightBeImplicitMember = false;
1907 else if (R.isOverloadedResult())
1908 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001909 else if (R.isUnresolvableResult())
1910 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001911 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001912 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1913 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001914
1915 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001916 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1917 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001918 }
1919
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001920 if (TemplateArgs || TemplateKWLoc.isValid())
1921 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001922
John McCallf7a1a742009-11-24 19:00:30 +00001923 return BuildDeclarationNameExpr(SS, R, ADL);
1924}
1925
John McCall129e2df2009-11-30 22:42:35 +00001926/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1927/// declaration name, generally during template instantiation.
1928/// There's a large number of things which don't need to be done along
1929/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001930ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001931Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Richard Smithefeeccf2012-10-21 03:28:35 +00001932 const DeclarationNameInfo &NameInfo,
1933 bool IsAddressOfOperand) {
Richard Smith713c2872012-10-23 19:56:01 +00001934 DeclContext *DC = computeDeclContext(SS, false);
1935 if (!DC)
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001936 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1937 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001938
John McCall77bb1aa2010-05-01 00:40:08 +00001939 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001940 return ExprError();
1941
Abramo Bagnara25777432010-08-11 22:01:17 +00001942 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001943 LookupQualifiedName(R, DC);
1944
1945 if (R.isAmbiguous())
1946 return ExprError();
1947
Richard Smith713c2872012-10-23 19:56:01 +00001948 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1949 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1950 NameInfo, /*TemplateArgs=*/0);
1951
John McCallf7a1a742009-11-24 19:00:30 +00001952 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001953 Diag(NameInfo.getLoc(), diag::err_no_member)
1954 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001955 return ExprError();
1956 }
1957
Richard Smithefeeccf2012-10-21 03:28:35 +00001958 // Defend against this resolving to an implicit member access. We usually
1959 // won't get here if this might be a legitimate a class member (we end up in
1960 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1961 // a pointer-to-member or in an unevaluated context in C++11.
1962 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1963 return BuildPossibleImplicitMemberExpr(SS,
1964 /*TemplateKWLoc=*/SourceLocation(),
1965 R, /*TemplateArgs=*/0);
1966
1967 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCallf7a1a742009-11-24 19:00:30 +00001968}
1969
1970/// LookupInObjCMethod - The parser has read a name in, and Sema has
1971/// detected that we're currently inside an ObjC method. Perform some
1972/// additional lookup.
1973///
1974/// Ideally, most of this would be done by lookup, but there's
1975/// actually quite a lot of extra work involved.
1976///
1977/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001978ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001979Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001980 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001981 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001982 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Fariborz Jahanian0dc4ff22013-02-18 17:22:23 +00001983
1984 // Check for error condition which is already reported.
1985 if (!CurMethod)
1986 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001987
John McCallf7a1a742009-11-24 19:00:30 +00001988 // There are two cases to handle here. 1) scoped lookup could have failed,
1989 // in which case we should look for an ivar. 2) scoped lookup could have
1990 // found a decl, but that decl is outside the current instance method (i.e.
1991 // a global variable). In these two cases, we do a lookup for an ivar with
1992 // this name, if the lookup sucedes, we replace it our current decl.
1993
1994 // If we're in a class method, we don't normally want to look for
1995 // ivars. But if we don't find anything else, and there's an
1996 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001997 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001998
1999 bool LookForIvars;
2000 if (Lookup.empty())
2001 LookForIvars = true;
2002 else if (IsClassMethod)
2003 LookForIvars = false;
2004 else
2005 LookForIvars = (Lookup.isSingleResult() &&
2006 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002007 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00002008 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002009 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002010 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00002011 ObjCIvarDecl *IV = 0;
2012 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00002013 // Diagnose using an ivar in a class method.
2014 if (IsClassMethod)
2015 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2016 << IV->getDeclName());
2017
2018 // If we're referencing an invalid decl, just return this as a silent
2019 // error node. The error diagnostic was already emitted on the decl.
2020 if (IV->isInvalidDecl())
2021 return ExprError();
2022
2023 // Check if referencing a field with __attribute__((deprecated)).
2024 if (DiagnoseUseOfDecl(IV, Loc))
2025 return ExprError();
2026
2027 // Diagnose the use of an ivar outside of the declaring class.
2028 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00002029 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002030 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00002031 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2032
2033 // FIXME: This should use a new expr for a direct reference, don't
2034 // turn this into Self->ivar, just return a BareIVarExpr or something.
2035 IdentifierInfo &II = Context.Idents.get("self");
2036 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002037 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00002038 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00002039 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002040 SourceLocation TemplateKWLoc;
2041 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002042 SelfName, false, false);
2043 if (SelfExpr.isInvalid())
2044 return ExprError();
2045
John Wiegley429bb272011-04-08 18:41:53 +00002046 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2047 if (SelfExpr.isInvalid())
2048 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002049
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +00002050 MarkAnyDeclReferenced(Loc, IV, true);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002051
2052 ObjCMethodFamily MF = CurMethod->getMethodFamily();
Fariborz Jahanian26202292013-02-14 19:07:19 +00002053 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2054 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002055 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00002056
2057 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2058 Loc,
2059 SelfExpr.take(),
2060 true, true);
2061
2062 if (getLangOpts().ObjCAutoRefCount) {
2063 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2064 DiagnosticsEngine::Level Level =
2065 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2066 if (Level != DiagnosticsEngine::Ignored)
2067 getCurFunction()->recordUseOfWeak(Result);
2068 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002069 if (CurContext->isClosure())
2070 Diag(Loc, diag::warn_implicitly_retains_self)
2071 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002072 }
2073
2074 return Owned(Result);
John McCallf7a1a742009-11-24 19:00:30 +00002075 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002076 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002077 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002078 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2079 ObjCInterfaceDecl *ClassDeclared;
2080 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2081 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002082 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002083 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2084 }
John McCallf7a1a742009-11-24 19:00:30 +00002085 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002086 } else if (Lookup.isSingleResult() &&
2087 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2088 // If accessing a stand-alone ivar in a class method, this is an error.
2089 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2090 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2091 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002092 }
2093
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002094 if (Lookup.empty() && II && AllowBuiltinCreation) {
2095 // FIXME. Consolidate this with similar code in LookupName.
2096 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002097 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002098 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2099 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2100 S, Lookup.isForRedeclaration(),
2101 Lookup.getNameLoc());
2102 if (D) Lookup.addDecl(D);
2103 }
2104 }
2105 }
John McCallf7a1a742009-11-24 19:00:30 +00002106 // Sentinel value saying that we didn't do anything special.
2107 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002108}
John McCallba135432009-11-21 08:51:07 +00002109
John McCall6bb80172010-03-30 21:47:33 +00002110/// \brief Cast a base object to a member's actual type.
2111///
2112/// Logically this happens in three phases:
2113///
2114/// * First we cast from the base type to the naming class.
2115/// The naming class is the class into which we were looking
2116/// when we found the member; it's the qualifier type if a
2117/// qualifier was provided, and otherwise it's the base type.
2118///
2119/// * Next we cast from the naming class to the declaring class.
2120/// If the member we found was brought into a class's scope by
2121/// a using declaration, this is that class; otherwise it's
2122/// the class declaring the member.
2123///
2124/// * Finally we cast from the declaring class to the "true"
2125/// declaring class of the member. This conversion does not
2126/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002127ExprResult
2128Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002129 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002130 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002131 NamedDecl *Member) {
2132 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2133 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002134 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002135
Douglas Gregor5fccd362010-03-03 23:55:11 +00002136 QualType DestRecordType;
2137 QualType DestType;
2138 QualType FromRecordType;
2139 QualType FromType = From->getType();
2140 bool PointerConversions = false;
2141 if (isa<FieldDecl>(Member)) {
2142 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002143
Douglas Gregor5fccd362010-03-03 23:55:11 +00002144 if (FromType->getAs<PointerType>()) {
2145 DestType = Context.getPointerType(DestRecordType);
2146 FromRecordType = FromType->getPointeeType();
2147 PointerConversions = true;
2148 } else {
2149 DestType = DestRecordType;
2150 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002151 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002152 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2153 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002154 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002155
Douglas Gregor5fccd362010-03-03 23:55:11 +00002156 DestType = Method->getThisType(Context);
2157 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002158
Douglas Gregor5fccd362010-03-03 23:55:11 +00002159 if (FromType->getAs<PointerType>()) {
2160 FromRecordType = FromType->getPointeeType();
2161 PointerConversions = true;
2162 } else {
2163 FromRecordType = FromType;
2164 DestType = DestRecordType;
2165 }
2166 } else {
2167 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002168 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002169 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002170
Douglas Gregor5fccd362010-03-03 23:55:11 +00002171 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002172 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002173
Douglas Gregor5fccd362010-03-03 23:55:11 +00002174 // If the unqualified types are the same, no conversion is necessary.
2175 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002176 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002177
John McCall6bb80172010-03-30 21:47:33 +00002178 SourceRange FromRange = From->getSourceRange();
2179 SourceLocation FromLoc = FromRange.getBegin();
2180
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002181 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002182
Douglas Gregor5fccd362010-03-03 23:55:11 +00002183 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002184 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002185 // class name.
2186 //
2187 // If the member was a qualified name and the qualified referred to a
2188 // specific base subobject type, we'll cast to that intermediate type
2189 // first and then to the object in which the member is declared. That allows
2190 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2191 //
2192 // class Base { public: int x; };
2193 // class Derived1 : public Base { };
2194 // class Derived2 : public Base { };
2195 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2196 //
2197 // void VeryDerived::f() {
2198 // x = 17; // error: ambiguous base subobjects
2199 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2200 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002201 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002202 QualType QType = QualType(Qualifier->getAsType(), 0);
2203 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2204 assert(QType->isRecordType() && "lookup done with non-record type");
2205
2206 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2207
2208 // In C++98, the qualifier type doesn't actually have to be a base
2209 // type of the object type, in which case we just ignore it.
2210 // Otherwise build the appropriate casts.
2211 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002212 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002213 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002214 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002215 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002216
Douglas Gregor5fccd362010-03-03 23:55:11 +00002217 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002218 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002219 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2220 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002221
2222 FromType = QType;
2223 FromRecordType = QRecordType;
2224
2225 // If the qualifier type was the same as the destination type,
2226 // we're done.
2227 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002228 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002229 }
2230 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002231
John McCall6bb80172010-03-30 21:47:33 +00002232 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002233
John McCall6bb80172010-03-30 21:47:33 +00002234 // If we actually found the member through a using declaration, cast
2235 // down to the using declaration's type.
2236 //
2237 // Pointer equality is fine here because only one declaration of a
2238 // class ever has member declarations.
2239 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2240 assert(isa<UsingShadowDecl>(FoundDecl));
2241 QualType URecordType = Context.getTypeDeclType(
2242 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2243
2244 // We only need to do this if the naming-class to declaring-class
2245 // conversion is non-trivial.
2246 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2247 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002248 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002249 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002250 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002251 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002252
John McCall6bb80172010-03-30 21:47:33 +00002253 QualType UType = URecordType;
2254 if (PointerConversions)
2255 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002256 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2257 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002258 FromType = UType;
2259 FromRecordType = URecordType;
2260 }
2261
2262 // We don't do access control for the conversion from the
2263 // declaring class to the true declaring class.
2264 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002265 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002266
John McCallf871d0c2010-08-07 06:22:56 +00002267 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002268 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2269 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002270 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002271 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002272
John Wiegley429bb272011-04-08 18:41:53 +00002273 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2274 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002275}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002276
John McCallf7a1a742009-11-24 19:00:30 +00002277bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002278 const LookupResult &R,
2279 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002280 // Only when used directly as the postfix-expression of a call.
2281 if (!HasTrailingLParen)
2282 return false;
2283
2284 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002285 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002286 return false;
2287
2288 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002289 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002290 return false;
2291
2292 // Turn off ADL when we find certain kinds of declarations during
2293 // normal lookup:
2294 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2295 NamedDecl *D = *I;
2296
2297 // C++0x [basic.lookup.argdep]p3:
2298 // -- a declaration of a class member
2299 // Since using decls preserve this property, we check this on the
2300 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002301 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002302 return false;
2303
2304 // C++0x [basic.lookup.argdep]p3:
2305 // -- a block-scope function declaration that is not a
2306 // using-declaration
2307 // NOTE: we also trigger this for function templates (in fact, we
2308 // don't check the decl type at all, since all other decl types
2309 // turn off ADL anyway).
2310 if (isa<UsingShadowDecl>(D))
2311 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2312 else if (D->getDeclContext()->isFunctionOrMethod())
2313 return false;
2314
2315 // C++0x [basic.lookup.argdep]p3:
2316 // -- a declaration that is neither a function or a function
2317 // template
2318 // And also for builtin functions.
2319 if (isa<FunctionDecl>(D)) {
2320 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2321
2322 // But also builtin functions.
2323 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2324 return false;
2325 } else if (!isa<FunctionTemplateDecl>(D))
2326 return false;
2327 }
2328
2329 return true;
2330}
2331
2332
John McCallba135432009-11-21 08:51:07 +00002333/// Diagnoses obvious problems with the use of the given declaration
2334/// as an expression. This is only actually called for lookups that
2335/// were not overloaded, and it doesn't promise that the declaration
2336/// will in fact be used.
2337static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002338 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002339 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2340 return true;
2341 }
2342
2343 if (isa<ObjCInterfaceDecl>(D)) {
2344 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2345 return true;
2346 }
2347
2348 if (isa<NamespaceDecl>(D)) {
2349 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2350 return true;
2351 }
2352
2353 return false;
2354}
2355
John McCall60d7b3a2010-08-24 06:29:42 +00002356ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002357Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002358 LookupResult &R,
2359 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002360 // If this is a single, fully-resolved result and we don't need ADL,
2361 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002362 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002363 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2364 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002365
2366 // We only need to check the declaration if there's exactly one
2367 // result, because in the overloaded case the results can only be
2368 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002369 if (R.isSingleResult() &&
2370 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002371 return ExprError();
2372
John McCallc373d482010-01-27 01:50:18 +00002373 // Otherwise, just build an unresolved lookup expression. Suppress
2374 // any lookup-related diagnostics; we'll hash these out later, when
2375 // we've picked a target.
2376 R.suppressDiagnostics();
2377
John McCallba135432009-11-21 08:51:07 +00002378 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002379 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002380 SS.getWithLocInContext(Context),
2381 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002382 NeedsADL, R.isOverloadedResult(),
2383 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002384
2385 return Owned(ULE);
2386}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002387
John McCallba135432009-11-21 08:51:07 +00002388/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002389ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002390Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002391 const DeclarationNameInfo &NameInfo,
2392 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002393 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002394 assert(!isa<FunctionTemplateDecl>(D) &&
2395 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002396
Abramo Bagnara25777432010-08-11 22:01:17 +00002397 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002398 if (CheckDeclInExpr(*this, Loc, D))
2399 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002400
Douglas Gregor9af2f522009-12-01 16:58:18 +00002401 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2402 // Specifically diagnose references to class templates that are missing
2403 // a template argument list.
2404 Diag(Loc, diag::err_template_decl_ref)
2405 << Template << SS.getRange();
2406 Diag(Template->getLocation(), diag::note_template_decl_here);
2407 return ExprError();
2408 }
2409
2410 // Make sure that we're referring to a value.
2411 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2412 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002413 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002414 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002415 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002416 return ExprError();
2417 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002418
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002419 // Check whether this declaration can be used. Note that we suppress
2420 // this check when we're going to perform argument-dependent lookup
2421 // on this function name, because this might not be the function
2422 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002423 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002424 return ExprError();
2425
Steve Naroffdd972f22008-09-05 22:11:13 +00002426 // Only create DeclRefExpr's for valid Decl's.
2427 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002428 return ExprError();
2429
John McCall5808ce42011-02-03 08:15:49 +00002430 // Handle members of anonymous structs and unions. If we got here,
2431 // and the reference is to a class member indirect field, then this
2432 // must be the subject of a pointer-to-member expression.
2433 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2434 if (!indirectField->isCXXClassMember())
2435 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2436 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002437
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002438 {
John McCall76a40212011-02-09 01:13:10 +00002439 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002440 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002441
2442 switch (D->getKind()) {
2443 // Ignore all the non-ValueDecl kinds.
2444#define ABSTRACT_DECL(kind)
2445#define VALUE(type, base)
2446#define DECL(type, base) \
2447 case Decl::type:
2448#include "clang/AST/DeclNodes.inc"
2449 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002450
2451 // These shouldn't make it here.
2452 case Decl::ObjCAtDefsField:
2453 case Decl::ObjCIvar:
2454 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002455
2456 // Enum constants are always r-values and never references.
2457 // Unresolved using declarations are dependent.
2458 case Decl::EnumConstant:
2459 case Decl::UnresolvedUsingValue:
2460 valueKind = VK_RValue;
2461 break;
2462
2463 // Fields and indirect fields that got here must be for
2464 // pointer-to-member expressions; we just call them l-values for
2465 // internal consistency, because this subexpression doesn't really
2466 // exist in the high-level semantics.
2467 case Decl::Field:
2468 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002469 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002470 "building reference to field in C?");
2471
2472 // These can't have reference type in well-formed programs, but
2473 // for internal consistency we do this anyway.
2474 type = type.getNonReferenceType();
2475 valueKind = VK_LValue;
2476 break;
2477
2478 // Non-type template parameters are either l-values or r-values
2479 // depending on the type.
2480 case Decl::NonTypeTemplateParm: {
2481 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2482 type = reftype->getPointeeType();
2483 valueKind = VK_LValue; // even if the parameter is an r-value reference
2484 break;
2485 }
2486
2487 // For non-references, we need to strip qualifiers just in case
2488 // the template parameter was declared as 'const int' or whatever.
2489 valueKind = VK_RValue;
2490 type = type.getUnqualifiedType();
2491 break;
2492 }
2493
2494 case Decl::Var:
2495 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002496 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002497 !type.hasQualifiers() &&
2498 type->isVoidType()) {
2499 valueKind = VK_RValue;
2500 break;
2501 }
2502 // fallthrough
2503
2504 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002505 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002506 // These are always l-values.
2507 valueKind = VK_LValue;
2508 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002509
Douglas Gregor68932842012-02-18 05:51:20 +00002510 // FIXME: Does the addition of const really only apply in
2511 // potentially-evaluated contexts? Since the variable isn't actually
2512 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002513 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002514 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2515 if (!CapturedType.isNull())
2516 type = CapturedType;
2517 }
2518
John McCall76a40212011-02-09 01:13:10 +00002519 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002520 }
2521
John McCall76a40212011-02-09 01:13:10 +00002522 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002523 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2524 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2525 type = Context.BuiltinFnTy;
2526 valueKind = VK_RValue;
2527 break;
2528 }
2529 }
2530
John McCall755d8492011-04-12 00:42:48 +00002531 const FunctionType *fty = type->castAs<FunctionType>();
2532
2533 // If we're referring to a function with an __unknown_anytype
2534 // result type, make the entire expression __unknown_anytype.
2535 if (fty->getResultType() == Context.UnknownAnyTy) {
2536 type = Context.UnknownAnyTy;
2537 valueKind = VK_RValue;
2538 break;
2539 }
2540
John McCall76a40212011-02-09 01:13:10 +00002541 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002542 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002543 valueKind = VK_LValue;
2544 break;
2545 }
2546
2547 // C99 DR 316 says that, if a function type comes from a
2548 // function definition (without a prototype), that type is only
2549 // used for checking compatibility. Therefore, when referencing
2550 // the function, we pretend that we don't have the full function
2551 // type.
John McCall755d8492011-04-12 00:42:48 +00002552 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2553 isa<FunctionProtoType>(fty))
2554 type = Context.getFunctionNoProtoType(fty->getResultType(),
2555 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002556
2557 // Functions are r-values in C.
2558 valueKind = VK_RValue;
2559 break;
2560 }
2561
2562 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002563 // If we're referring to a method with an __unknown_anytype
2564 // result type, make the entire expression __unknown_anytype.
2565 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002566 if (const FunctionProtoType *proto
2567 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002568 if (proto->getResultType() == Context.UnknownAnyTy) {
2569 type = Context.UnknownAnyTy;
2570 valueKind = VK_RValue;
2571 break;
2572 }
2573
John McCall76a40212011-02-09 01:13:10 +00002574 // C++ methods are l-values if static, r-values if non-static.
2575 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2576 valueKind = VK_LValue;
2577 break;
2578 }
2579 // fallthrough
2580
2581 case Decl::CXXConversion:
2582 case Decl::CXXDestructor:
2583 case Decl::CXXConstructor:
2584 valueKind = VK_RValue;
2585 break;
2586 }
2587
2588 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2589 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002590}
2591
John McCall755d8492011-04-12 00:42:48 +00002592ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002593 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002594
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002596 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002597 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2598 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002599 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002600 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002601 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002602
Chris Lattnerfa28b302008-01-12 08:14:25 +00002603 // Pre-defined identifiers are of type char[x], where x is the length of the
2604 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Anders Carlsson3a082d82009-09-08 18:24:21 +00002606 Decl *currentDecl = getCurFunctionOrMethodDecl();
Benjamin Kramer42427402012-12-06 15:42:21 +00002607 // Blocks and lambdas can occur at global scope. Don't emit a warning.
2608 if (!currentDecl) {
2609 if (const BlockScopeInfo *BSI = getCurBlock())
2610 currentDecl = BSI->TheDecl;
2611 else if (const LambdaScopeInfo *LSI = getCurLambda())
2612 currentDecl = LSI->CallOperator;
2613 }
2614
Anders Carlsson3a082d82009-09-08 18:24:21 +00002615 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002616 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002617 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002618 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002619
Anders Carlsson773f3972009-09-11 01:22:35 +00002620 QualType ResTy;
2621 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2622 ResTy = Context.DependentTy;
2623 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002624 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002625
Anders Carlsson773f3972009-09-11 01:22:35 +00002626 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002627 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002628 ResTy = Context.WCharTy.withConst();
2629 else
2630 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002631 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2632 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002633 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002634}
2635
Richard Smith36f5cfe2012-03-09 08:00:36 +00002636ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002637 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002638 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002639 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002640 if (Invalid)
2641 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002642
Benjamin Kramerddeea562010-02-27 13:44:12 +00002643 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002644 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002646 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002647
Chris Lattnere8337df2009-12-30 21:19:39 +00002648 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002649 if (Literal.isWide())
2650 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002651 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002652 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002653 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002654 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002655 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002656 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002657 else
2658 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002659
Douglas Gregor5cee1192011-07-27 05:40:30 +00002660 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2661 if (Literal.isWide())
2662 Kind = CharacterLiteral::Wide;
2663 else if (Literal.isUTF16())
2664 Kind = CharacterLiteral::UTF16;
2665 else if (Literal.isUTF32())
2666 Kind = CharacterLiteral::UTF32;
2667
Richard Smithdd66be72012-03-08 01:34:56 +00002668 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2669 Tok.getLocation());
2670
2671 if (Literal.getUDSuffix().empty())
2672 return Owned(Lit);
2673
2674 // We're building a user-defined literal.
2675 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2676 SourceLocation UDSuffixLoc =
2677 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2678
Richard Smith36f5cfe2012-03-09 08:00:36 +00002679 // Make sure we're allowed user-defined literals here.
2680 if (!UDLScope)
2681 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2682
Richard Smithdd66be72012-03-08 01:34:56 +00002683 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2684 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002685 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2686 llvm::makeArrayRef(&Lit, 1),
2687 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002688}
2689
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002690ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2691 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2692 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2693 Context.IntTy, Loc));
2694}
2695
Richard Smithb453ad32012-03-08 08:45:32 +00002696static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2697 QualType Ty, SourceLocation Loc) {
2698 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2699
2700 using llvm::APFloat;
2701 APFloat Val(Format);
2702
2703 APFloat::opStatus result = Literal.GetFloatValue(Val);
2704
2705 // Overflow is always an error, but underflow is only an error if
2706 // we underflowed to zero (APFloat reports denormals as underflow).
2707 if ((result & APFloat::opOverflow) ||
2708 ((result & APFloat::opUnderflow) && Val.isZero())) {
2709 unsigned diagnostic;
2710 SmallString<20> buffer;
2711 if (result & APFloat::opOverflow) {
2712 diagnostic = diag::warn_float_overflow;
2713 APFloat::getLargest(Format).toString(buffer);
2714 } else {
2715 diagnostic = diag::warn_float_underflow;
2716 APFloat::getSmallest(Format).toString(buffer);
2717 }
2718
2719 S.Diag(Loc, diagnostic)
2720 << Ty
2721 << StringRef(buffer.data(), buffer.size());
2722 }
2723
2724 bool isExact = (result == APFloat::opOK);
2725 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2726}
2727
Richard Smith36f5cfe2012-03-09 08:00:36 +00002728ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002729 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002730 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002731 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002732 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002733 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 }
Ted Kremenek28396602009-01-13 23:19:12 +00002735
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002736 SmallString<128> SpellingBuffer;
2737 // NumericLiteralParser wants to overread by one character. Add padding to
2738 // the buffer in case the token is copied to the buffer. If getSpelling()
2739 // returns a StringRef to the memory buffer, it should have a null char at
2740 // the EOF, so it is also safe.
2741 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002742
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002744 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002745 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002746 if (Invalid)
2747 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002748
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002749 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002750 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002751 return ExprError();
2752
Richard Smithb453ad32012-03-08 08:45:32 +00002753 if (Literal.hasUDSuffix()) {
2754 // We're building a user-defined literal.
2755 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2756 SourceLocation UDSuffixLoc =
2757 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2758
Richard Smith36f5cfe2012-03-09 08:00:36 +00002759 // Make sure we're allowed user-defined literals here.
2760 if (!UDLScope)
2761 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002762
Richard Smith36f5cfe2012-03-09 08:00:36 +00002763 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002764 if (Literal.isFloatingLiteral()) {
2765 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2766 // long double, the literal is treated as a call of the form
2767 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002768 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002769 } else {
2770 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2771 // unsigned long long, the literal is treated as a call of the form
2772 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002773 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002774 }
2775
Richard Smith36f5cfe2012-03-09 08:00:36 +00002776 DeclarationName OpName =
2777 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2778 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2779 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2780
2781 // Perform literal operator lookup to determine if we're building a raw
2782 // literal or a cooked one.
2783 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2784 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2785 /*AllowRawAndTemplate*/true)) {
2786 case LOLR_Error:
2787 return ExprError();
2788
2789 case LOLR_Cooked: {
2790 Expr *Lit;
2791 if (Literal.isFloatingLiteral()) {
2792 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2793 } else {
2794 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2795 if (Literal.GetIntegerValue(ResultVal))
2796 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2797 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2798 Tok.getLocation());
2799 }
2800 return BuildLiteralOperatorCall(R, OpNameInfo,
2801 llvm::makeArrayRef(&Lit, 1),
2802 Tok.getLocation());
2803 }
2804
2805 case LOLR_Raw: {
2806 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2807 // literal is treated as a call of the form
2808 // operator "" X ("n")
2809 SourceLocation TokLoc = Tok.getLocation();
2810 unsigned Length = Literal.getUDSuffixOffset();
2811 QualType StrTy = Context.getConstantArrayType(
Richard Smith4ea6a642013-01-23 23:38:20 +00002812 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
Richard Smith36f5cfe2012-03-09 08:00:36 +00002813 ArrayType::Normal, 0);
2814 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002815 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002816 /*Pascal*/false, StrTy, &TokLoc, 1);
2817 return BuildLiteralOperatorCall(R, OpNameInfo,
2818 llvm::makeArrayRef(&Lit, 1), TokLoc);
2819 }
2820
2821 case LOLR_Template:
2822 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2823 // template), L is treated as a call fo the form
2824 // operator "" X <'c1', 'c2', ... 'ck'>()
2825 // where n is the source character sequence c1 c2 ... ck.
2826 TemplateArgumentListInfo ExplicitArgs;
2827 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2828 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2829 llvm::APSInt Value(CharBits, CharIsUnsigned);
2830 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002831 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002832 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002833 TemplateArgumentLocInfo ArgInfo;
2834 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2835 }
2836 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2837 Tok.getLocation(), &ExplicitArgs);
2838 }
2839
2840 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002841 }
2842
Chris Lattner5d661452007-08-26 03:42:43 +00002843 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002844
Chris Lattner5d661452007-08-26 03:42:43 +00002845 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002846 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002847 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002848 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002849 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002850 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002851 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002852 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002853
Richard Smithb453ad32012-03-08 08:45:32 +00002854 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002855
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002856 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002857 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002858 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002859 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002860 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002861 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002862 }
2863 }
Chris Lattner5d661452007-08-26 03:42:43 +00002864 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002865 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002866 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002867 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002868
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002869 // 'long long' is a C99 or C++11 feature.
2870 if (!getLangOpts().C99 && Literal.isLongLong) {
2871 if (getLangOpts().CPlusPlus)
2872 Diag(Tok.getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00002873 getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002874 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2875 else
2876 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2877 }
Neil Boothb9449512007-08-29 22:00:19 +00002878
Reid Spencer5f016e22007-07-11 17:01:13 +00002879 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002880 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2881 // The microsoft literal suffix extensions support 128-bit literals, which
2882 // may be wider than [u]intmax_t.
Richard Smith84268902012-11-29 05:41:51 +00002883 // FIXME: Actually, they don't. We seem to have accidentally invented the
2884 // i128 suffix.
2885 if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2886 PP.getTargetInfo().hasInt128Type())
Stephen Canonb9e05f12012-05-03 22:49:43 +00002887 MaxWidth = 128;
2888 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002889
Reid Spencer5f016e22007-07-11 17:01:13 +00002890 if (Literal.GetIntegerValue(ResultVal)) {
2891 // If this value didn't fit into uintmax_t, warn and force to ull.
2892 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002893 Ty = Context.UnsignedLongLongTy;
2894 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002895 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 } else {
2897 // If this value fits into a ULL, try to figure out what else it fits into
2898 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002899
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2901 // be an unsigned int.
2902 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2903
2904 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002905 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002906 if (!Literal.isLong && !Literal.isLongLong) {
2907 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002908 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002909
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 // Does it fit in a unsigned int?
2911 if (ResultVal.isIntN(IntSize)) {
2912 // Does it fit in a signed int?
2913 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002914 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002916 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002917 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002918 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002920
Reid Spencer5f016e22007-07-11 17:01:13 +00002921 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002922 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002923 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002924
Reid Spencer5f016e22007-07-11 17:01:13 +00002925 // Does it fit in a unsigned long?
2926 if (ResultVal.isIntN(LongSize)) {
2927 // Does it fit in a signed long?
2928 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002929 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002930 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002931 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002932 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002933 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002934 }
2935
Stephen Canonb9e05f12012-05-03 22:49:43 +00002936 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002937 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002938 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002939
Reid Spencer5f016e22007-07-11 17:01:13 +00002940 // Does it fit in a unsigned long long?
2941 if (ResultVal.isIntN(LongLongSize)) {
2942 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002943 // To be compatible with MSVC, hex integer literals ending with the
2944 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002945 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002946 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002947 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002948 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002949 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002950 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002951 }
2952 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002953
2954 // If it doesn't fit in unsigned long long, and we're using Microsoft
2955 // extensions, then its a 128-bit integer literal.
Richard Smith84268902012-11-29 05:41:51 +00002956 if (Ty.isNull() && Literal.isMicrosoftInteger &&
2957 PP.getTargetInfo().hasInt128Type()) {
Stephen Canonb9e05f12012-05-03 22:49:43 +00002958 if (Literal.isUnsigned)
2959 Ty = Context.UnsignedInt128Ty;
2960 else
2961 Ty = Context.Int128Ty;
2962 Width = 128;
2963 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002964
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 // If we still couldn't decide a type, we probably have something that
2966 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002967 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002969 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002970 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002971 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002972
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002973 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002974 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002976 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002977 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002978
Chris Lattner5d661452007-08-26 03:42:43 +00002979 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2980 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002981 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002982 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002983
2984 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002985}
2986
Richard Trieuccd891a2011-09-09 01:45:06 +00002987ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002988 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002989 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002990}
2991
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002992static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2993 SourceLocation Loc,
2994 SourceRange ArgRange) {
2995 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2996 // scalar or vector data type argument..."
2997 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2998 // type (C99 6.2.5p18) or void.
2999 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3000 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3001 << T << ArgRange;
3002 return true;
3003 }
3004
3005 assert((T->isVoidType() || !T->isIncompleteType()) &&
3006 "Scalar types should always be complete");
3007 return false;
3008}
3009
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003010static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3011 SourceLocation Loc,
3012 SourceRange ArgRange,
3013 UnaryExprOrTypeTrait TraitKind) {
3014 // C99 6.5.3.4p1:
3015 if (T->isFunctionType()) {
3016 // alignof(function) is allowed as an extension.
3017 if (TraitKind == UETT_SizeOf)
3018 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3019 return false;
3020 }
3021
3022 // Allow sizeof(void)/alignof(void) as an extension.
3023 if (T->isVoidType()) {
3024 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3025 return false;
3026 }
3027
3028 return true;
3029}
3030
3031static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3032 SourceLocation Loc,
3033 SourceRange ArgRange,
3034 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00003035 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3036 // runtime doesn't allow it.
3037 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003038 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3039 << T << (TraitKind == UETT_SizeOf)
3040 << ArgRange;
3041 return true;
3042 }
3043
3044 return false;
3045}
3046
Chandler Carruth9d342d02011-05-26 08:53:10 +00003047/// \brief Check the constrains on expression operands to unary type expression
3048/// and type traits.
3049///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003050/// Completes any types necessary and validates the constraints on the operand
3051/// expression. The logic mostly mirrors the type-based overload, but may modify
3052/// the expression as it completes the type for that expression through template
3053/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00003054bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003055 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003056 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003057
3058 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3059 // the result is the size of the referenced type."
3060 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3061 // result shall be the alignment of the referenced type."
3062 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3063 ExprTy = Ref->getPointeeType();
3064
3065 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003066 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3067 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003068
3069 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003070 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3071 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003072 return false;
3073
Richard Trieuccd891a2011-09-09 01:45:06 +00003074 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00003075 diag::err_sizeof_alignof_incomplete_type,
3076 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003077 return true;
3078
3079 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003080 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003081 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3082 ExprTy = Ref->getPointeeType();
3083
Richard Trieuccd891a2011-09-09 01:45:06 +00003084 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3085 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003086 return true;
3087
Nico Webercf739922011-06-15 02:47:03 +00003088 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003089 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003090 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3091 QualType OType = PVD->getOriginalType();
3092 QualType Type = PVD->getType();
3093 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003094 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003095 << Type << OType;
3096 Diag(PVD->getLocation(), diag::note_declared_at);
3097 }
3098 }
3099 }
3100 }
3101
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003102 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003103}
3104
3105/// \brief Check the constraints on operands to unary expression and type
3106/// traits.
3107///
3108/// This will complete any types necessary, and validate the various constraints
3109/// on those operands.
3110///
Reid Spencer5f016e22007-07-11 17:01:13 +00003111/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003112/// C99 6.3.2.1p[2-4] all state:
3113/// Except when it is the operand of the sizeof operator ...
3114///
3115/// C++ [expr.sizeof]p4
3116/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3117/// standard conversions are not applied to the operand of sizeof.
3118///
3119/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003120bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003121 SourceLocation OpLoc,
3122 SourceRange ExprRange,
3123 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003124 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003125 return false;
3126
Sebastian Redl5d484e82009-11-23 17:18:46 +00003127 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3128 // the result is the size of the referenced type."
3129 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3130 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003131 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3132 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003133
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003134 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003135 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003136
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003137 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003138 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003139 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003140 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Richard Trieuccd891a2011-09-09 01:45:06 +00003142 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003143 diag::err_sizeof_alignof_incomplete_type,
3144 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003145 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Richard Trieuccd891a2011-09-09 01:45:06 +00003147 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003148 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003149 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003150
Chris Lattner1efaa952009-04-24 00:30:45 +00003151 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003152}
3153
Chandler Carruth9d342d02011-05-26 08:53:10 +00003154static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003155 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003156
Mike Stump1eb44332009-09-09 15:08:12 +00003157 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003158 if (isa<DeclRefExpr>(E))
3159 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003160
3161 // Cannot know anything else if the expression is dependent.
3162 if (E->isTypeDependent())
3163 return false;
3164
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003165 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003166 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3167 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003168 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003169 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003170
3171 // Alignment of a field access is always okay, so long as it isn't a
3172 // bit-field.
3173 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003174 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003175 return false;
3176
Chandler Carruth9d342d02011-05-26 08:53:10 +00003177 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003178}
3179
Chandler Carruth9d342d02011-05-26 08:53:10 +00003180bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003181 E = E->IgnoreParens();
3182
3183 // Cannot know anything else if the expression is dependent.
3184 if (E->isTypeDependent())
3185 return false;
3186
Chandler Carruth9d342d02011-05-26 08:53:10 +00003187 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003188}
3189
Douglas Gregorba498172009-03-13 21:01:28 +00003190/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003191ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003192Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3193 SourceLocation OpLoc,
3194 UnaryExprOrTypeTrait ExprKind,
3195 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003196 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003197 return ExprError();
3198
John McCalla93c9342009-12-07 02:54:59 +00003199 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003200
Douglas Gregorba498172009-03-13 21:01:28 +00003201 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003202 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003203 return ExprError();
3204
3205 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003206 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3207 Context.getSizeType(),
3208 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003209}
3210
3211/// \brief Build a sizeof or alignof expression given an expression
3212/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003213ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003214Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3215 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003216 ExprResult PE = CheckPlaceholderExpr(E);
3217 if (PE.isInvalid())
3218 return ExprError();
3219
3220 E = PE.get();
3221
Douglas Gregorba498172009-03-13 21:01:28 +00003222 // Verify that the operand is valid.
3223 bool isInvalid = false;
3224 if (E->isTypeDependent()) {
3225 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003226 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003227 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003228 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003229 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003230 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003231 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003232 isInvalid = true;
3233 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003234 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003235 }
3236
3237 if (isInvalid)
3238 return ExprError();
3239
Eli Friedman71b8fb52012-01-21 01:01:51 +00003240 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Krameraccaf192012-11-14 15:08:31 +00003241 PE = TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +00003242 if (PE.isInvalid()) return ExprError();
3243 E = PE.take();
3244 }
3245
Douglas Gregorba498172009-03-13 21:01:28 +00003246 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003247 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003248 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003249 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003250}
3251
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003252/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3253/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003254/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003255ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003256Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003257 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003258 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003259 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003260 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003261
Richard Trieuccd891a2011-09-09 01:45:06 +00003262 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003263 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003264 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003265 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003266 }
Sebastian Redl05189992008-11-11 17:56:53 +00003267
Douglas Gregorba498172009-03-13 21:01:28 +00003268 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003269 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003270 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003271}
3272
John Wiegley429bb272011-04-08 18:41:53 +00003273static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003274 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003275 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003276 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003277
John McCallf6a16482010-12-04 03:47:34 +00003278 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003279 if (V.get()->getObjectKind() != OK_Ordinary) {
3280 V = S.DefaultLvalueConversion(V.take());
3281 if (V.isInvalid())
3282 return QualType();
3283 }
John McCallf6a16482010-12-04 03:47:34 +00003284
Chris Lattnercc26ed72007-08-26 05:39:26 +00003285 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003286 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003287 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003288
Chris Lattnercc26ed72007-08-26 05:39:26 +00003289 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003290 if (V.get()->getType()->isArithmeticType())
3291 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003292
John McCall2cd11fe2010-10-12 02:09:17 +00003293 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003294 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003295 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003296 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003297 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003298 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003299 }
3300
Chris Lattnercc26ed72007-08-26 05:39:26 +00003301 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003302 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003303 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003304 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003305}
3306
3307
Reid Spencer5f016e22007-07-11 17:01:13 +00003308
John McCall60d7b3a2010-08-24 06:29:42 +00003309ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003310Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003311 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003312 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003313 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003314 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003315 case tok::plusplus: Opc = UO_PostInc; break;
3316 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003317 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003318
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003319 // Since this might is a postfix expression, get rid of ParenListExprs.
3320 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3321 if (Result.isInvalid()) return ExprError();
3322 Input = Result.take();
3323
John McCall9ae2f072010-08-23 23:25:46 +00003324 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003325}
3326
John McCall1503f0d2012-07-31 05:14:30 +00003327/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3328///
3329/// \return true on error
3330static bool checkArithmeticOnObjCPointer(Sema &S,
3331 SourceLocation opLoc,
3332 Expr *op) {
3333 assert(op->getType()->isObjCObjectPointerType());
3334 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3335 return false;
3336
3337 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3338 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3339 << op->getSourceRange();
3340 return true;
3341}
3342
John McCall60d7b3a2010-08-24 06:29:42 +00003343ExprResult
John McCall7a534b92013-03-04 01:30:55 +00003344Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3345 Expr *idx, SourceLocation rbLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003346 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall7a534b92013-03-04 01:30:55 +00003347 if (isa<ParenListExpr>(base)) {
3348 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3349 if (result.isInvalid()) return ExprError();
3350 base = result.take();
3351 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00003352
John McCall7a534b92013-03-04 01:30:55 +00003353 // Handle any non-overload placeholder types in the base and index
3354 // expressions. We can't handle overloads here because the other
3355 // operand might be an overloadable type, in which case the overload
3356 // resolution for the operator overload should get the first crack
3357 // at the overload.
3358 if (base->getType()->isNonOverloadPlaceholderType()) {
3359 ExprResult result = CheckPlaceholderExpr(base);
3360 if (result.isInvalid()) return ExprError();
3361 base = result.take();
3362 }
3363 if (idx->getType()->isNonOverloadPlaceholderType()) {
3364 ExprResult result = CheckPlaceholderExpr(idx);
3365 if (result.isInvalid()) return ExprError();
3366 idx = result.take();
3367 }
Mike Stump1eb44332009-09-09 15:08:12 +00003368
John McCall7a534b92013-03-04 01:30:55 +00003369 // Build an unanalyzed expression if either operand is type-dependent.
David Blaikie4e4d0842012-03-11 07:00:24 +00003370 if (getLangOpts().CPlusPlus &&
John McCall7a534b92013-03-04 01:30:55 +00003371 (base->isTypeDependent() || idx->isTypeDependent())) {
3372 return Owned(new (Context) ArraySubscriptExpr(base, idx,
John McCallf89e55a2010-11-18 06:31:45 +00003373 Context.DependentTy,
3374 VK_LValue, OK_Ordinary,
John McCall7a534b92013-03-04 01:30:55 +00003375 rbLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003376 }
3377
John McCall7a534b92013-03-04 01:30:55 +00003378 // Use C++ overloaded-operator rules if either operand has record
3379 // type. The spec says to do this if either type is *overloadable*,
3380 // but enum types can't declare subscript operators or conversion
3381 // operators, so there's nothing interesting for overload resolution
3382 // to do if there aren't any record types involved.
3383 //
3384 // ObjC pointers have their own subscripting logic that is not tied
3385 // to overload resolution and so should not take this path.
David Blaikie4e4d0842012-03-11 07:00:24 +00003386 if (getLangOpts().CPlusPlus &&
John McCall7a534b92013-03-04 01:30:55 +00003387 (base->getType()->isRecordType() ||
3388 (!base->getType()->isObjCObjectPointerType() &&
3389 idx->getType()->isRecordType()))) {
3390 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003391 }
3392
John McCall7a534b92013-03-04 01:30:55 +00003393 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003394}
3395
John McCall60d7b3a2010-08-24 06:29:42 +00003396ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003397Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003398 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003399 Expr *LHSExp = Base;
3400 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003401
Chris Lattner12d9ff62007-07-16 00:14:47 +00003402 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003403 if (!LHSExp->getType()->getAs<VectorType>()) {
3404 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3405 if (Result.isInvalid())
3406 return ExprError();
3407 LHSExp = Result.take();
3408 }
3409 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3410 if (Result.isInvalid())
3411 return ExprError();
3412 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003413
Chris Lattner12d9ff62007-07-16 00:14:47 +00003414 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003415 ExprValueKind VK = VK_LValue;
3416 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003417
Reid Spencer5f016e22007-07-11 17:01:13 +00003418 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003419 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003420 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003421 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003422 Expr *BaseExpr, *IndexExpr;
3423 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003424 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3425 BaseExpr = LHSExp;
3426 IndexExpr = RHSExp;
3427 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003428 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003429 BaseExpr = LHSExp;
3430 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003431 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003432 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003433 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003434 BaseExpr = LHSExp;
3435 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003436
3437 // Use custom logic if this should be the pseudo-object subscript
3438 // expression.
3439 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3440 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3441
Steve Naroff14108da2009-07-10 23:34:53 +00003442 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003443 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3444 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3445 << ResultType << BaseExpr->getSourceRange();
3446 return ExprError();
3447 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003448 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3449 // Handle the uncommon case of "123[Ptr]".
3450 BaseExpr = RHSExp;
3451 IndexExpr = LHSExp;
3452 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003453 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003454 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003455 // Handle the uncommon case of "123[Ptr]".
3456 BaseExpr = RHSExp;
3457 IndexExpr = LHSExp;
3458 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003459 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3460 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3461 << ResultType << BaseExpr->getSourceRange();
3462 return ExprError();
3463 }
John McCall183700f2009-09-21 23:43:11 +00003464 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003465 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003466 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003467 VK = LHSExp->getValueKind();
3468 if (VK != VK_RValue)
3469 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003470
Chris Lattner12d9ff62007-07-16 00:14:47 +00003471 // FIXME: need to deal with const...
3472 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003473 } else if (LHSTy->isArrayType()) {
3474 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003475 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003476 // wasn't promoted because of the C90 rule that doesn't
3477 // allow promoting non-lvalue arrays. Warn, then
3478 // force the promotion here.
3479 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3480 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003481 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3482 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003483 LHSTy = LHSExp->getType();
3484
3485 BaseExpr = LHSExp;
3486 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003487 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003488 } else if (RHSTy->isArrayType()) {
3489 // Same as previous, except for 123[f().a] case
3490 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3491 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003492 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3493 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003494 RHSTy = RHSExp->getType();
3495
3496 BaseExpr = RHSExp;
3497 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003498 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003499 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003500 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3501 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003502 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003503 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003504 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003505 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3506 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003507
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003508 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003509 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3510 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003511 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3512
Douglas Gregore7450f52009-03-24 19:52:54 +00003513 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003514 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3515 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003516 // incomplete types are not object types.
3517 if (ResultType->isFunctionType()) {
3518 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3519 << ResultType << BaseExpr->getSourceRange();
3520 return ExprError();
3521 }
Mike Stump1eb44332009-09-09 15:08:12 +00003522
David Blaikie4e4d0842012-03-11 07:00:24 +00003523 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003524 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003525 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3526 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003527
3528 // C forbids expressions of unqualified void type from being l-values.
3529 // See IsCForbiddenLValueType.
3530 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003531 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003532 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003533 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003534 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003535
John McCall09431682010-11-18 19:01:18 +00003536 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003537 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003538
Mike Stumpeed9cac2009-02-19 03:04:26 +00003539 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003540 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003541}
3542
John McCall60d7b3a2010-08-24 06:29:42 +00003543ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003544 FunctionDecl *FD,
3545 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003546 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003547 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003548 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003549 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003550 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003551 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003552 return ExprError();
3553 }
3554
3555 if (Param->hasUninstantiatedDefaultArg()) {
3556 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003557
Richard Smithadb1d4c2012-07-22 23:45:10 +00003558 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3559 Param);
3560
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003561 // Instantiate the expression.
3562 MultiLevelTemplateArgumentList ArgList
3563 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003564
Nico Weber08e41a62010-11-29 18:19:25 +00003565 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003566 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003567 InstantiatingTemplate Inst(*this, CallLoc, Param,
3568 ArrayRef<TemplateArgument>(Innermost.first,
3569 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003570 if (Inst)
3571 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003572
Nico Weber08e41a62010-11-29 18:19:25 +00003573 ExprResult Result;
3574 {
3575 // C++ [dcl.fct.default]p5:
3576 // The names in the [default argument] expression are bound, and
3577 // the semantic constraints are checked, at the point where the
3578 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003579 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003580 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003581 Result = SubstExpr(UninstExpr, ArgList);
3582 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003583 if (Result.isInvalid())
3584 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003585
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003586 // Check the expression as an initializer for the parameter.
3587 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003588 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003589 InitializationKind Kind
3590 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003591 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003592 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003593
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003594 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003595 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003596 if (Result.isInvalid())
3597 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003598
David Blaikiec1c07252012-04-30 18:21:31 +00003599 Expr *Arg = Result.takeAs<Expr>();
Richard Smith6c3af3d2013-01-17 01:17:56 +00003600 CheckCompletedExpr(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003601 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003602 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003603 }
3604
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003605 // If the default expression creates temporaries, we need to
3606 // push them to the current stack of expression temporaries so they'll
3607 // be properly destroyed.
3608 // FIXME: We should really be rebuilding the default argument with new
3609 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003610 // We don't need to do that with block decls, though, because
3611 // blocks in default argument expression can never capture anything.
3612 if (isa<ExprWithCleanups>(Param->getInit())) {
3613 // Set the "needs cleanups" bit regardless of whether there are
3614 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003615 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003616
3617 // Append all the objects to the cleanup list. Right now, this
3618 // should always be a no-op, because blocks in default argument
3619 // expressions should never be able to capture anything.
3620 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3621 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003622 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003623
3624 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003625 // Just mark all of the declarations in this potentially-evaluated expression
3626 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003627 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3628 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003629 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003630}
3631
Richard Smith831421f2012-06-25 20:30:08 +00003632
3633Sema::VariadicCallType
3634Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3635 Expr *Fn) {
3636 if (Proto && Proto->isVariadic()) {
3637 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3638 return VariadicConstructor;
3639 else if (Fn && Fn->getType()->isBlockPointerType())
3640 return VariadicBlock;
3641 else if (FDecl) {
3642 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3643 if (Method->isInstance())
3644 return VariadicMethod;
3645 }
3646 return VariadicFunction;
3647 }
3648 return VariadicDoesNotApply;
3649}
3650
Douglas Gregor88a35142008-12-22 05:46:06 +00003651/// ConvertArgumentsForCall - Converts the arguments specified in
3652/// Args/NumArgs to the parameter types of the function FDecl with
3653/// function prototype Proto. Call is the call expression itself, and
3654/// Fn is the function expression. For a C++ member function, this
3655/// routine does not attempt to convert the object argument. Returns
3656/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003657bool
3658Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003659 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003660 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003661 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003662 SourceLocation RParenLoc,
3663 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003664 // Bail out early if calling a builtin with custom typechecking.
3665 // We don't need to do this in the
3666 if (FDecl)
3667 if (unsigned ID = FDecl->getBuiltinID())
3668 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3669 return false;
3670
Mike Stumpeed9cac2009-02-19 03:04:26 +00003671 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003672 // assignment, to the types of the corresponding parameter, ...
3673 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003674 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003675 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003676 unsigned FnKind = Fn->getType()->isBlockPointerType()
3677 ? 1 /* block */
3678 : (IsExecConfig ? 3 /* kernel function (exec config) */
3679 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003680
Douglas Gregor88a35142008-12-22 05:46:06 +00003681 // If too few arguments are available (and we don't have default
3682 // arguments for the remaining parameters), don't make the call.
3683 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003684 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003685 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3686 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3687 ? diag::err_typecheck_call_too_few_args_one
3688 : diag::err_typecheck_call_too_few_args_at_least_one)
3689 << FnKind
3690 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3691 else
3692 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3693 ? diag::err_typecheck_call_too_few_args
3694 : diag::err_typecheck_call_too_few_args_at_least)
3695 << FnKind
3696 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003697
3698 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003699 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003700 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3701 << FDecl;
3702
3703 return true;
3704 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003705 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003706 }
3707
3708 // If too many are passed and not variadic, error on the extras and drop
3709 // them.
3710 if (NumArgs > NumArgsInProto) {
3711 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003712 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3713 Diag(Args[NumArgsInProto]->getLocStart(),
3714 MinArgs == NumArgsInProto
3715 ? diag::err_typecheck_call_too_many_args_one
3716 : diag::err_typecheck_call_too_many_args_at_most_one)
3717 << FnKind
3718 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3719 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3720 Args[NumArgs-1]->getLocEnd());
3721 else
3722 Diag(Args[NumArgsInProto]->getLocStart(),
3723 MinArgs == NumArgsInProto
3724 ? diag::err_typecheck_call_too_many_args
3725 : diag::err_typecheck_call_too_many_args_at_most)
3726 << FnKind
3727 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3728 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3729 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003730
3731 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003732 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003733 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3734 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003735
Douglas Gregor88a35142008-12-22 05:46:06 +00003736 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003737 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003738 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003739 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003740 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003741 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003742 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3743
Daniel Dunbar96a00142012-03-09 18:35:03 +00003744 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003745 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003746 if (Invalid)
3747 return true;
3748 unsigned TotalNumArgs = AllArgs.size();
3749 for (unsigned i = 0; i < TotalNumArgs; ++i)
3750 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003751
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003752 return false;
3753}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003754
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003755bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3756 FunctionDecl *FDecl,
3757 const FunctionProtoType *Proto,
3758 unsigned FirstProtoArg,
3759 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003760 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003761 VariadicCallType CallType,
Richard Smitha4dc51b2013-02-05 05:52:24 +00003762 bool AllowExplicit,
3763 bool IsListInitialization) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003764 unsigned NumArgsInProto = Proto->getNumArgs();
3765 unsigned NumArgsToCheck = NumArgs;
3766 bool Invalid = false;
3767 if (NumArgs != NumArgsInProto)
3768 // Use default arguments for missing arguments
3769 NumArgsToCheck = NumArgsInProto;
3770 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003771 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003772 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003773 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003774
Douglas Gregor88a35142008-12-22 05:46:06 +00003775 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003776 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003777 if (ArgIx < NumArgs) {
3778 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003779
Daniel Dunbar96a00142012-03-09 18:35:03 +00003780 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003781 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003782 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003783 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003784
Douglas Gregora188ff22009-12-22 16:09:06 +00003785 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003786 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003787 if (FDecl && i < FDecl->getNumParams())
3788 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003789
John McCall5acb0c92011-10-17 18:40:02 +00003790 // Strip the unbridged-cast placeholder expression off, if applicable.
3791 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3792 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3793 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3794 Arg = stripARCUnbridgedCast(Arg);
3795
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00003796 InitializedEntity Entity = Param ?
3797 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3798 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3799 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003800 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003801 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003802 Owned(Arg),
Richard Smitha4dc51b2013-02-05 05:52:24 +00003803 IsListInitialization,
Douglas Gregored878af2012-02-24 23:56:31 +00003804 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003805 if (ArgE.isInvalid())
3806 return true;
3807
3808 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003809 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003810 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003811
John McCall60d7b3a2010-08-24 06:29:42 +00003812 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003813 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003814 if (ArgExpr.isInvalid())
3815 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003816
Anders Carlsson56c5e332009-08-25 03:49:14 +00003817 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003818 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003819
3820 // Check for array bounds violations for each argument to the call. This
3821 // check only triggers warnings when the argument isn't a more complex Expr
3822 // with its own checking, such as a BinaryOperator.
3823 CheckArrayAccess(Arg);
3824
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003825 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3826 CheckStaticArrayArgument(CallLoc, Param, Arg);
3827
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003828 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003829 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003830
Douglas Gregor88a35142008-12-22 05:46:06 +00003831 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003832 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003833 // Assume that extern "C" functions with variadic arguments that
3834 // return __unknown_anytype aren't *really* variadic.
3835 if (Proto->getResultType() == Context.UnknownAnyTy &&
3836 FDecl && FDecl->isExternC()) {
3837 for (unsigned i = ArgIx; i != NumArgs; ++i) {
John McCall48f90422013-03-04 07:34:02 +00003838 QualType paramType; // ignored
3839 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
John McCall755d8492011-04-12 00:42:48 +00003840 Invalid |= arg.isInvalid();
3841 AllArgs.push_back(arg.take());
3842 }
3843
3844 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3845 } else {
3846 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003847 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3848 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003849 Invalid |= Arg.isInvalid();
3850 AllArgs.push_back(Arg.take());
3851 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003852 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003853
3854 // Check for array bounds violations.
3855 for (unsigned i = ArgIx; i != NumArgs; ++i)
3856 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003857 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003858 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003859}
3860
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003861static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3862 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00003863 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003864 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
David Blaikie39e6ab42013-02-18 22:06:02 +00003865 << ATL.getLocalSourceRange();
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003866}
3867
3868/// CheckStaticArrayArgument - If the given argument corresponds to a static
3869/// array parameter, check that it is non-null, and that if it is formed by
3870/// array-to-pointer decay, the underlying array is sufficiently large.
3871///
3872/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3873/// array type derivation, then for each call to the function, the value of the
3874/// corresponding actual argument shall provide access to the first element of
3875/// an array with at least as many elements as specified by the size expression.
3876void
3877Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3878 ParmVarDecl *Param,
3879 const Expr *ArgExpr) {
3880 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003881 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003882 return;
3883
3884 QualType OrigTy = Param->getOriginalType();
3885
3886 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3887 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3888 return;
3889
3890 if (ArgExpr->isNullPointerConstant(Context,
3891 Expr::NPC_NeverValueDependent)) {
3892 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3893 DiagnoseCalleeStaticArrayParam(*this, Param);
3894 return;
3895 }
3896
3897 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3898 if (!CAT)
3899 return;
3900
3901 const ConstantArrayType *ArgCAT =
3902 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3903 if (!ArgCAT)
3904 return;
3905
3906 if (ArgCAT->getSize().ult(CAT->getSize())) {
3907 Diag(CallLoc, diag::warn_static_array_too_small)
3908 << ArgExpr->getSourceRange()
3909 << (unsigned) ArgCAT->getSize().getZExtValue()
3910 << (unsigned) CAT->getSize().getZExtValue();
3911 DiagnoseCalleeStaticArrayParam(*this, Param);
3912 }
3913}
3914
John McCall755d8492011-04-12 00:42:48 +00003915/// Given a function expression of unknown-any type, try to rebuild it
3916/// to have a function type.
3917static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3918
Steve Narofff69936d2007-09-16 03:34:24 +00003919/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003920/// This provides the location of the left/right parens and a list of comma
3921/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003922ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003923Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003924 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003925 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003926 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003927 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003928 if (Result.isInvalid()) return ExprError();
3929 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003930
David Blaikie4e4d0842012-03-11 07:00:24 +00003931 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003932 // If this is a pseudo-destructor expression, build the call immediately.
3933 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003934 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003935 // Pseudo-destructor calls should not have any arguments.
3936 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003937 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003938 SourceRange(ArgExprs[0]->getLocStart(),
3939 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003940 }
Mike Stump1eb44332009-09-09 15:08:12 +00003941
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003942 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3943 Context.VoidTy, VK_RValue,
3944 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003945 }
Mike Stump1eb44332009-09-09 15:08:12 +00003946
Douglas Gregor17330012009-02-04 15:01:18 +00003947 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003948 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003949 // FIXME: Will need to cache the results of name lookup (including ADL) in
3950 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003951 bool Dependent = false;
3952 if (Fn->isTypeDependent())
3953 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003954 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003955 Dependent = true;
3956
Peter Collingbournee08ce652011-02-09 21:07:24 +00003957 if (Dependent) {
3958 if (ExecConfig) {
3959 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003960 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003961 Context.DependentTy, VK_RValue, RParenLoc));
3962 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003963 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003964 Context.DependentTy, VK_RValue,
3965 RParenLoc));
3966 }
3967 }
Douglas Gregor17330012009-02-04 15:01:18 +00003968
3969 // Determine whether this is a call to an object (C++ [over.call.object]).
3970 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003971 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3972 ArgExprs.data(),
3973 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003974
John McCall755d8492011-04-12 00:42:48 +00003975 if (Fn->getType() == Context.UnknownAnyTy) {
3976 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3977 if (result.isInvalid()) return ExprError();
3978 Fn = result.take();
3979 }
3980
John McCall864c0412011-04-26 20:42:42 +00003981 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003982 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3983 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003984 }
John McCall864c0412011-04-26 20:42:42 +00003985 }
John McCall129e2df2009-11-30 22:42:35 +00003986
John McCall864c0412011-04-26 20:42:42 +00003987 // Check for overloaded calls. This can happen even in C due to extensions.
3988 if (Fn->getType() == Context.OverloadTy) {
3989 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3990
Douglas Gregoree697e62011-10-13 18:10:35 +00003991 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003992 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003993 OverloadExpr *ovl = find.Expression;
3994 if (isa<UnresolvedLookupExpr>(ovl)) {
3995 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003996 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3997 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003998 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003999 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4000 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004001 }
4002 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004003 }
4004
Douglas Gregorfa047642009-02-04 00:32:51 +00004005 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00004006 if (Fn->getType() == Context.UnknownAnyTy) {
4007 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4008 if (result.isInvalid()) return ExprError();
4009 Fn = result.take();
4010 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004011
Eli Friedmanefa42f72009-12-26 03:35:45 +00004012 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004013
John McCall3b4294e2009-12-16 12:17:52 +00004014 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004015 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4016 if (UnOp->getOpcode() == UO_AddrOf)
4017 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4018
John McCall3b4294e2009-12-16 12:17:52 +00004019 if (isa<DeclRefExpr>(NakedFn))
4020 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00004021 else if (isa<MemberExpr>(NakedFn))
4022 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00004023
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004024 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
4025 ArgExprs.size(), RParenLoc, ExecConfig,
4026 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00004027}
4028
4029ExprResult
4030Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004031 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00004032 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4033 if (!ConfigDecl)
4034 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4035 << "cudaConfigureCall");
4036 QualType ConfigQTy = ConfigDecl->getType();
4037
4038 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00004039 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00004040 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00004041
Peter Collingbourne1f240762011-10-02 23:49:29 +00004042 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4043 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00004044}
4045
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004046/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4047///
4048/// __builtin_astype( value, dst type )
4049///
Richard Trieuccd891a2011-09-09 01:45:06 +00004050ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004051 SourceLocation BuiltinLoc,
4052 SourceLocation RParenLoc) {
4053 ExprValueKind VK = VK_RValue;
4054 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00004055 QualType DstTy = GetTypeFromParser(ParsedDestTy);
4056 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004057 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4058 return ExprError(Diag(BuiltinLoc,
4059 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00004060 << DstTy
4061 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00004062 << E->getSourceRange());
4063 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00004064 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004065}
4066
John McCall3b4294e2009-12-16 12:17:52 +00004067/// BuildResolvedCallExpr - Build a call to a resolved expression,
4068/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004069/// unary-convert to an expression of function-pointer or
4070/// block-pointer type.
4071///
4072/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004073ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004074Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4075 SourceLocation LParenLoc,
4076 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004077 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004078 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00004079 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004080 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00004081
Chris Lattner04421082008-04-08 04:40:51 +00004082 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004083 // We special-case function promotion here because we only allow promoting
4084 // builtin functions to function pointers in the callee of a call.
4085 ExprResult Result;
4086 if (BuiltinID &&
4087 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4088 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4089 CK_BuiltinFnToFnPtr).take();
4090 } else {
4091 Result = UsualUnaryConversions(Fn);
4092 }
John Wiegley429bb272011-04-08 18:41:53 +00004093 if (Result.isInvalid())
4094 return ExprError();
4095 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004096
Chris Lattner925e60d2007-12-28 05:29:59 +00004097 // Make the call expr early, before semantic checks. This guarantees cleanup
4098 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004099 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004100 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004101 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4102 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004103 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004104 Context.BoolTy,
4105 VK_RValue,
4106 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004107 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00004108 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004109 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004110 Context.BoolTy,
4111 VK_RValue,
4112 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004113
John McCall8e10f3b2011-02-26 05:39:39 +00004114 // Bail out early if calling a builtin with custom typechecking.
4115 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4116 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4117
John McCall1de4d4e2011-04-07 08:22:57 +00004118 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004119 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004120 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004121 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4122 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004123 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004124 if (FuncT == 0)
4125 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4126 << Fn->getType() << Fn->getSourceRange());
4127 } else if (const BlockPointerType *BPT =
4128 Fn->getType()->getAs<BlockPointerType>()) {
4129 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4130 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004131 // Handle calls to expressions of unknown-any type.
4132 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004133 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004134 if (rewrite.isInvalid()) return ExprError();
4135 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004136 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004137 goto retry;
4138 }
4139
Sebastian Redl0eb23302009-01-19 00:08:26 +00004140 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4141 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004142 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004143
David Blaikie4e4d0842012-03-11 07:00:24 +00004144 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004145 if (Config) {
4146 // CUDA: Kernel calls must be to global functions
4147 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4148 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4149 << FDecl->getName() << Fn->getSourceRange());
4150
4151 // CUDA: Kernel function must have 'void' return type
4152 if (!FuncT->getResultType()->isVoidType())
4153 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4154 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004155 } else {
4156 // CUDA: Calls to global functions must be configured
4157 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4158 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4159 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004160 }
4161 }
4162
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004163 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004164 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004165 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004166 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004167 return ExprError();
4168
Chris Lattner925e60d2007-12-28 05:29:59 +00004169 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004170 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004171 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004172
Richard Smith831421f2012-06-25 20:30:08 +00004173 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4174 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004175 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004176 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004177 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004178 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004179 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004180
Douglas Gregor74734d52009-04-02 15:37:10 +00004181 if (FDecl) {
4182 // Check if we have too few/too many template arguments, based
4183 // on our knowledge of the function definition.
4184 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004185 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004186 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004187 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004188 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4189 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004190 }
Douglas Gregor46542412010-10-25 20:39:23 +00004191
4192 // If the function we're calling isn't a function prototype, but we have
4193 // a function prototype from a prior declaratiom, use that prototype.
4194 if (!FDecl->hasPrototype())
4195 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004196 }
4197
Steve Naroffb291ab62007-08-28 23:30:39 +00004198 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004199 for (unsigned i = 0; i != NumArgs; i++) {
4200 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004201
4202 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004203 InitializedEntity Entity
4204 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004205 Proto->getArgType(i),
4206 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004207 ExprResult ArgE = PerformCopyInitialization(Entity,
4208 SourceLocation(),
4209 Owned(Arg));
4210 if (ArgE.isInvalid())
4211 return true;
4212
4213 Arg = ArgE.takeAs<Expr>();
4214
4215 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004216 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4217
4218 if (ArgE.isInvalid())
4219 return true;
4220
4221 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004222 }
4223
Daniel Dunbar96a00142012-03-09 18:35:03 +00004224 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004225 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004226 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004227 return ExprError();
4228
Chris Lattner925e60d2007-12-28 05:29:59 +00004229 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004230 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004231 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004232
Douglas Gregor88a35142008-12-22 05:46:06 +00004233 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4234 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004235 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4236 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004237
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004238 // Check for sentinels
4239 if (NDecl)
4240 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Chris Lattner59907c42007-08-10 20:18:51 +00004242 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004243 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004244 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004245 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004246
John McCall8e10f3b2011-02-26 05:39:39 +00004247 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004248 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004249 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004250 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004251 return ExprError();
4252 }
Chris Lattner59907c42007-08-10 20:18:51 +00004253
John McCall9ae2f072010-08-23 23:25:46 +00004254 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004255}
4256
John McCall60d7b3a2010-08-24 06:29:42 +00004257ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004258Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004259 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004260 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004261 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004262 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004263
4264 TypeSourceInfo *TInfo;
4265 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4266 if (!TInfo)
4267 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4268
John McCall9ae2f072010-08-23 23:25:46 +00004269 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004270}
4271
John McCall60d7b3a2010-08-24 06:29:42 +00004272ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004273Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004274 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004275 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004276
Eli Friedman6223c222008-05-20 05:22:08 +00004277 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004278 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004279 diag::err_illegal_decl_array_incomplete_type,
4280 SourceRange(LParenLoc,
4281 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004282 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004283 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004284 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004285 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004286 } else if (!literalType->isDependentType() &&
4287 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004288 diag::err_typecheck_decl_incomplete_type,
4289 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004290 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004291
Douglas Gregor99a2e602009-12-16 01:38:02 +00004292 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004293 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004294 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004295 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004296 SourceRange(LParenLoc, RParenLoc),
4297 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004298 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004299 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4300 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004301 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004302 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004303 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004304
Chris Lattner371f2582008-12-04 23:50:19 +00004305 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004306 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004307 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004308 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004309 }
Eli Friedman08544622009-12-22 02:35:53 +00004310
John McCallf89e55a2010-11-18 06:31:45 +00004311 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004312 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004313
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004314 return MaybeBindToTemporary(
4315 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004316 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004317}
4318
John McCall60d7b3a2010-08-24 06:29:42 +00004319ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004320Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004321 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004322 // Immediately handle non-overload placeholders. Overloads can be
4323 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004324 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4325 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4326 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004327
4328 // Ignore failures; dropping the entire initializer list because
4329 // of one failure would be terrible for indexing/etc.
4330 if (result.isInvalid()) continue;
4331
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004332 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004333 }
4334 }
4335
Steve Naroff08d92e42007-09-15 18:49:24 +00004336 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004337 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004338
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004339 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4340 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004341 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004342 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004343}
4344
John McCalldc05b112011-09-10 01:16:55 +00004345/// Do an explicit extend of the given block pointer if we're in ARC.
4346static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4347 assert(E.get()->getType()->isBlockPointerType());
4348 assert(E.get()->isRValue());
4349
4350 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004351 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004352
4353 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004354 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004355 /*base path*/ 0, VK_RValue);
4356 S.ExprNeedsCleanups = true;
4357}
4358
4359/// Prepare a conversion of the given expression to an ObjC object
4360/// pointer type.
4361CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4362 QualType type = E.get()->getType();
4363 if (type->isObjCObjectPointerType()) {
4364 return CK_BitCast;
4365 } else if (type->isBlockPointerType()) {
4366 maybeExtendBlockObject(*this, E);
4367 return CK_BlockPointerToObjCPointerCast;
4368 } else {
4369 assert(type->isPointerType());
4370 return CK_CPointerToObjCPointerCast;
4371 }
4372}
4373
John McCallf3ea8cf2010-11-14 08:17:51 +00004374/// Prepares for a scalar cast, performing all the necessary stages
4375/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004376CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004377 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4378 // Also, callers should have filtered out the invalid cases with
4379 // pointers. Everything else should be possible.
4380
John Wiegley429bb272011-04-08 18:41:53 +00004381 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004382 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004383 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004384
John McCall1d9b3b22011-09-09 05:25:32 +00004385 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004386 case Type::STK_MemberPointer:
4387 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004388
John McCall1d9b3b22011-09-09 05:25:32 +00004389 case Type::STK_CPointer:
4390 case Type::STK_BlockPointer:
4391 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004392 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004393 case Type::STK_CPointer:
4394 return CK_BitCast;
4395 case Type::STK_BlockPointer:
4396 return (SrcKind == Type::STK_BlockPointer
4397 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4398 case Type::STK_ObjCObjectPointer:
4399 if (SrcKind == Type::STK_ObjCObjectPointer)
4400 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004401 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004402 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004403 maybeExtendBlockObject(*this, Src);
4404 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004405 case Type::STK_Bool:
4406 return CK_PointerToBoolean;
4407 case Type::STK_Integral:
4408 return CK_PointerToIntegral;
4409 case Type::STK_Floating:
4410 case Type::STK_FloatingComplex:
4411 case Type::STK_IntegralComplex:
4412 case Type::STK_MemberPointer:
4413 llvm_unreachable("illegal cast from pointer");
4414 }
David Blaikie7530c032012-01-17 06:56:22 +00004415 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004416
John McCalldaa8e4e2010-11-15 09:13:47 +00004417 case Type::STK_Bool: // casting from bool is like casting from an integer
4418 case Type::STK_Integral:
4419 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004420 case Type::STK_CPointer:
4421 case Type::STK_ObjCObjectPointer:
4422 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004423 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004424 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004425 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004426 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004427 case Type::STK_Bool:
4428 return CK_IntegralToBoolean;
4429 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004430 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004431 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004432 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004433 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004434 Src = ImpCastExprToType(Src.take(),
4435 DestTy->castAs<ComplexType>()->getElementType(),
4436 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004437 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004438 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004439 Src = ImpCastExprToType(Src.take(),
4440 DestTy->castAs<ComplexType>()->getElementType(),
4441 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004442 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004443 case Type::STK_MemberPointer:
4444 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004445 }
David Blaikie7530c032012-01-17 06:56:22 +00004446 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004447
John McCalldaa8e4e2010-11-15 09:13:47 +00004448 case Type::STK_Floating:
4449 switch (DestTy->getScalarTypeKind()) {
4450 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004451 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004452 case Type::STK_Bool:
4453 return CK_FloatingToBoolean;
4454 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004455 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004456 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004457 Src = ImpCastExprToType(Src.take(),
4458 DestTy->castAs<ComplexType>()->getElementType(),
4459 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004460 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004461 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004462 Src = ImpCastExprToType(Src.take(),
4463 DestTy->castAs<ComplexType>()->getElementType(),
4464 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004465 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004466 case Type::STK_CPointer:
4467 case Type::STK_ObjCObjectPointer:
4468 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004469 llvm_unreachable("valid float->pointer cast?");
4470 case Type::STK_MemberPointer:
4471 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004472 }
David Blaikie7530c032012-01-17 06:56:22 +00004473 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004474
John McCalldaa8e4e2010-11-15 09:13:47 +00004475 case Type::STK_FloatingComplex:
4476 switch (DestTy->getScalarTypeKind()) {
4477 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004478 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004479 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004480 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004481 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004482 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4483 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004484 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004485 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004486 return CK_FloatingCast;
4487 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004488 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004489 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004490 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004491 Src = ImpCastExprToType(Src.take(),
4492 SrcTy->castAs<ComplexType>()->getElementType(),
4493 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004494 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004495 case Type::STK_CPointer:
4496 case Type::STK_ObjCObjectPointer:
4497 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004498 llvm_unreachable("valid complex float->pointer cast?");
4499 case Type::STK_MemberPointer:
4500 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004501 }
David Blaikie7530c032012-01-17 06:56:22 +00004502 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004503
John McCalldaa8e4e2010-11-15 09:13:47 +00004504 case Type::STK_IntegralComplex:
4505 switch (DestTy->getScalarTypeKind()) {
4506 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004507 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004508 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004509 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004510 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004511 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4512 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004513 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004514 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004515 return CK_IntegralCast;
4516 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004517 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004518 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004519 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004520 Src = ImpCastExprToType(Src.take(),
4521 SrcTy->castAs<ComplexType>()->getElementType(),
4522 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004523 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004524 case Type::STK_CPointer:
4525 case Type::STK_ObjCObjectPointer:
4526 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004527 llvm_unreachable("valid complex int->pointer cast?");
4528 case Type::STK_MemberPointer:
4529 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004530 }
David Blaikie7530c032012-01-17 06:56:22 +00004531 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004532 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004533
John McCallf3ea8cf2010-11-14 08:17:51 +00004534 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004535}
4536
Anders Carlssonc3516322009-10-16 02:48:28 +00004537bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004538 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004539 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004540
Anders Carlssona64db8f2007-11-27 05:51:55 +00004541 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004542 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004543 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004544 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004545 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004546 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004547 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004548 } else
4549 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004550 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004551 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004552
John McCall2de56d12010-08-25 11:45:40 +00004553 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004554 return false;
4555}
4556
John Wiegley429bb272011-04-08 18:41:53 +00004557ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4558 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004559 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004560
Anders Carlsson16a89042009-10-16 05:23:41 +00004561 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004562
Nate Begeman9b10da62009-06-27 22:05:55 +00004563 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4564 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004565 // In OpenCL, casts between vectors of different types are not allowed.
4566 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004567 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004568 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004569 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004570 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004571 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004572 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004573 return ExprError();
4574 }
John McCall2de56d12010-08-25 11:45:40 +00004575 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004576 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004577 }
4578
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004579 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004580 // conversion will take place first from scalar to elt type, and then
4581 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004582 if (SrcTy->isPointerType())
4583 return Diag(R.getBegin(),
4584 diag::err_invalid_conversion_between_vector_and_scalar)
4585 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004586
4587 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004588 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004589 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004590 if (CastExprRes.isInvalid())
4591 return ExprError();
4592 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004593
John McCall2de56d12010-08-25 11:45:40 +00004594 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004595 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004596}
4597
John McCall60d7b3a2010-08-24 06:29:42 +00004598ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004599Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4600 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004601 SourceLocation RParenLoc, Expr *CastExpr) {
4602 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004603 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004604
Richard Trieuccd891a2011-09-09 01:45:06 +00004605 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004606 if (D.isInvalidType())
4607 return ExprError();
4608
David Blaikie4e4d0842012-03-11 07:00:24 +00004609 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004610 // Check that there are no default arguments (C++ only).
4611 CheckExtraCXXDefaultArguments(D);
4612 }
4613
John McCalle82247a2011-10-01 05:17:03 +00004614 checkUnusedDeclAttributes(D);
4615
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004616 QualType castType = castTInfo->getType();
4617 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004618
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004619 bool isVectorLiteral = false;
4620
4621 // Check for an altivec or OpenCL literal,
4622 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004623 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4624 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004625 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004626 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004627 if (PLE && PLE->getNumExprs() == 0) {
4628 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4629 return ExprError();
4630 }
4631 if (PE || PLE->getNumExprs() == 1) {
4632 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4633 if (!E->getType()->isVectorType())
4634 isVectorLiteral = true;
4635 }
4636 else
4637 isVectorLiteral = true;
4638 }
4639
4640 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4641 // then handle it as such.
4642 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004643 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004644
Nate Begeman2ef13e52009-08-10 23:49:36 +00004645 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004646 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4647 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004648 if (isa<ParenListExpr>(CastExpr)) {
4649 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004650 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004651 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004652 }
John McCallb042fdf2010-01-15 18:56:44 +00004653
Richard Trieuccd891a2011-09-09 01:45:06 +00004654 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004655}
4656
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004657ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4658 SourceLocation RParenLoc, Expr *E,
4659 TypeSourceInfo *TInfo) {
4660 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4661 "Expected paren or paren list expression");
4662
4663 Expr **exprs;
4664 unsigned numExprs;
4665 Expr *subExpr;
Richard Smithafbcab82013-02-05 05:55:57 +00004666 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004667 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
Richard Smithafbcab82013-02-05 05:55:57 +00004668 LiteralLParenLoc = PE->getLParenLoc();
4669 LiteralRParenLoc = PE->getRParenLoc();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004670 exprs = PE->getExprs();
4671 numExprs = PE->getNumExprs();
Richard Smithafbcab82013-02-05 05:55:57 +00004672 } else { // isa<ParenExpr> by assertion at function entrance
4673 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
4674 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004675 subExpr = cast<ParenExpr>(E)->getSubExpr();
4676 exprs = &subExpr;
4677 numExprs = 1;
4678 }
4679
4680 QualType Ty = TInfo->getType();
4681 assert(Ty->isVectorType() && "Expected vector type");
4682
Chris Lattner5f9e2722011-07-23 10:55:15 +00004683 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004684 const VectorType *VTy = Ty->getAs<VectorType>();
4685 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4686
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004687 // '(...)' form of vector initialization in AltiVec: the number of
4688 // initializers must be one or must match the size of the vector.
4689 // If a single value is specified in the initializer then it will be
4690 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004691 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004692 // The number of initializers must be one or must match the size of the
4693 // vector. If a single value is specified in the initializer then it will
4694 // be replicated to all the components of the vector
4695 if (numExprs == 1) {
4696 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004697 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4698 if (Literal.isInvalid())
4699 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004700 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004701 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004702 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4703 }
4704 else if (numExprs < numElems) {
4705 Diag(E->getExprLoc(),
4706 diag::err_incorrect_number_of_vector_initializers);
4707 return ExprError();
4708 }
4709 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004710 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004711 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004712 else {
4713 // For OpenCL, when the number of initializers is a single value,
4714 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004715 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004716 VTy->getVectorKind() == VectorType::GenericVector &&
4717 numExprs == 1) {
4718 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004719 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4720 if (Literal.isInvalid())
4721 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004722 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004723 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004724 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4725 }
4726
Benjamin Kramer14c59822012-02-14 12:06:21 +00004727 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004728 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004729 // FIXME: This means that pretty-printing the final AST will produce curly
4730 // braces instead of the original commas.
Richard Smithafbcab82013-02-05 05:55:57 +00004731 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
4732 initExprs, LiteralRParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004733 initE->setType(Ty);
4734 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4735}
4736
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004737/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4738/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004739ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004740Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4741 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004742 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004743 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004744
John McCall60d7b3a2010-08-24 06:29:42 +00004745 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004746
Nate Begeman2ef13e52009-08-10 23:49:36 +00004747 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004748 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4749 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004750
John McCall9ae2f072010-08-23 23:25:46 +00004751 if (Result.isInvalid()) return ExprError();
4752
4753 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004754}
4755
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004756ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4757 SourceLocation R,
4758 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004759 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004760 return Owned(expr);
4761}
4762
Chandler Carruth82214a82011-02-18 23:54:50 +00004763/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004764/// constant and the other is not a pointer. Returns true if a diagnostic is
4765/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004766bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004767 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004768 Expr *NullExpr = LHSExpr;
4769 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004770 Expr::NullPointerConstantKind NullKind =
4771 NullExpr->isNullPointerConstant(Context,
4772 Expr::NPC_ValueDependentIsNotNull);
4773
4774 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004775 NullExpr = RHSExpr;
4776 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004777 NullKind =
4778 NullExpr->isNullPointerConstant(Context,
4779 Expr::NPC_ValueDependentIsNotNull);
4780 }
4781
4782 if (NullKind == Expr::NPCK_NotNull)
4783 return false;
4784
David Blaikie50800fc2012-08-08 17:33:31 +00004785 if (NullKind == Expr::NPCK_ZeroExpression)
4786 return false;
4787
4788 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004789 // In this case, check to make sure that we got here from a "NULL"
4790 // string in the source code.
4791 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004792 SourceLocation loc = NullExpr->getExprLoc();
4793 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004794 return false;
4795 }
4796
Richard Smith4e24f0f2013-01-02 12:01:23 +00004797 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Chandler Carruth82214a82011-02-18 23:54:50 +00004798 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4799 << NonPointerExpr->getType() << DiagType
4800 << NonPointerExpr->getSourceRange();
4801 return true;
4802}
4803
Richard Trieu26f96072011-09-02 01:51:02 +00004804/// \brief Return false if the condition expression is valid, true otherwise.
4805static bool checkCondition(Sema &S, Expr *Cond) {
4806 QualType CondTy = Cond->getType();
4807
4808 // C99 6.5.15p2
4809 if (CondTy->isScalarType()) return false;
4810
4811 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004812 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004813 return false;
4814
4815 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004816 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004817 diag::err_typecheck_cond_expect_scalar :
4818 diag::err_typecheck_cond_expect_scalar_or_vector)
4819 << CondTy;
4820 return true;
4821}
4822
4823/// \brief Return false if the two expressions can be converted to a vector,
4824/// true otherwise
4825static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4826 ExprResult &RHS,
4827 QualType CondTy) {
4828 // Both operands should be of scalar type.
4829 if (!LHS.get()->getType()->isScalarType()) {
4830 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4831 << CondTy;
4832 return true;
4833 }
4834 if (!RHS.get()->getType()->isScalarType()) {
4835 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4836 << CondTy;
4837 return true;
4838 }
4839
4840 // Implicity convert these scalars to the type of the condition.
4841 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4842 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4843 return false;
4844}
4845
4846/// \brief Handle when one or both operands are void type.
4847static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4848 ExprResult &RHS) {
4849 Expr *LHSExpr = LHS.get();
4850 Expr *RHSExpr = RHS.get();
4851
4852 if (!LHSExpr->getType()->isVoidType())
4853 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4854 << RHSExpr->getSourceRange();
4855 if (!RHSExpr->getType()->isVoidType())
4856 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4857 << LHSExpr->getSourceRange();
4858 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4859 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4860 return S.Context.VoidTy;
4861}
4862
4863/// \brief Return false if the NullExpr can be promoted to PointerTy,
4864/// true otherwise.
4865static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4866 QualType PointerTy) {
4867 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4868 !NullExpr.get()->isNullPointerConstant(S.Context,
4869 Expr::NPC_ValueDependentIsNull))
4870 return true;
4871
4872 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4873 return false;
4874}
4875
4876/// \brief Checks compatibility between two pointers and return the resulting
4877/// type.
4878static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4879 ExprResult &RHS,
4880 SourceLocation Loc) {
4881 QualType LHSTy = LHS.get()->getType();
4882 QualType RHSTy = RHS.get()->getType();
4883
4884 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4885 // Two identical pointers types are always compatible.
4886 return LHSTy;
4887 }
4888
4889 QualType lhptee, rhptee;
4890
4891 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004892 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4893 lhptee = LHSBTy->getPointeeType();
4894 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004895 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004896 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4897 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004898 }
4899
Eli Friedmanae916a12012-04-05 22:30:04 +00004900 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4901 // differently qualified versions of compatible types, the result type is
4902 // a pointer to an appropriately qualified version of the composite
4903 // type.
4904
4905 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4906 // clause doesn't make sense for our extensions. E.g. address space 2 should
4907 // be incompatible with address space 3: they may live on different devices or
4908 // anything.
4909 Qualifiers lhQual = lhptee.getQualifiers();
4910 Qualifiers rhQual = rhptee.getQualifiers();
4911
4912 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4913 lhQual.removeCVRQualifiers();
4914 rhQual.removeCVRQualifiers();
4915
4916 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4917 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4918
4919 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4920
4921 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004922 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4923 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4924 << RHS.get()->getSourceRange();
4925 // In this situation, we assume void* type. No especially good
4926 // reason, but this is what gcc does, and we do have to pick
4927 // to get a consistent AST.
4928 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4929 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4930 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4931 return incompatTy;
4932 }
4933
4934 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004935 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4936 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004937
Eli Friedmanae916a12012-04-05 22:30:04 +00004938 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4939 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4940 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004941}
4942
4943/// \brief Return the resulting type when the operands are both block pointers.
4944static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4945 ExprResult &LHS,
4946 ExprResult &RHS,
4947 SourceLocation Loc) {
4948 QualType LHSTy = LHS.get()->getType();
4949 QualType RHSTy = RHS.get()->getType();
4950
4951 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4952 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4953 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4954 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4955 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4956 return destType;
4957 }
4958 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4959 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4960 << RHS.get()->getSourceRange();
4961 return QualType();
4962 }
4963
4964 // We have 2 block pointer types.
4965 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4966}
4967
4968/// \brief Return the resulting type when the operands are both pointers.
4969static QualType
4970checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4971 ExprResult &RHS,
4972 SourceLocation Loc) {
4973 // get the pointer types
4974 QualType LHSTy = LHS.get()->getType();
4975 QualType RHSTy = RHS.get()->getType();
4976
4977 // get the "pointed to" types
4978 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4979 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4980
4981 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4982 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4983 // Figure out necessary qualifiers (C99 6.5.15p6)
4984 QualType destPointee
4985 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4986 QualType destType = S.Context.getPointerType(destPointee);
4987 // Add qualifiers if necessary.
4988 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4989 // Promote to void*.
4990 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4991 return destType;
4992 }
4993 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4994 QualType destPointee
4995 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4996 QualType destType = S.Context.getPointerType(destPointee);
4997 // Add qualifiers if necessary.
4998 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4999 // Promote to void*.
5000 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5001 return destType;
5002 }
5003
5004 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5005}
5006
5007/// \brief Return false if the first expression is not an integer and the second
5008/// expression is not a pointer, true otherwise.
5009static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5010 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005011 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00005012 if (!PointerExpr->getType()->isPointerType() ||
5013 !Int.get()->getType()->isIntegerType())
5014 return false;
5015
Richard Trieuccd891a2011-09-09 01:45:06 +00005016 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5017 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00005018
5019 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5020 << Expr1->getType() << Expr2->getType()
5021 << Expr1->getSourceRange() << Expr2->getSourceRange();
5022 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5023 CK_IntegralToPointer);
5024 return true;
5025}
5026
Richard Trieu33fc7572011-09-06 20:06:39 +00005027/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5028/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005029/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00005030QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5031 ExprResult &RHS, ExprValueKind &VK,
5032 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005033 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005034
Richard Trieu33fc7572011-09-06 20:06:39 +00005035 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5036 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005037 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005038
Richard Trieu33fc7572011-09-06 20:06:39 +00005039 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5040 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005041 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005042
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005043 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00005044 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005045 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005046
5047 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005048 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005049
John Wiegley429bb272011-04-08 18:41:53 +00005050 Cond = UsualUnaryConversions(Cond.take());
5051 if (Cond.isInvalid())
5052 return QualType();
5053 LHS = UsualUnaryConversions(LHS.take());
5054 if (LHS.isInvalid())
5055 return QualType();
5056 RHS = UsualUnaryConversions(RHS.take());
5057 if (RHS.isInvalid())
5058 return QualType();
5059
5060 QualType CondTy = Cond.get()->getType();
5061 QualType LHSTy = LHS.get()->getType();
5062 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005063
Reid Spencer5f016e22007-07-11 17:01:13 +00005064 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00005065 if (checkCondition(*this, Cond.get()))
5066 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005067
Chris Lattner70d67a92008-01-06 22:42:25 +00005068 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005069 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005070 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00005071
Nate Begeman6155d732010-09-20 22:41:17 +00005072 // OpenCL: If the condition is a vector, and both operands are scalar,
5073 // attempt to implicity convert them to the vector type to act like the
5074 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00005075 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00005076 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00005077 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00005078
Chris Lattner70d67a92008-01-06 22:42:25 +00005079 // If both operands have arithmetic type, do the usual arithmetic conversions
5080 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005081 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5082 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005083 if (LHS.isInvalid() || RHS.isInvalid())
5084 return QualType();
5085 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005086 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005087
Chris Lattner70d67a92008-01-06 22:42:25 +00005088 // If both operands are the same structure or union type, the result is that
5089 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005090 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5091 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005092 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005093 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005094 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005095 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005096 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005097 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005098
Chris Lattner70d67a92008-01-06 22:42:25 +00005099 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005100 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005101 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005102 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00005103 }
Richard Trieu26f96072011-09-02 01:51:02 +00005104
Steve Naroffb6d54e52008-01-08 01:11:38 +00005105 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5106 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00005107 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5108 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005109
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005110 // All objective-c pointer type analysis is done here.
5111 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5112 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005113 if (LHS.isInvalid() || RHS.isInvalid())
5114 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005115 if (!compositeType.isNull())
5116 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005117
5118
Steve Naroff7154a772009-07-01 14:36:47 +00005119 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00005120 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5121 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5122 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005123
Steve Naroff7154a772009-07-01 14:36:47 +00005124 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00005125 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5126 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5127 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005128
John McCall404cd162010-11-13 01:35:44 +00005129 // GCC compatibility: soften pointer/integer mismatch. Note that
5130 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00005131 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5132 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00005133 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005134 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5135 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00005136 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005137
Chandler Carruth82214a82011-02-18 23:54:50 +00005138 // Emit a better diagnostic if one of the expressions is a null pointer
5139 // constant and the other is not a pointer type. In this case, the user most
5140 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005141 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005142 return QualType();
5143
Chris Lattner70d67a92008-01-06 22:42:25 +00005144 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005145 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005146 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5147 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005148 return QualType();
5149}
5150
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005151/// FindCompositeObjCPointerType - Helper method to find composite type of
5152/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005153QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005154 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005155 QualType LHSTy = LHS.get()->getType();
5156 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005157
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005158 // Handle things like Class and struct objc_class*. Here we case the result
5159 // to the pseudo-builtin, because that will be implicitly cast back to the
5160 // redefinition type if an attempt is made to access its fields.
5161 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005162 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005163 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005164 return LHSTy;
5165 }
5166 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005167 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005168 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005169 return RHSTy;
5170 }
5171 // And the same for struct objc_object* / id
5172 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005173 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005174 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005175 return LHSTy;
5176 }
5177 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005178 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005179 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005180 return RHSTy;
5181 }
5182 // And the same for struct objc_selector* / SEL
5183 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005184 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005185 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005186 return LHSTy;
5187 }
5188 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005189 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005190 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005191 return RHSTy;
5192 }
5193 // Check constraints for Objective-C object pointers types.
5194 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005195
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005196 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5197 // Two identical object pointer types are always compatible.
5198 return LHSTy;
5199 }
John McCall1d9b3b22011-09-09 05:25:32 +00005200 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5201 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005202 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005203
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005204 // If both operands are interfaces and either operand can be
5205 // assigned to the other, use that type as the composite
5206 // type. This allows
5207 // xxx ? (A*) a : (B*) b
5208 // where B is a subclass of A.
5209 //
5210 // Additionally, as for assignment, if either type is 'id'
5211 // allow silent coercion. Finally, if the types are
5212 // incompatible then make sure to use 'id' as the composite
5213 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005214
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005215 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5216 // It could return the composite type.
5217 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5218 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5219 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5220 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5221 } else if ((LHSTy->isObjCQualifiedIdType() ||
5222 RHSTy->isObjCQualifiedIdType()) &&
5223 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5224 // Need to handle "id<xx>" explicitly.
5225 // GCC allows qualified id and any Objective-C type to devolve to
5226 // id. Currently localizing to here until clear this should be
5227 // part of ObjCQualifiedIdTypesAreCompatible.
5228 compositeType = Context.getObjCIdType();
5229 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5230 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005231 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005232 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5233 ;
5234 else {
5235 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5236 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005237 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005238 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005239 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5240 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005241 return incompatTy;
5242 }
5243 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005244 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5245 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005246 return compositeType;
5247 }
5248 // Check Objective-C object pointer types and 'void *'
5249 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005250 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005251 // ARC forbids the implicit conversion of object pointers to 'void *',
5252 // so these types are not compatible.
5253 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5254 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5255 LHS = RHS = true;
5256 return QualType();
5257 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005258 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5259 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5260 QualType destPointee
5261 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5262 QualType destType = Context.getPointerType(destPointee);
5263 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005264 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005265 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005266 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005267 return destType;
5268 }
5269 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005270 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005271 // ARC forbids the implicit conversion of object pointers to 'void *',
5272 // so these types are not compatible.
5273 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5274 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5275 LHS = RHS = true;
5276 return QualType();
5277 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005278 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5279 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5280 QualType destPointee
5281 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5282 QualType destType = Context.getPointerType(destPointee);
5283 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005284 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005285 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005286 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005287 return destType;
5288 }
5289 return QualType();
5290}
5291
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005292/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005293/// ParenRange in parentheses.
5294static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005295 const PartialDiagnostic &Note,
5296 SourceRange ParenRange) {
5297 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5298 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5299 EndLoc.isValid()) {
5300 Self.Diag(Loc, Note)
5301 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5302 << FixItHint::CreateInsertion(EndLoc, ")");
5303 } else {
5304 // We can't display the parentheses, so just show the bare note.
5305 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005306 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005307}
5308
5309static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5310 return Opc >= BO_Mul && Opc <= BO_Shr;
5311}
5312
Hans Wennborg2f072b42011-06-09 17:06:51 +00005313/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5314/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005315/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5316/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005317static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005318 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005319 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5320 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005321 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005322 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005323
5324 // Built-in binary operator.
5325 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5326 if (IsArithmeticOp(OP->getOpcode())) {
5327 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005328 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005329 return true;
5330 }
5331 }
5332
5333 // Overloaded operator.
5334 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5335 if (Call->getNumArgs() != 2)
5336 return false;
5337
5338 // Make sure this is really a binary operator that is safe to pass into
5339 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5340 OverloadedOperatorKind OO = Call->getOperator();
5341 if (OO < OO_Plus || OO > OO_Arrow)
5342 return false;
5343
5344 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5345 if (IsArithmeticOp(OpKind)) {
5346 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005347 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005348 return true;
5349 }
5350 }
5351
5352 return false;
5353}
5354
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005355static bool IsLogicOp(BinaryOperatorKind Opc) {
5356 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5357}
5358
Hans Wennborg2f072b42011-06-09 17:06:51 +00005359/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5360/// or is a logical expression such as (x==y) which has int type, but is
5361/// commonly interpreted as boolean.
5362static bool ExprLooksBoolean(Expr *E) {
5363 E = E->IgnoreParenImpCasts();
5364
5365 if (E->getType()->isBooleanType())
5366 return true;
5367 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5368 return IsLogicOp(OP->getOpcode());
5369 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5370 return OP->getOpcode() == UO_LNot;
5371
5372 return false;
5373}
5374
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005375/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5376/// and binary operator are mixed in a way that suggests the programmer assumed
5377/// the conditional operator has higher precedence, for example:
5378/// "int x = a + someBinaryCondition ? 1 : 2".
5379static void DiagnoseConditionalPrecedence(Sema &Self,
5380 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005381 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005382 Expr *LHSExpr,
5383 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005384 BinaryOperatorKind CondOpcode;
5385 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005386
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005387 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005388 return;
5389 if (!ExprLooksBoolean(CondRHS))
5390 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005391
Hans Wennborg2f072b42011-06-09 17:06:51 +00005392 // The condition is an arithmetic binary expression, with a right-
5393 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005394
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005395 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005396 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005397 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005398
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005399 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00005400 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005401 << BinaryOperator::getOpcodeStr(CondOpcode),
5402 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005403
5404 SuggestParentheses(Self, OpLoc,
5405 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005406 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005407}
5408
Steve Narofff69936d2007-09-16 03:34:24 +00005409/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005410/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005411ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005412 SourceLocation ColonLoc,
5413 Expr *CondExpr, Expr *LHSExpr,
5414 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005415 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5416 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005417 OpaqueValueExpr *opaqueValue = 0;
5418 Expr *commonExpr = 0;
5419 if (LHSExpr == 0) {
5420 commonExpr = CondExpr;
5421
5422 // We usually want to apply unary conversions *before* saving, except
5423 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005424 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005425 && !commonExpr->isTypeDependent()
5426 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5427 && commonExpr->isGLValue()
5428 && commonExpr->isOrdinaryOrBitFieldObject()
5429 && RHSExpr->isOrdinaryOrBitFieldObject()
5430 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005431 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5432 if (commonRes.isInvalid())
5433 return ExprError();
5434 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005435 }
5436
5437 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5438 commonExpr->getType(),
5439 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005440 commonExpr->getObjectKind(),
5441 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005442 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005443 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005444
John McCallf89e55a2010-11-18 06:31:45 +00005445 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005446 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005447 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5448 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005449 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005450 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5451 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005452 return ExprError();
5453
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005454 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5455 RHS.get());
5456
John McCall56ca35d2011-02-17 10:25:35 +00005457 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005458 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5459 LHS.take(), ColonLoc,
5460 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005461
5462 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005463 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005464 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5465 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005466}
5467
John McCalle4be87e2011-01-31 23:13:11 +00005468// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005469// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005470// routine is it effectively iqnores the qualifiers on the top level pointee.
5471// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5472// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005473static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005474checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5475 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5476 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005477
Reid Spencer5f016e22007-07-11 17:01:13 +00005478 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005479 const Type *lhptee, *rhptee;
5480 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005481 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5482 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005483
John McCalle4be87e2011-01-31 23:13:11 +00005484 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005485
5486 // C99 6.5.16.1p1: This following citation is common to constraints
5487 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5488 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005489 Qualifiers lq;
5490
John McCallf85e1932011-06-15 23:02:42 +00005491 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5492 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5493 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5494 // Ignore lifetime for further calculation.
5495 lhq.removeObjCLifetime();
5496 rhq.removeObjCLifetime();
5497 }
5498
John McCall86c05f32011-02-01 00:10:29 +00005499 if (!lhq.compatiblyIncludes(rhq)) {
5500 // Treat address-space mismatches as fatal. TODO: address subspaces
5501 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5502 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5503
John McCallf85e1932011-06-15 23:02:42 +00005504 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005505 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005506 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005507 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005508 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005509 && (lhptee->isVoidType() || rhptee->isVoidType()))
5510 ; // keep old
5511
John McCallf85e1932011-06-15 23:02:42 +00005512 // Treat lifetime mismatches as fatal.
5513 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5514 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5515
John McCall86c05f32011-02-01 00:10:29 +00005516 // For GCC compatibility, other qualifier mismatches are treated
5517 // as still compatible in C.
5518 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5519 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005520
Mike Stumpeed9cac2009-02-19 03:04:26 +00005521 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5522 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005523 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005524 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005525 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005526 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005527
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005528 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005529 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005530 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005531 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005532
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005533 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005534 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005535 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005536
5537 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005538 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005539 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005540 }
John McCall86c05f32011-02-01 00:10:29 +00005541
Mike Stumpeed9cac2009-02-19 03:04:26 +00005542 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005543 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005544 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5545 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005546 // Check if the pointee types are compatible ignoring the sign.
5547 // We explicitly check for char so that we catch "char" vs
5548 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005549 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005550 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005551 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005552 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005553
Chris Lattner6a2b9262009-10-17 20:33:28 +00005554 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005555 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005556 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005557 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005558
John McCall86c05f32011-02-01 00:10:29 +00005559 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005560 // Types are compatible ignoring the sign. Qualifier incompatibility
5561 // takes priority over sign incompatibility because the sign
5562 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005563 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005564 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005565
John McCalle4be87e2011-01-31 23:13:11 +00005566 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005567 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005568
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005569 // If we are a multi-level pointer, it's possible that our issue is simply
5570 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5571 // the eventual target type is the same and the pointers have the same
5572 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005573 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005574 do {
John McCall86c05f32011-02-01 00:10:29 +00005575 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5576 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005577 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005578
John McCall86c05f32011-02-01 00:10:29 +00005579 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005580 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005581 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005582
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005583 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005584 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005585 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005586 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005587 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5588 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005589 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005590}
5591
John McCalle4be87e2011-01-31 23:13:11 +00005592/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005593/// block pointer types are compatible or whether a block and normal pointer
5594/// are compatible. It is more restrict than comparing two function pointer
5595// types.
John McCalle4be87e2011-01-31 23:13:11 +00005596static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005597checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5598 QualType RHSType) {
5599 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5600 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005601
Steve Naroff1c7d0672008-09-04 15:10:53 +00005602 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005603
Steve Naroff1c7d0672008-09-04 15:10:53 +00005604 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005605 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5606 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005607
John McCalle4be87e2011-01-31 23:13:11 +00005608 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005609 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005610 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005611
John McCalle4be87e2011-01-31 23:13:11 +00005612 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005613
Steve Naroff1c7d0672008-09-04 15:10:53 +00005614 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005615 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5616 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005617
Richard Trieu1da27a12011-09-06 20:21:22 +00005618 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005619 return Sema::IncompatibleBlockPointer;
5620
Steve Naroff1c7d0672008-09-04 15:10:53 +00005621 return ConvTy;
5622}
5623
John McCalle4be87e2011-01-31 23:13:11 +00005624/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005625/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005626static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005627checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5628 QualType RHSType) {
5629 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5630 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005631
Richard Trieu1da27a12011-09-06 20:21:22 +00005632 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005633 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005634 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5635 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005636 return Sema::IncompatiblePointer;
5637 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005638 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005639 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005640 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5641 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005642 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005643 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005644 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005645 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5646 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005647
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005648 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5649 // make an exception for id<P>
5650 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005651 return Sema::CompatiblePointerDiscardsQualifiers;
5652
Richard Trieu1da27a12011-09-06 20:21:22 +00005653 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005654 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005655 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005656 return Sema::IncompatibleObjCQualifiedId;
5657 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005658}
5659
John McCall1c23e912010-11-16 02:32:08 +00005660Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005661Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005662 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005663 // Fake up an opaque expression. We don't actually care about what
5664 // cast operations are required, so if CheckAssignmentConstraints
5665 // adds casts to this they'll be wasted, but fortunately that doesn't
5666 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005667 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5668 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005669 CastKind K = CK_Invalid;
5670
Richard Trieu1da27a12011-09-06 20:21:22 +00005671 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005672}
5673
Mike Stumpeed9cac2009-02-19 03:04:26 +00005674/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5675/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005676/// pointers. Here are some objectionable examples that GCC considers warnings:
5677///
5678/// int a, *pint;
5679/// short *pshort;
5680/// struct foo *pfoo;
5681///
5682/// pint = pshort; // warning: assignment from incompatible pointer type
5683/// a = pint; // warning: assignment makes integer from pointer without a cast
5684/// pint = a; // warning: assignment makes pointer from integer without a cast
5685/// pint = pfoo; // warning: assignment from incompatible pointer type
5686///
5687/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005688/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005689///
John McCalldaa8e4e2010-11-15 09:13:47 +00005690/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005691Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005692Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005693 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005694 QualType RHSType = RHS.get()->getType();
5695 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005696
Chris Lattnerfc144e22008-01-04 23:18:45 +00005697 // Get canonical types. We're not formatting these types, just comparing
5698 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005699 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5700 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005701
John McCallb6cfa242011-01-31 22:28:28 +00005702 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005703 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005704 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005705 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005706 }
5707
Eli Friedman860a3192012-06-16 02:19:17 +00005708 // If we have an atomic type, try a non-atomic assignment, then just add an
5709 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005710 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005711 Sema::AssignConvertType result =
5712 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5713 if (result != Compatible)
5714 return result;
5715 if (Kind != CK_NoOp)
5716 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5717 Kind = CK_NonAtomicToAtomic;
5718 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005719 }
5720
Douglas Gregor9d293df2008-10-28 00:22:11 +00005721 // If the left-hand side is a reference type, then we are in a
5722 // (rare!) case where we've allowed the use of references in C,
5723 // e.g., as a parameter type in a built-in function. In this case,
5724 // just make sure that the type referenced is compatible with the
5725 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005726 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005727 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005728 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5729 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005730 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005731 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005732 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005733 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005734 }
John McCallb6cfa242011-01-31 22:28:28 +00005735
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005736 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5737 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005738 if (LHSType->isExtVectorType()) {
5739 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005740 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005741 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005742 // CK_VectorSplat does T -> vector T, so first cast to the
5743 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005744 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5745 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005746 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005747 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005748 }
5749 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005750 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005751 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005752 }
Mike Stump1eb44332009-09-09 15:08:12 +00005753
John McCallb6cfa242011-01-31 22:28:28 +00005754 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005755 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5756 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005757 // Allow assignments of an AltiVec vector type to an equivalent GCC
5758 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005759 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005760 Kind = CK_BitCast;
5761 return Compatible;
5762 }
5763
Douglas Gregor255210e2010-08-06 10:14:59 +00005764 // If we are allowing lax vector conversions, and LHS and RHS are both
5765 // vectors, the total size only needs to be the same. This is a bitcast;
5766 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005767 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005768 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005769 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005770 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005771 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005772 }
5773 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005774 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005775
John McCallb6cfa242011-01-31 22:28:28 +00005776 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005777 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005778 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005779 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005780 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005781 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005782
John McCallb6cfa242011-01-31 22:28:28 +00005783 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005784 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005785 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005786 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005787 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005788 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005789 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005790
John McCallb6cfa242011-01-31 22:28:28 +00005791 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005792 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005793 Kind = CK_IntegralToPointer; // FIXME: null?
5794 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005795 }
John McCallb6cfa242011-01-31 22:28:28 +00005796
5797 // C pointers are not compatible with ObjC object pointers,
5798 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005799 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005800 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005801 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005802 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005803 return Compatible;
5804 }
5805
5806 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005807 if (RHSType->isObjCClassType() &&
5808 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005809 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005810 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005811 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005812 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005813
John McCallb6cfa242011-01-31 22:28:28 +00005814 Kind = CK_BitCast;
5815 return IncompatiblePointer;
5816 }
5817
5818 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005819 if (RHSType->getAs<BlockPointerType>()) {
5820 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005821 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005822 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005823 }
Steve Naroffb4406862008-09-29 18:10:17 +00005824 }
John McCallb6cfa242011-01-31 22:28:28 +00005825
Steve Naroff1c7d0672008-09-04 15:10:53 +00005826 return Incompatible;
5827 }
5828
John McCallb6cfa242011-01-31 22:28:28 +00005829 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005830 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005831 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005832 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005833 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005834 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005835 }
5836
5837 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005838 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005839 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005840 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005841 }
5842
John McCallb6cfa242011-01-31 22:28:28 +00005843 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005844 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005845 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005846 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005847 }
Steve Naroffb4406862008-09-29 18:10:17 +00005848
John McCallb6cfa242011-01-31 22:28:28 +00005849 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005850 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005851 if (RHSPT->getPointeeType()->isVoidType()) {
5852 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005853 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005854 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005855
Chris Lattnerfc144e22008-01-04 23:18:45 +00005856 return Incompatible;
5857 }
5858
John McCallb6cfa242011-01-31 22:28:28 +00005859 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005860 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005861 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005862 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005863 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005864 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005865 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005866 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005867 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005868 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005869 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005870 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005871 }
5872
5873 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005874 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005875 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005876 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005877 }
5878
John McCallb6cfa242011-01-31 22:28:28 +00005879 // In general, C pointers are not compatible with ObjC object pointers,
5880 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005881 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005882 Kind = CK_CPointerToObjCPointerCast;
5883
John McCallb6cfa242011-01-31 22:28:28 +00005884 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005885 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005886 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005887 }
5888
5889 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005890 if (LHSType->isObjCClassType() &&
5891 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005892 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005893 return Compatible;
5894 }
5895
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005896 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005897 }
John McCallb6cfa242011-01-31 22:28:28 +00005898
5899 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005900 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005901 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005902 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005903 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005904 }
5905
Steve Naroff14108da2009-07-10 23:34:53 +00005906 return Incompatible;
5907 }
John McCallb6cfa242011-01-31 22:28:28 +00005908
5909 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005910 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005911 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005912 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005913 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005914 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005915 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005916
John McCallb6cfa242011-01-31 22:28:28 +00005917 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005918 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005919 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005920 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005921 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005922
Chris Lattnerfc144e22008-01-04 23:18:45 +00005923 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005924 }
John McCallb6cfa242011-01-31 22:28:28 +00005925
5926 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005927 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005928 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005929 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005930 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005931 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005932 }
Steve Naroff14108da2009-07-10 23:34:53 +00005933
John McCallb6cfa242011-01-31 22:28:28 +00005934 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005935 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005936 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005937 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005938 }
5939
Steve Naroff14108da2009-07-10 23:34:53 +00005940 return Incompatible;
5941 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005942
John McCallb6cfa242011-01-31 22:28:28 +00005943 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005944 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5945 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005946 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005947 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005948 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005949 }
John McCallb6cfa242011-01-31 22:28:28 +00005950
Reid Spencer5f016e22007-07-11 17:01:13 +00005951 return Incompatible;
5952}
5953
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005954/// \brief Constructs a transparent union from an expression that is
5955/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005956static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5957 ExprResult &EResult, QualType UnionType,
5958 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005959 // Build an initializer list that designates the appropriate member
5960 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005961 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005962 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005963 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005964 Initializer->setType(UnionType);
5965 Initializer->setInitializedFieldInUnion(Field);
5966
5967 // Build a compound literal constructing a value of the transparent
5968 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005969 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005970 EResult = S.Owned(
5971 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5972 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005973}
5974
5975Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005976Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005977 ExprResult &RHS) {
5978 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005979
Mike Stump1eb44332009-09-09 15:08:12 +00005980 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005981 // transparent_union GCC extension.
5982 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005983 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005984 return Incompatible;
5985
5986 // The field to initialize within the transparent union.
5987 RecordDecl *UD = UT->getDecl();
5988 FieldDecl *InitField = 0;
5989 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005990 for (RecordDecl::field_iterator it = UD->field_begin(),
5991 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005992 it != itend; ++it) {
5993 if (it->getType()->isPointerType()) {
5994 // If the transparent union contains a pointer type, we allow:
5995 // 1) void pointer
5996 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005997 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005998 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005999 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00006000 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006001 break;
6002 }
Mike Stump1eb44332009-09-09 15:08:12 +00006003
Richard Trieuf7720da2011-09-06 20:40:12 +00006004 if (RHS.get()->isNullPointerConstant(Context,
6005 Expr::NPC_ValueDependentIsNull)) {
6006 RHS = ImpCastExprToType(RHS.take(), it->getType(),
6007 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00006008 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006009 break;
6010 }
6011 }
6012
John McCalldaa8e4e2010-11-15 09:13:47 +00006013 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00006014 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006015 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00006016 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00006017 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006018 break;
6019 }
6020 }
6021
6022 if (!InitField)
6023 return Incompatible;
6024
Richard Trieuf7720da2011-09-06 20:40:12 +00006025 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006026 return Compatible;
6027}
6028
Chris Lattner5cf216b2008-01-04 18:04:52 +00006029Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00006030Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6031 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006032 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00006033 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006034 // C++ 5.17p3: If the left operand is not of class type, the
6035 // expression is implicitly converted (C++ 4) to the
6036 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00006037 ExprResult Res;
6038 if (Diagnose) {
6039 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6040 AA_Assigning);
6041 } else {
6042 ImplicitConversionSequence ICS =
6043 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6044 /*SuppressUserConversions=*/false,
6045 /*AllowExplicit=*/false,
6046 /*InOverloadResolution=*/false,
6047 /*CStyle=*/false,
6048 /*AllowObjCWritebackConversion=*/false);
6049 if (ICS.isFailure())
6050 return Incompatible;
6051 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6052 ICS, AA_Assigning);
6053 }
John Wiegley429bb272011-04-08 18:41:53 +00006054 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006055 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00006056 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00006057 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00006058 !CheckObjCARCUnavailableWeakConversion(LHSType,
6059 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00006060 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006061 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00006062 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006063 }
6064
6065 // FIXME: Currently, we fall through and treat C++ classes like C
6066 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00006067 // FIXME: We also fall through for atomics; not sure what should
6068 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00006069 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006070
Steve Naroff529a4ad2007-11-27 17:58:44 +00006071 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6072 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00006073 if ((LHSType->isPointerType() ||
6074 LHSType->isObjCObjectPointerType() ||
6075 LHSType->isBlockPointerType())
6076 && RHS.get()->isNullPointerConstant(Context,
6077 Expr::NPC_ValueDependentIsNull)) {
6078 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006079 return Compatible;
6080 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006081
Chris Lattner943140e2007-10-16 02:55:40 +00006082 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006083 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006084 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006085 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006086 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006087 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00006088 if (!LHSType->isReferenceType()) {
6089 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6090 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006091 return Incompatible;
6092 }
Steve Narofff1120de2007-08-24 22:33:52 +00006093
John McCalldaa8e4e2010-11-15 09:13:47 +00006094 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006095 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00006096 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006097
Steve Narofff1120de2007-08-24 22:33:52 +00006098 // C99 6.5.16.1p2: The value of the right operand is converted to the
6099 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006100 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6101 // so that we can use references in built-in functions even in C.
6102 // The getNonReferenceType() call makes sure that the resulting expression
6103 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00006104 if (result != Incompatible && RHS.get()->getType() != LHSType)
6105 RHS = ImpCastExprToType(RHS.take(),
6106 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006107 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006108}
6109
Richard Trieuf7720da2011-09-06 20:40:12 +00006110QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6111 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006112 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00006113 << LHS.get()->getType() << RHS.get()->getType()
6114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006115 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006116}
6117
Richard Trieu08062aa2011-09-06 21:01:04 +00006118QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006119 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00006120 if (!IsCompAssign) {
6121 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6122 if (LHS.isInvalid())
6123 return QualType();
6124 }
6125 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6126 if (RHS.isInvalid())
6127 return QualType();
6128
Mike Stumpeed9cac2009-02-19 03:04:26 +00006129 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006130 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00006131 QualType LHSType =
6132 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6133 QualType RHSType =
6134 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006135
Nate Begemanbe2341d2008-07-14 18:02:46 +00006136 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006137 if (LHSType == RHSType)
6138 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006139
Douglas Gregor255210e2010-08-06 10:14:59 +00006140 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006141 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6142 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6143 if (LHSType->isExtVectorType()) {
6144 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6145 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006146 }
6147
Richard Trieuccd891a2011-09-09 01:45:06 +00006148 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006149 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6150 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006151 }
6152
David Blaikie4e4d0842012-03-11 07:00:24 +00006153 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006154 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006155 // If we are allowing lax vector conversions, and LHS and RHS are both
6156 // vectors, the total size only needs to be the same. This is a
6157 // bitcast; no bits are changed but the result type is different.
6158 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006159 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6160 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006161 }
6162
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006163 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6164 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6165 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006166 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006167 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006168 std::swap(RHS, LHS);
6169 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006170 }
Mike Stump1eb44332009-09-09 15:08:12 +00006171
Nate Begemandde25982009-06-28 19:12:57 +00006172 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006173 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006174 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006175 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6176 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006177 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006178 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006179 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006180 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6181 if (swapped) std::swap(RHS, LHS);
6182 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006183 }
6184 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006185 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6186 RHSType->isRealFloatingType()) {
6187 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006188 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006189 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006190 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006191 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6192 if (swapped) std::swap(RHS, LHS);
6193 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006194 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006195 }
6196 }
Mike Stump1eb44332009-09-09 15:08:12 +00006197
Nate Begemandde25982009-06-28 19:12:57 +00006198 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006199 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006200 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006201 << LHS.get()->getType() << RHS.get()->getType()
6202 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006203 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006204}
6205
Richard Trieu481037f2011-09-16 00:53:10 +00006206// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6207// expression. These are mainly cases where the null pointer is used as an
6208// integer instead of a pointer.
6209static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6210 SourceLocation Loc, bool IsCompare) {
6211 // The canonical way to check for a GNU null is with isNullPointerConstant,
6212 // but we use a bit of a hack here for speed; this is a relatively
6213 // hot path, and isNullPointerConstant is slow.
6214 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6215 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6216
6217 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6218
6219 // Avoid analyzing cases where the result will either be invalid (and
6220 // diagnosed as such) or entirely valid and not something to warn about.
6221 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6222 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6223 return;
6224
6225 // Comparison operations would not make sense with a null pointer no matter
6226 // what the other expression is.
6227 if (!IsCompare) {
6228 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6229 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6230 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6231 return;
6232 }
6233
6234 // The rest of the operations only make sense with a null pointer
6235 // if the other expression is a pointer.
6236 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6237 NonNullType->canDecayToPointerType())
6238 return;
6239
6240 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6241 << LHSNull /* LHS is NULL */ << NonNullType
6242 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6243}
6244
Richard Trieu08062aa2011-09-06 21:01:04 +00006245QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006246 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006247 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006248 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6249
Richard Trieu08062aa2011-09-06 21:01:04 +00006250 if (LHS.get()->getType()->isVectorType() ||
6251 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006252 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006253
Richard Trieuccd891a2011-09-09 01:45:06 +00006254 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006255 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006256 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006257
David Chisnall7a7ee302012-01-16 17:27:18 +00006258
Eli Friedman860a3192012-06-16 02:19:17 +00006259 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006260 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006261
Chris Lattner7ef655a2010-01-12 21:23:57 +00006262 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006263 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006264 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006265 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006266 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6267 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006268
Chris Lattner7ef655a2010-01-12 21:23:57 +00006269 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006270}
6271
Chris Lattner7ef655a2010-01-12 21:23:57 +00006272QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006273 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006274 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6275
Richard Trieu08062aa2011-09-06 21:01:04 +00006276 if (LHS.get()->getType()->isVectorType() ||
6277 RHS.get()->getType()->isVectorType()) {
6278 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6279 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006280 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006281 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006282 }
Steve Naroff90045e82007-07-13 23:32:42 +00006283
Richard Trieuccd891a2011-09-09 01:45:06 +00006284 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006285 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006286 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006287
Eli Friedman860a3192012-06-16 02:19:17 +00006288 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006289 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006290
Chris Lattner7ef655a2010-01-12 21:23:57 +00006291 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006292 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006293 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006294 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6295 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006296
Chris Lattner7ef655a2010-01-12 21:23:57 +00006297 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006298}
6299
Chandler Carruth13b21be2011-06-27 08:02:19 +00006300/// \brief Diagnose invalid arithmetic on two void pointers.
6301static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006302 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006303 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006304 ? diag::err_typecheck_pointer_arith_void_type
6305 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006306 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6307 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006308}
6309
6310/// \brief Diagnose invalid arithmetic on a void pointer.
6311static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6312 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006313 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006314 ? diag::err_typecheck_pointer_arith_void_type
6315 : diag::ext_gnu_void_ptr)
6316 << 0 /* one pointer */ << Pointer->getSourceRange();
6317}
6318
6319/// \brief Diagnose invalid arithmetic on two function pointers.
6320static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6321 Expr *LHS, Expr *RHS) {
6322 assert(LHS->getType()->isAnyPointerType());
6323 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006324 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006325 ? diag::err_typecheck_pointer_arith_function_type
6326 : diag::ext_gnu_ptr_func_arith)
6327 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6328 // We only show the second type if it differs from the first.
6329 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6330 RHS->getType())
6331 << RHS->getType()->getPointeeType()
6332 << LHS->getSourceRange() << RHS->getSourceRange();
6333}
6334
6335/// \brief Diagnose invalid arithmetic on a function pointer.
6336static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6337 Expr *Pointer) {
6338 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006339 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006340 ? diag::err_typecheck_pointer_arith_function_type
6341 : diag::ext_gnu_ptr_func_arith)
6342 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6343 << 0 /* one pointer, so only one type */
6344 << Pointer->getSourceRange();
6345}
6346
Richard Trieud9f19342011-09-12 18:08:02 +00006347/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006348///
6349/// \returns True if pointer has incomplete type
6350static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6351 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006352 assert(Operand->getType()->isAnyPointerType() &&
6353 !Operand->getType()->isDependentType());
6354 QualType PointeeTy = Operand->getType()->getPointeeType();
6355 return S.RequireCompleteType(Loc, PointeeTy,
6356 diag::err_typecheck_arithmetic_incomplete_type,
6357 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006358}
6359
Chandler Carruth13b21be2011-06-27 08:02:19 +00006360/// \brief Check the validity of an arithmetic pointer operand.
6361///
6362/// If the operand has pointer type, this code will check for pointer types
6363/// which are invalid in arithmetic operations. These will be diagnosed
6364/// appropriately, including whether or not the use is supported as an
6365/// extension.
6366///
6367/// \returns True when the operand is valid to use (even if as an extension).
6368static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6369 Expr *Operand) {
6370 if (!Operand->getType()->isAnyPointerType()) return true;
6371
6372 QualType PointeeTy = Operand->getType()->getPointeeType();
6373 if (PointeeTy->isVoidType()) {
6374 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006375 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006376 }
6377 if (PointeeTy->isFunctionType()) {
6378 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006379 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006380 }
6381
Richard Trieu097ecd22011-09-02 02:15:37 +00006382 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006383
6384 return true;
6385}
6386
6387/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6388/// operands.
6389///
6390/// This routine will diagnose any invalid arithmetic on pointer operands much
6391/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6392/// for emitting a single diagnostic even for operations where both LHS and RHS
6393/// are (potentially problematic) pointers.
6394///
6395/// \returns True when the operand is valid to use (even if as an extension).
6396static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006397 Expr *LHSExpr, Expr *RHSExpr) {
6398 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6399 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006400 if (!isLHSPointer && !isRHSPointer) return true;
6401
6402 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006403 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6404 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006405
6406 // Check for arithmetic on pointers to incomplete types.
6407 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6408 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6409 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006410 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6411 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6412 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006413
David Blaikie4e4d0842012-03-11 07:00:24 +00006414 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006415 }
6416
6417 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6418 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6419 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006420 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6421 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6422 RHSExpr);
6423 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006424
David Blaikie4e4d0842012-03-11 07:00:24 +00006425 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006426 }
6427
John McCall1503f0d2012-07-31 05:14:30 +00006428 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6429 return false;
6430 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6431 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006432
Chandler Carruth13b21be2011-06-27 08:02:19 +00006433 return true;
6434}
6435
Nico Weber1cb2d742012-03-02 22:01:22 +00006436/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6437/// literal.
6438static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6439 Expr *LHSExpr, Expr *RHSExpr) {
6440 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6441 Expr* IndexExpr = RHSExpr;
6442 if (!StrExpr) {
6443 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6444 IndexExpr = LHSExpr;
6445 }
6446
6447 bool IsStringPlusInt = StrExpr &&
6448 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6449 if (!IsStringPlusInt)
6450 return;
6451
6452 llvm::APSInt index;
6453 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6454 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6455 if (index.isNonNegative() &&
6456 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6457 index.isUnsigned()))
6458 return;
6459 }
6460
6461 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6462 Self.Diag(OpLoc, diag::warn_string_plus_int)
6463 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6464
6465 // Only print a fixit for "str" + int, not for int + "str".
6466 if (IndexExpr == RHSExpr) {
6467 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6468 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6469 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6470 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6471 << FixItHint::CreateInsertion(EndLoc, "]");
6472 } else
6473 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6474}
6475
Richard Trieud9f19342011-09-12 18:08:02 +00006476/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006477static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006478 Expr *LHSExpr, Expr *RHSExpr) {
6479 assert(LHSExpr->getType()->isAnyPointerType());
6480 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006481 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006482 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6483 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006484}
6485
Chris Lattner7ef655a2010-01-12 21:23:57 +00006486QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006487 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6488 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006489 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6490
Richard Trieudef75842011-09-06 21:13:51 +00006491 if (LHS.get()->getType()->isVectorType() ||
6492 RHS.get()->getType()->isVectorType()) {
6493 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006494 if (CompLHSTy) *CompLHSTy = compType;
6495 return compType;
6496 }
Steve Naroff49b45262007-07-13 16:58:59 +00006497
Richard Trieudef75842011-09-06 21:13:51 +00006498 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6499 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006500 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006501
Nico Weber1cb2d742012-03-02 22:01:22 +00006502 // Diagnose "string literal" '+' int.
6503 if (Opc == BO_Add)
6504 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6505
Reid Spencer5f016e22007-07-11 17:01:13 +00006506 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006507 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006508 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006509 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006510 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006511
John McCall1503f0d2012-07-31 05:14:30 +00006512 // Type-checking. Ultimately the pointer's going to be in PExp;
6513 // note that we bias towards the LHS being the pointer.
6514 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006515
John McCall1503f0d2012-07-31 05:14:30 +00006516 bool isObjCPointer;
6517 if (PExp->getType()->isPointerType()) {
6518 isObjCPointer = false;
6519 } else if (PExp->getType()->isObjCObjectPointerType()) {
6520 isObjCPointer = true;
6521 } else {
6522 std::swap(PExp, IExp);
6523 if (PExp->getType()->isPointerType()) {
6524 isObjCPointer = false;
6525 } else if (PExp->getType()->isObjCObjectPointerType()) {
6526 isObjCPointer = true;
6527 } else {
6528 return InvalidOperands(Loc, LHS, RHS);
6529 }
6530 }
6531 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006532
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006533 if (!IExp->getType()->isIntegerType())
6534 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006535
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006536 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6537 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006538
John McCall1503f0d2012-07-31 05:14:30 +00006539 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006540 return QualType();
6541
6542 // Check array bounds for pointer arithemtic
6543 CheckArrayAccess(PExp, IExp);
6544
6545 if (CompLHSTy) {
6546 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6547 if (LHSTy.isNull()) {
6548 LHSTy = LHS.get()->getType();
6549 if (LHSTy->isPromotableIntegerType())
6550 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006551 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006552 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006553 }
6554
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006555 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006556}
6557
Chris Lattnereca7be62008-04-07 05:30:13 +00006558// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006559QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006560 SourceLocation Loc,
6561 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006562 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6563
Richard Trieudef75842011-09-06 21:13:51 +00006564 if (LHS.get()->getType()->isVectorType() ||
6565 RHS.get()->getType()->isVectorType()) {
6566 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006567 if (CompLHSTy) *CompLHSTy = compType;
6568 return compType;
6569 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006570
Richard Trieudef75842011-09-06 21:13:51 +00006571 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6572 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006573 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006574
Chris Lattner6e4ab612007-12-09 21:53:25 +00006575 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006576
Chris Lattner6e4ab612007-12-09 21:53:25 +00006577 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006578 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006579 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006580 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006581 }
Mike Stump1eb44332009-09-09 15:08:12 +00006582
Chris Lattner6e4ab612007-12-09 21:53:25 +00006583 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006584 if (LHS.get()->getType()->isAnyPointerType()) {
6585 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006586
Chris Lattnerb5f15622009-04-24 23:50:08 +00006587 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006588 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6589 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006590 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006591
Chris Lattner6e4ab612007-12-09 21:53:25 +00006592 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006593 if (RHS.get()->getType()->isIntegerType()) {
6594 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006595 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006596
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006597 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006598 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6599 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006600
Richard Trieudef75842011-09-06 21:13:51 +00006601 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6602 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006603 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006604
Chris Lattner6e4ab612007-12-09 21:53:25 +00006605 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006606 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006607 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006608 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006609
David Blaikie4e4d0842012-03-11 07:00:24 +00006610 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006611 // Pointee types must be the same: C++ [expr.add]
6612 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006613 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006614 }
6615 } else {
6616 // Pointee types must be compatible C99 6.5.6p3
6617 if (!Context.typesAreCompatible(
6618 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6619 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006620 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006621 return QualType();
6622 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006623 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006624
Chandler Carruth13b21be2011-06-27 08:02:19 +00006625 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006626 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006627 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006628
Richard Trieudef75842011-09-06 21:13:51 +00006629 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006630 return Context.getPointerDiffType();
6631 }
6632 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006633
Richard Trieudef75842011-09-06 21:13:51 +00006634 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006635}
6636
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006637static bool isScopedEnumerationType(QualType T) {
6638 if (const EnumType *ET = dyn_cast<EnumType>(T))
6639 return ET->getDecl()->isScoped();
6640 return false;
6641}
6642
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006643static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006644 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006645 QualType LHSType) {
David Tweed7a834212013-01-07 16:43:27 +00006646 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
6647 // so skip remaining warnings as we don't want to modify values within Sema.
6648 if (S.getLangOpts().OpenCL)
6649 return;
6650
Chandler Carruth21206d52011-02-23 23:34:11 +00006651 llvm::APSInt Right;
6652 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006653 if (RHS.get()->isValueDependent() ||
6654 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006655 return;
6656
6657 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006658 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006659 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006660 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006661 return;
6662 }
6663 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006664 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006665 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006666 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006667 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006668 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006669 return;
6670 }
6671 if (Opc != BO_Shl)
6672 return;
6673
6674 // When left shifting an ICE which is signed, we can check for overflow which
6675 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6676 // integers have defined behavior modulo one more than the maximum value
6677 // representable in the result type, so never warn for those.
6678 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006679 if (LHS.get()->isValueDependent() ||
6680 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6681 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006682 return;
6683 llvm::APInt ResultBits =
6684 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6685 if (LeftBits.uge(ResultBits))
6686 return;
6687 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6688 Result = Result.shl(Right);
6689
Ted Kremenekfa821382011-06-15 00:54:52 +00006690 // Print the bit representation of the signed integer as an unsigned
6691 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006692 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006693 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6694
Chandler Carruth21206d52011-02-23 23:34:11 +00006695 // If we are only missing a sign bit, this is less likely to result in actual
6696 // bugs -- if the result is cast back to an unsigned type, it will have the
6697 // expected value. Thus we place this behind a different warning that can be
6698 // turned off separately if needed.
6699 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006700 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006701 << HexResult.str() << LHSType
6702 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006703 return;
6704 }
6705
6706 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006707 << HexResult.str() << Result.getMinSignedBits() << LHSType
6708 << Left.getBitWidth() << LHS.get()->getSourceRange()
6709 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006710}
6711
Chris Lattnereca7be62008-04-07 05:30:13 +00006712// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006713QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006714 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006715 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006716 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6717
Chris Lattnerca5eede2007-12-12 05:47:28 +00006718 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006719 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6720 !RHS.get()->getType()->hasIntegerRepresentation())
6721 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006722
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006723 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6724 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006725 if (isScopedEnumerationType(LHS.get()->getType()) ||
6726 isScopedEnumerationType(RHS.get()->getType())) {
6727 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006728 }
6729
Nate Begeman2207d792009-10-25 02:26:48 +00006730 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006731 if (LHS.get()->getType()->isVectorType() ||
6732 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006733 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006734
Chris Lattnerca5eede2007-12-12 05:47:28 +00006735 // Shifts don't perform usual arithmetic conversions, they just do integer
6736 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006737
John McCall1bc80af2010-12-16 19:28:59 +00006738 // For the LHS, do usual unary conversions, but then reset them away
6739 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006740 ExprResult OldLHS = LHS;
6741 LHS = UsualUnaryConversions(LHS.take());
6742 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006743 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006744 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006745 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006746
6747 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006748 RHS = UsualUnaryConversions(RHS.take());
6749 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006750 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006751
Ryan Flynnd0439682009-08-07 16:20:20 +00006752 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006753 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006754
Chris Lattnerca5eede2007-12-12 05:47:28 +00006755 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006756 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006757}
6758
Chandler Carruth99919472010-07-10 12:30:03 +00006759static bool IsWithinTemplateSpecialization(Decl *D) {
6760 if (DeclContext *DC = D->getDeclContext()) {
6761 if (isa<ClassTemplateSpecializationDecl>(DC))
6762 return true;
6763 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6764 return FD->isFunctionTemplateSpecialization();
6765 }
6766 return false;
6767}
6768
Richard Trieue648ac32011-09-02 03:48:46 +00006769/// If two different enums are compared, raise a warning.
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00006770static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
6771 Expr *RHS) {
6772 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
6773 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006774
6775 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6776 if (!LHSEnumType)
6777 return;
6778 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6779 if (!RHSEnumType)
6780 return;
6781
6782 // Ignore anonymous enums.
6783 if (!LHSEnumType->getDecl()->getIdentifier())
6784 return;
6785 if (!RHSEnumType->getDecl()->getIdentifier())
6786 return;
6787
6788 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6789 return;
6790
6791 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6792 << LHSStrippedType << RHSStrippedType
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00006793 << LHS->getSourceRange() << RHS->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006794}
6795
Richard Trieu7be1be02011-09-02 02:55:45 +00006796/// \brief Diagnose bad pointer comparisons.
6797static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006798 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006799 bool IsError) {
6800 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006801 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006802 << LHS.get()->getType() << RHS.get()->getType()
6803 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006804}
6805
6806/// \brief Returns false if the pointers are converted to a composite type,
6807/// true otherwise.
6808static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006809 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006810 // C++ [expr.rel]p2:
6811 // [...] Pointer conversions (4.10) and qualification
6812 // conversions (4.4) are performed on pointer operands (or on
6813 // a pointer operand and a null pointer constant) to bring
6814 // them to their composite pointer type. [...]
6815 //
6816 // C++ [expr.eq]p1 uses the same notion for (in)equality
6817 // comparisons of pointers.
6818
6819 // C++ [expr.eq]p2:
6820 // In addition, pointers to members can be compared, or a pointer to
6821 // member and a null pointer constant. Pointer to member conversions
6822 // (4.11) and qualification conversions (4.4) are performed to bring
6823 // them to a common type. If one operand is a null pointer constant,
6824 // the common type is the type of the other operand. Otherwise, the
6825 // common type is a pointer to member type similar (4.4) to the type
6826 // of one of the operands, with a cv-qualification signature (4.4)
6827 // that is the union of the cv-qualification signatures of the operand
6828 // types.
6829
Richard Trieuba261492011-09-06 21:27:33 +00006830 QualType LHSType = LHS.get()->getType();
6831 QualType RHSType = RHS.get()->getType();
6832 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6833 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006834
6835 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006836 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006837 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006838 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006839 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006840 return true;
6841 }
6842
6843 if (NonStandardCompositeType)
6844 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006845 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6846 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006847
Richard Trieuba261492011-09-06 21:27:33 +00006848 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6849 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006850 return false;
6851}
6852
6853static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006854 ExprResult &LHS,
6855 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006856 bool IsError) {
6857 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6858 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006859 << LHS.get()->getType() << RHS.get()->getType()
6860 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006861}
6862
Jordan Rose9f63a452012-06-08 21:14:25 +00006863static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rose87da0b72012-11-09 23:55:21 +00006864 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rose9f63a452012-06-08 21:14:25 +00006865 case Stmt::ObjCArrayLiteralClass:
6866 case Stmt::ObjCDictionaryLiteralClass:
6867 case Stmt::ObjCStringLiteralClass:
6868 case Stmt::ObjCBoxedExprClass:
6869 return true;
6870 default:
6871 // Note that ObjCBoolLiteral is NOT an object literal!
6872 return false;
6873 }
6874}
6875
Jordan Rose8d872ca2012-07-17 17:46:40 +00006876static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
Benjamin Kramer2e85e742013-02-15 15:17:50 +00006877 const ObjCObjectPointerType *Type =
6878 LHS->getType()->getAs<ObjCObjectPointerType>();
6879
6880 // If this is not actually an Objective-C object, bail out.
6881 if (!Type)
Jordan Rose8d872ca2012-07-17 17:46:40 +00006882 return false;
Benjamin Kramer2e85e742013-02-15 15:17:50 +00006883
6884 // Get the LHS object's interface type.
6885 QualType InterfaceType = Type->getPointeeType();
6886 if (const ObjCObjectType *iQFaceTy =
6887 InterfaceType->getAsObjCQualifiedInterfaceType())
6888 InterfaceType = iQFaceTy->getBaseType();
Jordan Rose8d872ca2012-07-17 17:46:40 +00006889
6890 // If the RHS isn't an Objective-C object, bail out.
6891 if (!RHS->getType()->isObjCObjectPointerType())
6892 return false;
6893
6894 // Try to find the -isEqual: method.
6895 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6896 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6897 InterfaceType,
6898 /*instance=*/true);
6899 if (!Method) {
6900 if (Type->isObjCIdType()) {
6901 // For 'id', just check the global pool.
6902 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6903 /*receiverId=*/true,
6904 /*warn=*/false);
6905 } else {
6906 // Check protocols.
Benjamin Kramer2e85e742013-02-15 15:17:50 +00006907 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
Jordan Rose8d872ca2012-07-17 17:46:40 +00006908 /*instance=*/true);
6909 }
6910 }
6911
6912 if (!Method)
6913 return false;
6914
6915 QualType T = Method->param_begin()[0]->getType();
6916 if (!T->isObjCObjectPointerType())
6917 return false;
6918
6919 QualType R = Method->getResultType();
6920 if (!R->isScalarType())
6921 return false;
6922
6923 return true;
6924}
6925
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006926Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
6927 FromE = FromE->IgnoreParenImpCasts();
6928 switch (FromE->getStmtClass()) {
6929 default:
6930 break;
6931 case Stmt::ObjCStringLiteralClass:
6932 // "string literal"
6933 return LK_String;
6934 case Stmt::ObjCArrayLiteralClass:
6935 // "array literal"
6936 return LK_Array;
6937 case Stmt::ObjCDictionaryLiteralClass:
6938 // "dictionary literal"
6939 return LK_Dictionary;
Ted Kremenekd3292c82012-12-21 22:46:35 +00006940 case Stmt::BlockExprClass:
6941 return LK_Block;
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006942 case Stmt::ObjCBoxedExprClass: {
Ted Kremenekf530ff72012-12-21 21:59:39 +00006943 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006944 switch (Inner->getStmtClass()) {
6945 case Stmt::IntegerLiteralClass:
6946 case Stmt::FloatingLiteralClass:
6947 case Stmt::CharacterLiteralClass:
6948 case Stmt::ObjCBoolLiteralExprClass:
6949 case Stmt::CXXBoolLiteralExprClass:
6950 // "numeric literal"
6951 return LK_Numeric;
6952 case Stmt::ImplicitCastExprClass: {
6953 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6954 // Boolean literals can be represented by implicit casts.
6955 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
6956 return LK_Numeric;
6957 break;
6958 }
6959 default:
6960 break;
6961 }
6962 return LK_Boxed;
6963 }
6964 }
6965 return LK_None;
6966}
6967
Jordan Rose8d872ca2012-07-17 17:46:40 +00006968static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6969 ExprResult &LHS, ExprResult &RHS,
6970 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006971 Expr *Literal;
6972 Expr *Other;
6973 if (isObjCObjectLiteral(LHS)) {
6974 Literal = LHS.get();
6975 Other = RHS.get();
6976 } else {
6977 Literal = RHS.get();
6978 Other = LHS.get();
6979 }
6980
6981 // Don't warn on comparisons against nil.
6982 Other = Other->IgnoreParenCasts();
6983 if (Other->isNullPointerConstant(S.getASTContext(),
6984 Expr::NPC_ValueDependentIsNotNull))
6985 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006986
Jordan Roseeec207f2012-07-17 17:46:44 +00006987 // This should be kept in sync with warn_objc_literal_comparison.
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006988 // LK_String should always be after the other literals, since it has its own
6989 // warning flag.
6990 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
Ted Kremenekd3292c82012-12-21 22:46:35 +00006991 assert(LiteralKind != Sema::LK_Block);
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006992 if (LiteralKind == Sema::LK_None) {
Jordan Rose9f63a452012-06-08 21:14:25 +00006993 llvm_unreachable("Unknown Objective-C object literal kind");
6994 }
6995
Ted Kremenek3ee069b2012-12-21 21:59:36 +00006996 if (LiteralKind == Sema::LK_String)
Jordan Roseeec207f2012-07-17 17:46:44 +00006997 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6998 << Literal->getSourceRange();
6999 else
7000 S.Diag(Loc, diag::warn_objc_literal_comparison)
7001 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00007002
Jordan Rose8d872ca2012-07-17 17:46:40 +00007003 if (BinaryOperator::isEqualityOp(Opc) &&
7004 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7005 SourceLocation Start = LHS.get()->getLocStart();
7006 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian41f7b1a2013-02-01 20:04:49 +00007007 CharSourceRange OpRange =
7008 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00007009
Jordan Rose8d872ca2012-07-17 17:46:40 +00007010 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7011 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
Fariborz Jahanian41f7b1a2013-02-01 20:04:49 +00007012 << FixItHint::CreateReplacement(OpRange, " isEqual:")
Jordan Rose8d872ca2012-07-17 17:46:40 +00007013 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00007014 }
Jordan Rose9f63a452012-06-08 21:14:25 +00007015}
7016
Douglas Gregor0c6db942009-05-04 06:07:12 +00007017// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00007018QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00007019 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007020 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00007021 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7022
John McCall2de56d12010-08-25 11:45:40 +00007023 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007024
Chris Lattner02dd4b12009-12-05 05:40:13 +00007025 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007026 if (LHS.get()->getType()->isVectorType() ||
7027 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00007028 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007029
Richard Trieuf1775fb2011-09-06 21:43:51 +00007030 QualType LHSType = LHS.get()->getType();
7031 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00007032
Richard Trieuf1775fb2011-09-06 21:43:51 +00007033 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7034 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007035
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00007036 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
Chandler Carruth543cb652011-02-17 08:37:06 +00007037
Richard Trieuf1775fb2011-09-06 21:43:51 +00007038 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00007039 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007040 !LHS.get()->getLocStart().isMacroID() &&
7041 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007042 // For non-floating point types, check for self-comparisons of the form
7043 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7044 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007045 //
7046 // NOTE: Don't warn about comparison expressions resulting from macro
7047 // expansion. Also don't warn about comparisons which are only self
7048 // comparisons within a template specialization. The warnings should catch
7049 // obvious cases in the definition of the template anyways. The idea is to
7050 // warn when the typed comparison operator will always evaluate to the same
7051 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007052 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007053 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007054 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007055 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007056 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007057 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007058 << (Opc == BO_EQ
7059 || Opc == BO_LE
7060 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00007061 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00007062 !DRL->getDecl()->getType()->isReferenceType() &&
7063 !DRR->getDecl()->getType()->isReferenceType()) {
7064 // what is it always going to eval to?
7065 char always_evals_to;
7066 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007067 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007068 always_evals_to = 0; // false
7069 break;
John McCall2de56d12010-08-25 11:45:40 +00007070 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007071 always_evals_to = 1; // true
7072 break;
7073 default:
7074 // best we can say is 'a constant'
7075 always_evals_to = 2; // e.g. array1 <= array2
7076 break;
7077 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007078 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007079 << 1 // array
7080 << always_evals_to);
7081 }
7082 }
Chandler Carruth99919472010-07-10 12:30:03 +00007083 }
Mike Stump1eb44332009-09-09 15:08:12 +00007084
Chris Lattner55660a72009-03-08 19:39:53 +00007085 if (isa<CastExpr>(LHSStripped))
7086 LHSStripped = LHSStripped->IgnoreParenCasts();
7087 if (isa<CastExpr>(RHSStripped))
7088 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007089
Chris Lattner55660a72009-03-08 19:39:53 +00007090 // Warn about comparisons against a string constant (unless the other
7091 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007092 Expr *literalString = 0;
7093 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007094 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007095 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007096 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007097 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007098 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007099 } else if ((isa<StringLiteral>(RHSStripped) ||
7100 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007101 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007102 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007103 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007104 literalStringStripped = RHSStripped;
7105 }
7106
7107 if (literalString) {
7108 std::string resultComparison;
7109 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007110 case BO_LT: resultComparison = ") < 0"; break;
7111 case BO_GT: resultComparison = ") > 0"; break;
7112 case BO_LE: resultComparison = ") <= 0"; break;
7113 case BO_GE: resultComparison = ") >= 0"; break;
7114 case BO_EQ: resultComparison = ") == 0"; break;
7115 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00007116 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00007117 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007118
Ted Kremenek351ba912011-02-23 01:52:04 +00007119 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007120 PDiag(diag::warn_stringcompare)
7121 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007122 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007123 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007124 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007125
Douglas Gregord64fdd02010-06-08 19:50:34 +00007126 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00007127 if (LHS.get()->getType()->isArithmeticType() &&
7128 RHS.get()->getType()->isArithmeticType()) {
7129 UsualArithmeticConversions(LHS, RHS);
7130 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007131 return QualType();
7132 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007133 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007134 LHS = UsualUnaryConversions(LHS.take());
7135 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007136 return QualType();
7137
Richard Trieuf1775fb2011-09-06 21:43:51 +00007138 RHS = UsualUnaryConversions(RHS.take());
7139 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007140 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007141 }
7142
Richard Trieuf1775fb2011-09-06 21:43:51 +00007143 LHSType = LHS.get()->getType();
7144 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007145
Douglas Gregor447b69e2008-11-19 03:25:36 +00007146 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007147 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007148
Richard Trieuccd891a2011-09-09 01:45:06 +00007149 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007150 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007151 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007152 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007153 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007154 if (LHSType->hasFloatingRepresentation())
7155 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007156
Richard Trieuf1775fb2011-09-06 21:43:51 +00007157 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007158 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007159 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007160
Richard Trieuf1775fb2011-09-06 21:43:51 +00007161 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007162 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007163 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007164 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007165
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007166 // All of the following pointer-related warnings are GCC extensions, except
7167 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007168 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007169 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007170 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007171 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007172 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007173
David Blaikie4e4d0842012-03-11 07:00:24 +00007174 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007175 if (LCanPointeeTy == RCanPointeeTy)
7176 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007177 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007178 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7179 // Valid unless comparison between non-null pointer and function pointer
7180 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007181 // In a SFINAE context, we treat this as a hard error to maintain
7182 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007183 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7184 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007185 diagnoseFunctionPointerToVoidComparison(
David Blaikie0adb1752013-02-21 06:05:05 +00007186 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007187
7188 if (isSFINAEContext())
7189 return QualType();
7190
Richard Trieuf1775fb2011-09-06 21:43:51 +00007191 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007192 return ResultTy;
7193 }
7194 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007195
Richard Trieuf1775fb2011-09-06 21:43:51 +00007196 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007197 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007198 else
7199 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007200 }
Eli Friedman3075e762009-08-23 00:27:47 +00007201 // C99 6.5.9p2 and C99 6.5.8p2
7202 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7203 RCanPointeeTy.getUnqualifiedType())) {
7204 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007205 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007206 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007207 << LHSType << RHSType << LHS.get()->getSourceRange()
7208 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007209 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007210 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007211 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7212 // Valid unless comparison between non-null pointer and function pointer
7213 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007214 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007215 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007216 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007217 } else {
7218 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007219 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007220 }
John McCall34d6f932011-03-11 04:25:25 +00007221 if (LCanPointeeTy != RCanPointeeTy) {
7222 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007223 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007224 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007225 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007226 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007227 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007228 }
Mike Stump1eb44332009-09-09 15:08:12 +00007229
David Blaikie4e4d0842012-03-11 07:00:24 +00007230 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007231 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007232 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007233 return ResultTy;
7234
Mike Stump1eb44332009-09-09 15:08:12 +00007235 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007236 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007237 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007238 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007239 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007240 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7241 RHS = ImpCastExprToType(RHS.take(), LHSType,
7242 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007243 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007244 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007245 return ResultTy;
7246 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007247 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007248 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007249 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007250 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7251 LHS = ImpCastExprToType(LHS.take(), RHSType,
7252 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007253 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007254 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007255 return ResultTy;
7256 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007257
7258 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007259 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007260 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7261 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007262 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007263 else
7264 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007265 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007266
7267 // Handle scoped enumeration types specifically, since they don't promote
7268 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007269 if (LHS.get()->getType()->isEnumeralType() &&
7270 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7271 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007272 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007273 }
Mike Stump1eb44332009-09-09 15:08:12 +00007274
Steve Naroff1c7d0672008-09-04 15:10:53 +00007275 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007276 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007277 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007278 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7279 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007280
Steve Naroff1c7d0672008-09-04 15:10:53 +00007281 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007282 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007283 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007284 << LHSType << RHSType << LHS.get()->getSourceRange()
7285 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007286 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007287 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007288 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007289 }
John Wiegley429bb272011-04-08 18:41:53 +00007290
Steve Naroff59f53942008-09-28 01:11:11 +00007291 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007292 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007293 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7294 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007295 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007296 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007297 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007298 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007299 ->getPointeeType()->isVoidType())))
7300 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007301 << LHSType << RHSType << LHS.get()->getSourceRange()
7302 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007303 }
John McCall34d6f932011-03-11 04:25:25 +00007304 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007305 LHS = ImpCastExprToType(LHS.take(), RHSType,
7306 RHSType->isPointerType() ? CK_BitCast
7307 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007308 else
John McCall1d9b3b22011-09-09 05:25:32 +00007309 RHS = ImpCastExprToType(RHS.take(), LHSType,
7310 LHSType->isPointerType() ? CK_BitCast
7311 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007312 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007313 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007314
Richard Trieuf1775fb2011-09-06 21:43:51 +00007315 if (LHSType->isObjCObjectPointerType() ||
7316 RHSType->isObjCObjectPointerType()) {
7317 const PointerType *LPT = LHSType->getAs<PointerType>();
7318 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007319 if (LPT || RPT) {
7320 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7321 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007322
Steve Naroffa8069f12008-11-17 19:49:16 +00007323 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007324 !Context.typesAreCompatible(LHSType, RHSType)) {
7325 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007326 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007327 }
John McCall34d6f932011-03-11 04:25:25 +00007328 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007329 LHS = ImpCastExprToType(LHS.take(), RHSType,
7330 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007331 else
John McCall1d9b3b22011-09-09 05:25:32 +00007332 RHS = ImpCastExprToType(RHS.take(), LHSType,
7333 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007334 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007335 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007336 if (LHSType->isObjCObjectPointerType() &&
7337 RHSType->isObjCObjectPointerType()) {
7338 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7339 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007340 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007341 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007342 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007343
John McCall34d6f932011-03-11 04:25:25 +00007344 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007345 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007346 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007347 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007348 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007349 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007350 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007351 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7352 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007353 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007354 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007355 if (LangOpts.DebuggerSupport) {
7356 // Under a debugger, allow the comparison of pointers to integers,
7357 // since users tend to want to compare addresses.
7358 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007359 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007360 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007361 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007362 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007363 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007364 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007365 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7366 isError = true;
7367 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007368 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007369
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007370 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007371 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007372 << LHSType << RHSType << LHS.get()->getSourceRange()
7373 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007374 if (isError)
7375 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007376 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007377
Richard Trieuf1775fb2011-09-06 21:43:51 +00007378 if (LHSType->isIntegerType())
7379 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007380 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007381 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007382 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007383 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007384 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007385 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007386
Steve Naroff39218df2008-09-04 16:56:14 +00007387 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007388 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007389 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7390 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007391 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007392 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007393 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007394 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7395 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007396 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007397 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007398
Richard Trieuf1775fb2011-09-06 21:43:51 +00007399 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007400}
7401
Tanya Lattner4f692c22012-01-16 21:02:28 +00007402
7403// Return a signed type that is of identical size and number of elements.
7404// For floating point vectors, return an integer type of identical size
7405// and number of elements.
7406QualType Sema::GetSignedVectorType(QualType V) {
7407 const VectorType *VTy = V->getAs<VectorType>();
7408 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7409 if (TypeSize == Context.getTypeSize(Context.CharTy))
7410 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7411 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7412 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7413 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7414 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7415 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7416 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7417 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7418 "Unhandled vector element size in vector compare");
7419 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7420}
7421
Nate Begemanbe2341d2008-07-14 18:02:46 +00007422/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007423/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007424/// like a scalar comparison, a vector comparison produces a vector of integer
7425/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007426QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007427 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007428 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007429 // Check to make sure we're operating on vectors of the same type and width,
7430 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007431 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007432 if (vType.isNull())
7433 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007434
Richard Trieu9f60dee2011-09-07 01:19:57 +00007435 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007436
Anton Yartsev7870b132011-03-27 15:36:07 +00007437 // If AltiVec, the comparison results in a numeric type, i.e.
7438 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007439 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007440 return Context.getLogicalOperationType();
7441
Nate Begemanbe2341d2008-07-14 18:02:46 +00007442 // For non-floating point types, check for self-comparisons of the form
7443 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7444 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007445 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007446 if (DeclRefExpr* DRL
7447 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7448 if (DeclRefExpr* DRR
7449 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007450 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007451 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007452 PDiag(diag::warn_comparison_always)
7453 << 0 // self-
7454 << 2 // "a constant"
7455 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007456 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007457
Nate Begemanbe2341d2008-07-14 18:02:46 +00007458 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007459 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007460 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007461 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007462 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007463
7464 // Return a signed type for the vector.
7465 return GetSignedVectorType(LHSType);
7466}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007467
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007468QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7469 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007470 // Ensure that either both operands are of the same vector type, or
7471 // one operand is of a vector type and the other is of its element type.
7472 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
Joey Gouly52e933b2013-02-21 11:49:56 +00007473 if (vType.isNull())
7474 return InvalidOperands(Loc, LHS, RHS);
7475 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7476 vType->hasFloatingRepresentation())
Tanya Lattner4f692c22012-01-16 21:02:28 +00007477 return InvalidOperands(Loc, LHS, RHS);
7478
7479 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007480}
7481
Reid Spencer5f016e22007-07-11 17:01:13 +00007482inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007483 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007484 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7485
Richard Trieu9f60dee2011-09-07 01:19:57 +00007486 if (LHS.get()->getType()->isVectorType() ||
7487 RHS.get()->getType()->isVectorType()) {
7488 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7489 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007490 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007491
Richard Trieu9f60dee2011-09-07 01:19:57 +00007492 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007493 }
Steve Naroff90045e82007-07-13 23:32:42 +00007494
Richard Trieu9f60dee2011-09-07 01:19:57 +00007495 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7496 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007497 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007498 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007499 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007500 LHS = LHSResult.take();
7501 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007502
Eli Friedman860a3192012-06-16 02:19:17 +00007503 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007504 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007505 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007506}
7507
7508inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007509 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007510
Tanya Lattner4f692c22012-01-16 21:02:28 +00007511 // Check vector operands differently.
7512 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7513 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7514
Chris Lattner90a8f272010-07-13 19:41:32 +00007515 // Diagnose cases where the user write a logical and/or but probably meant a
7516 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7517 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007518 if (LHS.get()->getType()->isIntegerType() &&
7519 !LHS.get()->getType()->isBooleanType() &&
7520 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007521 // Don't warn in macros or template instantiations.
7522 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007523 // If the RHS can be constant folded, and if it constant folds to something
7524 // that isn't 0 or 1 (which indicate a potential logical operation that
7525 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007526 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007527 llvm::APSInt Result;
7528 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007529 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007530 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007531 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007532 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007533 << (Opc == BO_LAnd ? "&&" : "||");
7534 // Suggest replacing the logical operator with the bitwise version
7535 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7536 << (Opc == BO_LAnd ? "&" : "|")
7537 << FixItHint::CreateReplacement(SourceRange(
7538 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007539 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007540 Opc == BO_LAnd ? "&" : "|");
7541 if (Opc == BO_LAnd)
7542 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7543 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7544 << FixItHint::CreateRemoval(
7545 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007546 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007547 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007548 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007549 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007550 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007551 }
Joey Gouly52e933b2013-02-21 11:49:56 +00007552
David Blaikie4e4d0842012-03-11 07:00:24 +00007553 if (!Context.getLangOpts().CPlusPlus) {
Joey Gouly52e933b2013-02-21 11:49:56 +00007554 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
7555 // not operate on the built-in scalar and vector float types.
7556 if (Context.getLangOpts().OpenCL &&
7557 Context.getLangOpts().OpenCLVersion < 120) {
7558 if (LHS.get()->getType()->isFloatingType() ||
7559 RHS.get()->getType()->isFloatingType())
7560 return InvalidOperands(Loc, LHS, RHS);
7561 }
7562
Richard Trieu9f60dee2011-09-07 01:19:57 +00007563 LHS = UsualUnaryConversions(LHS.take());
7564 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007565 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007566
Richard Trieu9f60dee2011-09-07 01:19:57 +00007567 RHS = UsualUnaryConversions(RHS.take());
7568 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007569 return QualType();
7570
Richard Trieu9f60dee2011-09-07 01:19:57 +00007571 if (!LHS.get()->getType()->isScalarType() ||
7572 !RHS.get()->getType()->isScalarType())
7573 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007574
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007575 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007576 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007577
John McCall75f7c0f2010-06-04 00:29:51 +00007578 // The following is safe because we only use this method for
7579 // non-overloadable operands.
7580
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007581 // C++ [expr.log.and]p1
7582 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007583 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007584 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7585 if (LHSRes.isInvalid())
7586 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007587 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007588
Richard Trieu9f60dee2011-09-07 01:19:57 +00007589 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7590 if (RHSRes.isInvalid())
7591 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007592 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007593
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007594 // C++ [expr.log.and]p2
7595 // C++ [expr.log.or]p2
7596 // The result is a bool.
7597 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007598}
7599
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007600/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7601/// is a read-only property; return true if so. A readonly property expression
7602/// depends on various declarations and thus must be treated specially.
7603///
Mike Stump1eb44332009-09-09 15:08:12 +00007604static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007605 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7606 if (!PropExpr) return false;
7607 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007608
John McCall3c3b7f92011-10-25 17:37:35 +00007609 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7610 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007611 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007612 PropExpr->getBase()->getType();
7613
John McCall3c3b7f92011-10-25 17:37:35 +00007614 if (const ObjCObjectPointerType *OPT =
7615 BaseType->getAsObjCInterfacePointerType())
7616 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7617 if (S.isPropertyReadonly(PDecl, IFace))
7618 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007619 return false;
7620}
7621
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007622static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007623 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7624 if (!ME) return false;
7625 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7626 ObjCMessageExpr *Base =
7627 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7628 if (!Base) return false;
7629 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007630}
7631
John McCall78dae242012-03-13 00:37:01 +00007632/// Is the given expression (which must be 'const') a reference to a
7633/// variable which was originally non-const, but which has become
7634/// 'const' due to being captured within a block?
7635enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7636static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7637 assert(E->isLValue() && E->getType().isConstQualified());
7638 E = E->IgnoreParens();
7639
7640 // Must be a reference to a declaration from an enclosing scope.
7641 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7642 if (!DRE) return NCCK_None;
7643 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7644
7645 // The declaration must be a variable which is not declared 'const'.
7646 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7647 if (!var) return NCCK_None;
7648 if (var->getType().isConstQualified()) return NCCK_None;
7649 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7650
7651 // Decide whether the first capture was for a block or a lambda.
7652 DeclContext *DC = S.CurContext;
7653 while (DC->getParent() != var->getDeclContext())
7654 DC = DC->getParent();
7655 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7656}
7657
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007658/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7659/// emit an error and return true. If so, return false.
7660static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007661 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007662 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007663 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007664 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007665 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7666 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007667 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7668 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007669 if (IsLV == Expr::MLV_Valid)
7670 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007671
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007672 unsigned Diag = 0;
7673 bool NeedType = false;
7674 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007675 case Expr::MLV_ConstQualified:
7676 Diag = diag::err_typecheck_assign_const;
7677
John McCall78dae242012-03-13 00:37:01 +00007678 // Use a specialized diagnostic when we're assigning to an object
7679 // from an enclosing function or block.
7680 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7681 if (NCCK == NCCK_Block)
7682 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7683 else
7684 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7685 break;
7686 }
7687
John McCall7acddac2011-06-17 06:42:21 +00007688 // In ARC, use some specialized diagnostics for occasions where we
7689 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007690 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007691 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7692 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7693 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7694
John McCall7acddac2011-06-17 06:42:21 +00007695 // Use the normal diagnostic if it's pseudo-__strong but the
7696 // user actually wrote 'const'.
7697 if (var->isARCPseudoStrong() &&
7698 (!var->getTypeSourceInfo() ||
7699 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7700 // There are two pseudo-strong cases:
7701 // - self
John McCallf85e1932011-06-15 23:02:42 +00007702 ObjCMethodDecl *method = S.getCurMethodDecl();
7703 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007704 Diag = method->isClassMethod()
7705 ? diag::err_typecheck_arc_assign_self_class_method
7706 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007707
7708 // - fast enumeration variables
7709 else
John McCallf85e1932011-06-15 23:02:42 +00007710 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007711
John McCallf85e1932011-06-15 23:02:42 +00007712 SourceRange Assign;
7713 if (Loc != OrigLoc)
7714 Assign = SourceRange(OrigLoc, OrigLoc);
7715 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7716 // We need to preserve the AST regardless, so migration tool
7717 // can do its job.
7718 return false;
7719 }
7720 }
7721 }
7722
7723 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007724 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007725 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007726 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7727 NeedType = true;
7728 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007729 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007730 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7731 NeedType = true;
7732 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007733 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007734 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7735 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007736 case Expr::MLV_Valid:
7737 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007738 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007739 case Expr::MLV_MemberFunction:
7740 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007741 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7742 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007743 case Expr::MLV_IncompleteType:
7744 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007745 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007746 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007747 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007748 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7749 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007750 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007751 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007752 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007753 case Expr::MLV_InvalidMessageExpression:
7754 Diag = diag::error_readonly_message_assignment;
7755 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007756 case Expr::MLV_SubObjCPropertySetting:
7757 Diag = diag::error_no_subobject_property_setting;
7758 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007759 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007760
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007761 SourceRange Assign;
7762 if (Loc != OrigLoc)
7763 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007764 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007765 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007766 else
Mike Stump1eb44332009-09-09 15:08:12 +00007767 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007768 return true;
7769}
7770
Nico Weber7c81b432012-07-03 02:03:06 +00007771static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7772 SourceLocation Loc,
7773 Sema &Sema) {
7774 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007775 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7776 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7777 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7778 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007779 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007780 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007781
Nico Weber7c81b432012-07-03 02:03:06 +00007782 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007783 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7784 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7785 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7786 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7787 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7788 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007789 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007790 }
7791}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007792
7793// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007794QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007795 SourceLocation Loc,
7796 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007797 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7798
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007799 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007800 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007801 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007802
Richard Trieu268942b2011-09-07 01:33:52 +00007803 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007804 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7805 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007806 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007807 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007808 Expr *RHSCheck = RHS.get();
7809
Nico Weber7c81b432012-07-03 02:03:06 +00007810 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007811
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007812 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007813 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007814 if (RHS.isInvalid())
7815 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007816 // Special case of NSObject attributes on c-style pointer types.
7817 if (ConvTy == IncompatiblePointer &&
7818 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007819 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007820 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007821 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007822 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007823
John McCallf89e55a2010-11-18 06:31:45 +00007824 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007825 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007826 Diag(Loc, diag::err_objc_object_assignment)
7827 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007828
Chris Lattner2c156472008-08-21 18:04:13 +00007829 // If the RHS is a unary plus or minus, check to see if they = and + are
7830 // right next to each other. If so, the user may have typo'd "x =+ 4"
7831 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007832 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7833 RHSCheck = ICE->getSubExpr();
7834 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007835 if ((UO->getOpcode() == UO_Plus ||
7836 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007837 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007838 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007839 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007840 // And there is a space or other character before the subexpr of the
7841 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007842 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007843 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007844 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007845 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007846 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007847 }
Chris Lattner2c156472008-08-21 18:04:13 +00007848 }
John McCallf85e1932011-06-15 23:02:42 +00007849
7850 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00007851 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7852 // Warn about retain cycles where a block captures the LHS, but
7853 // not if the LHS is a simple variable into which the block is
7854 // being stored...unless that variable can be captured by reference!
7855 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7856 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7857 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7858 checkRetainCycles(LHSExpr, RHS.get());
7859
Jordan Rose58b6bdc2012-09-28 22:21:30 +00007860 // It is safe to assign a weak reference into a strong variable.
7861 // Although this code can still have problems:
7862 // id x = self.weakProp;
7863 // id y = self.weakProp;
7864 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7865 // paths through the function. This should be revisited if
7866 // -Wrepeated-use-of-weak is made flow-sensitive.
7867 DiagnosticsEngine::Level Level =
7868 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7869 RHS.get()->getLocStart());
7870 if (Level != DiagnosticsEngine::Ignored)
7871 getCurFunction()->markSafeWeakUse(RHS.get());
7872
Jordan Rosee10f4d32012-09-15 02:48:31 +00007873 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00007874 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00007875 }
John McCallf85e1932011-06-15 23:02:42 +00007876 }
Chris Lattner2c156472008-08-21 18:04:13 +00007877 } else {
7878 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007879 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007880 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007881
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007882 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007883 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007884 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007885
Richard Trieu268942b2011-09-07 01:33:52 +00007886 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007887
Reid Spencer5f016e22007-07-11 17:01:13 +00007888 // C99 6.5.16p3: The type of an assignment expression is the type of the
7889 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007890 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007891 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7892 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007893 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007894 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007895 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007896 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007897}
7898
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007899// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007900static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007901 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007902 LHS = S.CheckPlaceholderExpr(LHS.take());
7903 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007904 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007905 return QualType();
7906
John McCallcf2e5062010-10-12 07:14:40 +00007907 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7908 // operands, but not unary promotions.
7909 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007910
John McCallf6a16482010-12-04 03:47:34 +00007911 // So we treat the LHS as a ignored value, and in C++ we allow the
7912 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007913 LHS = S.IgnoredValueConversions(LHS.take());
7914 if (LHS.isInvalid())
7915 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007916
Eli Friedmana6115062012-05-24 00:47:05 +00007917 S.DiagnoseUnusedExprResult(LHS.get());
7918
David Blaikie4e4d0842012-03-11 07:00:24 +00007919 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007920 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7921 if (RHS.isInvalid())
7922 return QualType();
7923 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007924 S.RequireCompleteType(Loc, RHS.get()->getType(),
7925 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007926 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007927
John Wiegley429bb272011-04-08 18:41:53 +00007928 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007929}
7930
Steve Naroff49b45262007-07-13 16:58:59 +00007931/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7932/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007933static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7934 ExprValueKind &VK,
7935 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007936 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007937 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007938 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007939
Chris Lattner3528d352008-11-21 07:05:48 +00007940 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007941 // Atomic types can be used for increment / decrement where the non-atomic
7942 // versions can, so ignore the _Atomic() specifier for the purpose of
7943 // checking.
7944 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7945 ResType = ResAtomicType->getValueType();
7946
Chris Lattner3528d352008-11-21 07:05:48 +00007947 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007948
David Blaikie4e4d0842012-03-11 07:00:24 +00007949 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007950 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007951 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007952 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007953 return QualType();
7954 }
7955 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007956 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007957 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007958 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007959 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007960 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007961 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007962 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007963 } else if (ResType->isObjCObjectPointerType()) {
7964 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7965 // Otherwise, we just need a complete type.
7966 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7967 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7968 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007969 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007970 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007971 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007972 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007973 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007974 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007975 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007976 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007977 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007978 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007979 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007980 } else {
John McCall09431682010-11-18 19:01:18 +00007981 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007982 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007983 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007984 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007985 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007986 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007987 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007988 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007989 // In C++, a prefix increment is the same type as the operand. Otherwise
7990 // (in C or with postfix), the increment is the unqualified type of the
7991 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007992 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007993 VK = VK_LValue;
7994 return ResType;
7995 } else {
7996 VK = VK_RValue;
7997 return ResType.getUnqualifiedType();
7998 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007999}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008000
8001
Anders Carlsson369dee42008-02-01 07:15:58 +00008002/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008003/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008004/// where the declaration is needed for type checking. We only need to
8005/// handle cases when the expression references a function designator
8006/// or is an lvalue. Here are some examples:
8007/// - &(x) => x
8008/// - &*****f => f for f a function designator.
8009/// - &s.xx => s
8010/// - &s.zz[1].yy -> s, if zz is an array
8011/// - *(x + 1) -> x, if x is an array
8012/// - &"123"[2] -> 0
8013/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008014static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008015 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008016 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008017 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008018 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008019 // If this is an arrow operator, the address is an offset from
8020 // the base's value, so the object the base refers to is
8021 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008022 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008023 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008024 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008025 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008026 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008027 // FIXME: This code shouldn't be necessary! We should catch the implicit
8028 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008029 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8030 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8031 if (ICE->getSubExpr()->getType()->isArrayType())
8032 return getPrimaryDecl(ICE->getSubExpr());
8033 }
8034 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008035 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008036 case Stmt::UnaryOperatorClass: {
8037 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008038
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008039 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008040 case UO_Real:
8041 case UO_Imag:
8042 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008043 return getPrimaryDecl(UO->getSubExpr());
8044 default:
8045 return 0;
8046 }
8047 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008048 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008049 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008050 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008051 // If the result of an implicit cast is an l-value, we care about
8052 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008053 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008054 default:
8055 return 0;
8056 }
8057}
8058
Richard Trieu5520f232011-09-07 21:46:33 +00008059namespace {
8060 enum {
8061 AO_Bit_Field = 0,
8062 AO_Vector_Element = 1,
8063 AO_Property_Expansion = 2,
8064 AO_Register_Variable = 3,
8065 AO_No_Error = 4
8066 };
8067}
Richard Trieu09a26ad2011-09-02 00:47:55 +00008068/// \brief Diagnose invalid operand for address of operations.
8069///
8070/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00008071static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8072 Expr *E, unsigned Type) {
8073 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8074}
8075
Reid Spencer5f016e22007-07-11 17:01:13 +00008076/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008077/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008078/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008079/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008080/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008081/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008082/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00008083static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00008084 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00008085 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8086 if (PTy->getKind() == BuiltinType::Overload) {
8087 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
Richard Smith3fa3fea2013-02-02 02:14:45 +00008088 assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode()
8089 == UO_AddrOf);
8090 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008091 << OrigOp.get()->getSourceRange();
8092 return QualType();
8093 }
8094
8095 return S.Context.OverloadTy;
8096 }
8097
8098 if (PTy->getKind() == BuiltinType::UnknownAny)
8099 return S.Context.UnknownAnyTy;
8100
8101 if (PTy->getKind() == BuiltinType::BoundMember) {
8102 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8103 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00008104 return QualType();
8105 }
John McCall3c3b7f92011-10-25 17:37:35 +00008106
8107 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8108 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00008109 }
John McCall9c72c602010-08-27 09:08:28 +00008110
John McCall3c3b7f92011-10-25 17:37:35 +00008111 if (OrigOp.get()->isTypeDependent())
8112 return S.Context.DependentTy;
8113
8114 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008115
John McCall9c72c602010-08-27 09:08:28 +00008116 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00008117 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008118
David Blaikie4e4d0842012-03-11 07:00:24 +00008119 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008120 // Implement C99-only parts of addressof rules.
8121 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008122 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008123 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8124 // (assuming the deref expression is valid).
8125 return uOp->getSubExpr()->getType();
8126 }
8127 // Technically, there should be a check for array subscript
8128 // expressions here, but the result of one is always an lvalue anyway.
8129 }
John McCall5808ce42011-02-03 08:15:49 +00008130 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008131 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00008132 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008133
Richard Smith3fa3fea2013-02-02 02:14:45 +00008134 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
David Blaikie0adb1752013-02-21 06:05:05 +00008135 bool sfinae = (bool)S.isSFINAEContext();
8136 S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary
Richard Smith3fa3fea2013-02-02 02:14:45 +00008137 : diag::ext_typecheck_addrof_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008138 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008139 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008140 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008141 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008142 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008143 } else if (lval == Expr::LV_MemberFunction) {
8144 // If it's an instance method, make a member pointer.
8145 // The expression must have exactly the form &A::foo.
8146
8147 // If the underlying expression isn't a decl ref, give up.
8148 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008149 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008150 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008151 return QualType();
8152 }
8153 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8154 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8155
8156 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00008157 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00008158 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008159 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008160
8161 // The method was named without a qualifier.
8162 } else if (!DRE->getQualifier()) {
David Blaikieabeadfb2012-10-11 22:55:07 +00008163 if (MD->getParent()->getName().empty())
8164 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8165 << op->getSourceRange();
8166 else {
8167 SmallString<32> Str;
8168 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8169 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8170 << op->getSourceRange()
8171 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8172 }
John McCall9c72c602010-08-27 09:08:28 +00008173 }
8174
John McCall09431682010-11-18 19:01:18 +00008175 return S.Context.getMemberPointerType(op->getType(),
8176 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008177 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008178 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008179 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008180 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008181 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008182 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008183 AddressOfError = AO_Property_Expansion;
8184 } else {
John McCall3c3b7f92011-10-25 17:37:35 +00008185 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Richard Smith3fa3fea2013-02-02 02:14:45 +00008186 << op->getType() << op->getSourceRange();
John McCall3c3b7f92011-10-25 17:37:35 +00008187 return QualType();
8188 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008189 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008190 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008191 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008192 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008193 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008194 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008195 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008196 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008197 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008198 // with the register storage-class specifier.
8199 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008200 // in C++ it is not error to take address of a register
8201 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008202 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008203 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008204 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008205 }
John McCallba135432009-11-21 08:51:07 +00008206 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008207 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008208 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008209 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008210 // Could be a pointer to member, though, if there is an explicit
8211 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008212 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008213 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008214 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008215 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008216 S.Diag(OpLoc,
8217 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008218 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008219 return QualType();
8220 }
Mike Stump1eb44332009-09-09 15:08:12 +00008221
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008222 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8223 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008224 return S.Context.getMemberPointerType(op->getType(),
8225 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008226 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008227 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008228 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008229 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008230 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008231
Richard Trieu5520f232011-09-07 21:46:33 +00008232 if (AddressOfError != AO_No_Error) {
8233 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8234 return QualType();
8235 }
8236
Eli Friedman441cf102009-05-16 23:27:50 +00008237 if (lval == Expr::LV_IncompleteVoidType) {
8238 // Taking the address of a void variable is technically illegal, but we
8239 // allow it in cases which are otherwise valid.
8240 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008241 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008242 }
8243
Reid Spencer5f016e22007-07-11 17:01:13 +00008244 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008245 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008246 return S.Context.getObjCObjectPointerType(op->getType());
8247 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008248}
8249
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008250/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008251static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8252 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008253 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008254 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008255
John Wiegley429bb272011-04-08 18:41:53 +00008256 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8257 if (ConvResult.isInvalid())
8258 return QualType();
8259 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008260 QualType OpTy = Op->getType();
8261 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008262
8263 if (isa<CXXReinterpretCastExpr>(Op)) {
8264 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8265 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8266 Op->getSourceRange());
8267 }
8268
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008269 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8270 // is an incomplete type or void. It would be possible to warn about
8271 // dereferencing a void pointer, but it's completely well-defined, and such a
8272 // warning is unlikely to catch any mistakes.
8273 if (const PointerType *PT = OpTy->getAs<PointerType>())
8274 Result = PT->getPointeeType();
8275 else if (const ObjCObjectPointerType *OPT =
8276 OpTy->getAs<ObjCObjectPointerType>())
8277 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008278 else {
John McCallfb8721c2011-04-10 19:13:55 +00008279 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008280 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008281 if (PR.take() != Op)
8282 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008283 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008284
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008285 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008286 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008287 << OpTy << Op->getSourceRange();
8288 return QualType();
8289 }
John McCall09431682010-11-18 19:01:18 +00008290
8291 // Dereferences are usually l-values...
8292 VK = VK_LValue;
8293
8294 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008295 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008296 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008297
8298 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008299}
8300
John McCall2de56d12010-08-25 11:45:40 +00008301static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008302 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008303 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008304 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008305 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008306 case tok::periodstar: Opc = BO_PtrMemD; break;
8307 case tok::arrowstar: Opc = BO_PtrMemI; break;
8308 case tok::star: Opc = BO_Mul; break;
8309 case tok::slash: Opc = BO_Div; break;
8310 case tok::percent: Opc = BO_Rem; break;
8311 case tok::plus: Opc = BO_Add; break;
8312 case tok::minus: Opc = BO_Sub; break;
8313 case tok::lessless: Opc = BO_Shl; break;
8314 case tok::greatergreater: Opc = BO_Shr; break;
8315 case tok::lessequal: Opc = BO_LE; break;
8316 case tok::less: Opc = BO_LT; break;
8317 case tok::greaterequal: Opc = BO_GE; break;
8318 case tok::greater: Opc = BO_GT; break;
8319 case tok::exclaimequal: Opc = BO_NE; break;
8320 case tok::equalequal: Opc = BO_EQ; break;
8321 case tok::amp: Opc = BO_And; break;
8322 case tok::caret: Opc = BO_Xor; break;
8323 case tok::pipe: Opc = BO_Or; break;
8324 case tok::ampamp: Opc = BO_LAnd; break;
8325 case tok::pipepipe: Opc = BO_LOr; break;
8326 case tok::equal: Opc = BO_Assign; break;
8327 case tok::starequal: Opc = BO_MulAssign; break;
8328 case tok::slashequal: Opc = BO_DivAssign; break;
8329 case tok::percentequal: Opc = BO_RemAssign; break;
8330 case tok::plusequal: Opc = BO_AddAssign; break;
8331 case tok::minusequal: Opc = BO_SubAssign; break;
8332 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8333 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8334 case tok::ampequal: Opc = BO_AndAssign; break;
8335 case tok::caretequal: Opc = BO_XorAssign; break;
8336 case tok::pipeequal: Opc = BO_OrAssign; break;
8337 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008338 }
8339 return Opc;
8340}
8341
John McCall2de56d12010-08-25 11:45:40 +00008342static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008343 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008344 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008345 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008346 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008347 case tok::plusplus: Opc = UO_PreInc; break;
8348 case tok::minusminus: Opc = UO_PreDec; break;
8349 case tok::amp: Opc = UO_AddrOf; break;
8350 case tok::star: Opc = UO_Deref; break;
8351 case tok::plus: Opc = UO_Plus; break;
8352 case tok::minus: Opc = UO_Minus; break;
8353 case tok::tilde: Opc = UO_Not; break;
8354 case tok::exclaim: Opc = UO_LNot; break;
8355 case tok::kw___real: Opc = UO_Real; break;
8356 case tok::kw___imag: Opc = UO_Imag; break;
8357 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008358 }
8359 return Opc;
8360}
8361
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008362/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8363/// This warning is only emitted for builtin assignment operations. It is also
8364/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008365static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008366 SourceLocation OpLoc) {
8367 if (!S.ActiveTemplateInstantiations.empty())
8368 return;
8369 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8370 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008371 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8372 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8373 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8374 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8375 if (!LHSDeclRef || !RHSDeclRef ||
8376 LHSDeclRef->getLocation().isMacroID() ||
8377 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008378 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008379 const ValueDecl *LHSDecl =
8380 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8381 const ValueDecl *RHSDecl =
8382 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8383 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008384 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008385 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008386 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008387 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008388 if (RefTy->getPointeeType().isVolatileQualified())
8389 return;
8390
8391 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008392 << LHSDeclRef->getType()
8393 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008394}
8395
Douglas Gregoreaebc752008-11-06 23:29:22 +00008396/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8397/// operator @p Opc at location @c TokLoc. This routine only supports
8398/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008399ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008400 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008401 Expr *LHSExpr, Expr *RHSExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008402 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008403 // The syntax only allows initializer lists on the RHS of assignment,
8404 // so we don't need to worry about accepting invalid code for
8405 // non-assignment operators.
8406 // C++11 5.17p9:
8407 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8408 // of x = {} is x = T().
8409 InitializationKind Kind =
8410 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8411 InitializedEntity Entity =
8412 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8413 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008414 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008415 if (Init.isInvalid())
8416 return Init;
8417 RHSExpr = Init.take();
8418 }
8419
Richard Trieu78ea78b2011-09-07 01:49:20 +00008420 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008421 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008422 // The following two variables are used for compound assignment operators
8423 QualType CompLHSTy; // Type of LHS after promotions for computation
8424 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008425 ExprValueKind VK = VK_RValue;
8426 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008427
8428 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008429 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008430 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008431 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008432 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8433 VK = LHS.get()->getValueKind();
8434 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008435 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008436 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008437 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008438 break;
John McCall2de56d12010-08-25 11:45:40 +00008439 case BO_PtrMemD:
8440 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008441 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008442 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008443 break;
John McCall2de56d12010-08-25 11:45:40 +00008444 case BO_Mul:
8445 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008446 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008447 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008448 break;
John McCall2de56d12010-08-25 11:45:40 +00008449 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008450 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008451 break;
John McCall2de56d12010-08-25 11:45:40 +00008452 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008453 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008454 break;
John McCall2de56d12010-08-25 11:45:40 +00008455 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008456 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008457 break;
John McCall2de56d12010-08-25 11:45:40 +00008458 case BO_Shl:
8459 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008460 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008461 break;
John McCall2de56d12010-08-25 11:45:40 +00008462 case BO_LE:
8463 case BO_LT:
8464 case BO_GE:
8465 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008466 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008467 break;
John McCall2de56d12010-08-25 11:45:40 +00008468 case BO_EQ:
8469 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008470 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008471 break;
John McCall2de56d12010-08-25 11:45:40 +00008472 case BO_And:
8473 case BO_Xor:
8474 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008475 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008476 break;
John McCall2de56d12010-08-25 11:45:40 +00008477 case BO_LAnd:
8478 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008479 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008480 break;
John McCall2de56d12010-08-25 11:45:40 +00008481 case BO_MulAssign:
8482 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008483 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008484 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008485 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008486 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8487 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008488 break;
John McCall2de56d12010-08-25 11:45:40 +00008489 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008490 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008491 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008492 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8493 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008494 break;
John McCall2de56d12010-08-25 11:45:40 +00008495 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008496 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008497 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8498 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008499 break;
John McCall2de56d12010-08-25 11:45:40 +00008500 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008501 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8502 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8503 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008504 break;
John McCall2de56d12010-08-25 11:45:40 +00008505 case BO_ShlAssign:
8506 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008507 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008508 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008509 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8510 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008511 break;
John McCall2de56d12010-08-25 11:45:40 +00008512 case BO_AndAssign:
8513 case BO_XorAssign:
8514 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008515 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008516 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008517 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8518 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008519 break;
John McCall2de56d12010-08-25 11:45:40 +00008520 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008521 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008522 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008523 VK = RHS.get()->getValueKind();
8524 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008525 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008526 break;
8527 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008528 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008529 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008530
8531 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008532 CheckArrayAccess(LHS.get());
8533 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008534
Eli Friedmanab3a8522009-03-28 01:22:36 +00008535 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008536 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hamesbe9af122012-10-02 04:45:10 +00008537 ResultTy, VK, OK, OpLoc,
8538 FPFeatures.fp_contract));
David Blaikie4e4d0842012-03-11 07:00:24 +00008539 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008540 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008541 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008542 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008543 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008544 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008545 ResultTy, VK, OK, CompLHSTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00008546 CompResultTy, OpLoc,
8547 FPFeatures.fp_contract));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008548}
8549
Sebastian Redlaee3c932009-10-27 12:10:02 +00008550/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8551/// operators are mixed in a way that suggests that the programmer forgot that
8552/// comparison operators have higher precedence. The most typical example of
8553/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008554static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008555 SourceLocation OpLoc, Expr *LHSExpr,
8556 Expr *RHSExpr) {
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008557 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8558 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008559
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008560 // Check that one of the sides is a comparison operator.
8561 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8562 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8563 if (!isLeftComp && !isRightComp)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008564 return;
8565
8566 // Bitwise operations are sometimes used as eager logical ops.
8567 // Don't diagnose this.
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008568 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8569 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8570 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008571 return;
8572
Richard Trieu78ea78b2011-09-07 01:49:20 +00008573 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8574 OpLoc)
8575 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008576 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu70979d42011-08-10 22:41:34 +00008577 SourceRange ParensRange = isLeftComp ?
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008578 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8579 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008580
8581 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008582 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu70979d42011-08-10 22:41:34 +00008583 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00008584 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008585 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008586 SuggestParentheses(Self, OpLoc,
Eli Friedmanebbcd1d2012-11-15 00:29:07 +00008587 Self.PDiag(diag::note_precedence_bitwise_first)
8588 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu70979d42011-08-10 22:41:34 +00008589 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008590}
8591
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008592/// \brief It accepts a '&' expr that is inside a '|' one.
8593/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8594/// in parentheses.
8595static void
8596EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8597 BinaryOperator *Bop) {
8598 assert(Bop->getOpcode() == BO_And);
8599 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8600 << Bop->getSourceRange() << OpLoc;
8601 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008602 Self.PDiag(diag::note_precedence_silence)
8603 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008604 Bop->getSourceRange());
8605}
8606
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008607/// \brief It accepts a '&&' expr that is inside a '||' one.
8608/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8609/// in parentheses.
8610static void
8611EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008612 BinaryOperator *Bop) {
8613 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008614 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8615 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008616 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008617 Self.PDiag(diag::note_precedence_silence)
8618 << Bop->getOpcodeStr(),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008619 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008620}
8621
8622/// \brief Returns true if the given expression can be evaluated as a constant
8623/// 'true'.
8624static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8625 bool Res;
8626 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8627}
8628
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008629/// \brief Returns true if the given expression can be evaluated as a constant
8630/// 'false'.
8631static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8632 bool Res;
8633 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8634}
8635
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008636/// \brief Look for '&&' in the left hand of a '||' expr.
8637static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008638 Expr *LHSExpr, Expr *RHSExpr) {
8639 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008640 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008641 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008642 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008643 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008644 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8645 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8646 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8647 } else if (Bop->getOpcode() == BO_LOr) {
8648 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8649 // If it's "a || b && 1 || c" we didn't warn earlier for
8650 // "a || b && 1", but warn now.
8651 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8652 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8653 }
8654 }
8655 }
8656}
8657
8658/// \brief Look for '&&' in the right hand of a '||' expr.
8659static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008660 Expr *LHSExpr, Expr *RHSExpr) {
8661 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008662 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008663 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008664 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008665 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008666 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8667 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8668 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008669 }
8670 }
8671}
8672
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008673/// \brief Look for '&' in the left or right hand of a '|' expr.
8674static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8675 Expr *OrArg) {
8676 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8677 if (Bop->getOpcode() == BO_And)
8678 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8679 }
8680}
8681
David Blaikieb3f55c52012-10-05 00:41:03 +00008682static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie5f531a42012-10-19 18:26:06 +00008683 Expr *SubExpr, StringRef Shift) {
David Blaikieb3f55c52012-10-05 00:41:03 +00008684 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8685 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikie6b34c172012-10-08 01:19:49 +00008686 StringRef Op = Bop->getOpcodeStr();
David Blaikieb3f55c52012-10-05 00:41:03 +00008687 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie5f531a42012-10-19 18:26:06 +00008688 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikieb3f55c52012-10-05 00:41:03 +00008689 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008690 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikieb3f55c52012-10-05 00:41:03 +00008691 Bop->getSourceRange());
8692 }
8693 }
8694}
8695
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008696/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008697/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008698static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008699 SourceLocation OpLoc, Expr *LHSExpr,
8700 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008701 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008702 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008703 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008704
8705 // Diagnose "arg1 & arg2 | arg3"
8706 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008707 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8708 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008709 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008710
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008711 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8712 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008713 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008714 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8715 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008716 }
David Blaikieb3f55c52012-10-05 00:41:03 +00008717
8718 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8719 || Opc == BO_Shr) {
David Blaikie5f531a42012-10-19 18:26:06 +00008720 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8721 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8722 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikieb3f55c52012-10-05 00:41:03 +00008723 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008724}
8725
Reid Spencer5f016e22007-07-11 17:01:13 +00008726// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008727ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008728 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008729 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008730 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008731 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8732 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008733
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008734 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008735 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008736
Richard Trieubefece12011-09-07 02:02:10 +00008737 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008738}
8739
John McCall3c3b7f92011-10-25 17:37:35 +00008740/// Build an overloaded binary operator expression in the given scope.
8741static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8742 BinaryOperatorKind Opc,
8743 Expr *LHS, Expr *RHS) {
8744 // Find all of the overloaded operators visible from this
8745 // point. We perform both an operator-name lookup from the local
8746 // scope and an argument-dependent lookup based on the types of
8747 // the arguments.
8748 UnresolvedSet<16> Functions;
8749 OverloadedOperatorKind OverOp
8750 = BinaryOperator::getOverloadedOperator(Opc);
8751 if (Sc && OverOp != OO_None)
8752 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8753 RHS->getType(), Functions);
8754
8755 // Build the (potentially-overloaded, potentially-dependent)
8756 // binary operation.
8757 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8758}
8759
John McCall60d7b3a2010-08-24 06:29:42 +00008760ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008761 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008762 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008763 // We want to end up calling one of checkPseudoObjectAssignment
8764 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8765 // both expressions are overloadable or either is type-dependent),
8766 // or CreateBuiltinBinOp (in any other case). We also want to get
8767 // any placeholder types out of the way.
8768
John McCall3c3b7f92011-10-25 17:37:35 +00008769 // Handle pseudo-objects in the LHS.
8770 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8771 // Assignments with a pseudo-object l-value need special analysis.
8772 if (pty->getKind() == BuiltinType::PseudoObject &&
8773 BinaryOperator::isAssignmentOp(Opc))
8774 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8775
8776 // Don't resolve overloads if the other type is overloadable.
8777 if (pty->getKind() == BuiltinType::Overload) {
8778 // We can't actually test that if we still have a placeholder,
8779 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008780 // code below are valid when the LHS is an overload set. Note
8781 // that an overload set can be dependently-typed, but it never
8782 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008783 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8784 if (resolvedRHS.isInvalid()) return ExprError();
8785 RHSExpr = resolvedRHS.take();
8786
John McCallac516502011-10-28 01:04:34 +00008787 if (RHSExpr->isTypeDependent() ||
8788 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008789 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8790 }
8791
8792 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8793 if (LHS.isInvalid()) return ExprError();
8794 LHSExpr = LHS.take();
8795 }
8796
8797 // Handle pseudo-objects in the RHS.
8798 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8799 // An overload in the RHS can potentially be resolved by the type
8800 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008801 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8802 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8803 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8804
Eli Friedman87884912012-01-17 21:27:43 +00008805 if (LHSExpr->getType()->isOverloadableType())
8806 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8807
John McCall3c3b7f92011-10-25 17:37:35 +00008808 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008809 }
John McCall3c3b7f92011-10-25 17:37:35 +00008810
8811 // Don't resolve overloads if the other type is overloadable.
8812 if (pty->getKind() == BuiltinType::Overload &&
8813 LHSExpr->getType()->isOverloadableType())
8814 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8815
8816 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8817 if (!resolvedRHS.isUsable()) return ExprError();
8818 RHSExpr = resolvedRHS.take();
8819 }
8820
David Blaikie4e4d0842012-03-11 07:00:24 +00008821 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008822 // If either expression is type-dependent, always build an
8823 // overloaded op.
8824 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8825 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008826
John McCallac516502011-10-28 01:04:34 +00008827 // Otherwise, build an overloaded op if either expression has an
8828 // overloadable type.
8829 if (LHSExpr->getType()->isOverloadableType() ||
8830 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008831 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008832 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008833
Douglas Gregoreaebc752008-11-06 23:29:22 +00008834 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008835 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008836}
8837
John McCall60d7b3a2010-08-24 06:29:42 +00008838ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008839 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008840 Expr *InputExpr) {
8841 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008842 ExprValueKind VK = VK_RValue;
8843 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008844 QualType resultType;
8845 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008846 case UO_PreInc:
8847 case UO_PreDec:
8848 case UO_PostInc:
8849 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008850 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008851 Opc == UO_PreInc ||
8852 Opc == UO_PostInc,
8853 Opc == UO_PreInc ||
8854 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008855 break;
John McCall2de56d12010-08-25 11:45:40 +00008856 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008857 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008858 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008859 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008860 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008861 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008862 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008863 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008864 }
John McCall2de56d12010-08-25 11:45:40 +00008865 case UO_Plus:
8866 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008867 Input = UsualUnaryConversions(Input.take());
8868 if (Input.isInvalid()) return ExprError();
8869 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008870 if (resultType->isDependentType())
8871 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008872 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8873 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008874 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008875 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008876 resultType->isEnumeralType())
8877 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008878 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008879 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008880 resultType->isPointerType())
8881 break;
8882
Sebastian Redl0eb23302009-01-19 00:08:26 +00008883 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008884 << resultType << Input.get()->getSourceRange());
8885
John McCall2de56d12010-08-25 11:45:40 +00008886 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008887 Input = UsualUnaryConversions(Input.take());
Joey Gouly52e933b2013-02-21 11:49:56 +00008888 if (Input.isInvalid())
8889 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008890 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008891 if (resultType->isDependentType())
8892 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008893 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8894 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8895 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008896 Diag(OpLoc, diag::ext_integer_complement_complex)
Joey Gouly52e933b2013-02-21 11:49:56 +00008897 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008898 else if (resultType->hasIntegerRepresentation())
8899 break;
Joey Gouly52e933b2013-02-21 11:49:56 +00008900 else if (resultType->isExtVectorType()) {
8901 if (Context.getLangOpts().OpenCL) {
8902 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
8903 // on vector float types.
8904 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
8905 if (!T->isIntegerType())
8906 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8907 << resultType << Input.get()->getSourceRange());
8908 }
8909 break;
8910 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008911 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
Joey Gouly52e933b2013-02-21 11:49:56 +00008912 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008913 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008914 break;
John Wiegley429bb272011-04-08 18:41:53 +00008915
John McCall2de56d12010-08-25 11:45:40 +00008916 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008917 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008918 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8919 if (Input.isInvalid()) return ExprError();
8920 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008921
8922 // Though we still have to promote half FP to float...
Joey Gouly19dbb202013-01-23 11:56:20 +00008923 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008924 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8925 resultType = Context.FloatTy;
8926 }
8927
Sebastian Redl28507842009-02-26 14:39:58 +00008928 if (resultType->isDependentType())
8929 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008930 if (resultType->isScalarType()) {
8931 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008932 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008933 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8934 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008935 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8936 ScalarTypeToBooleanCastKind(resultType));
Joey Gouly52e933b2013-02-21 11:49:56 +00008937 } else if (Context.getLangOpts().OpenCL &&
8938 Context.getLangOpts().OpenCLVersion < 120) {
8939 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
8940 // operate on scalar float types.
8941 if (!resultType->isIntegerType())
8942 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8943 << resultType << Input.get()->getSourceRange());
Abramo Bagnara737d5442011-04-07 09:26:19 +00008944 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008945 } else if (resultType->isExtVectorType()) {
Joey Gouly52e933b2013-02-21 11:49:56 +00008946 if (Context.getLangOpts().OpenCL &&
8947 Context.getLangOpts().OpenCLVersion < 120) {
8948 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
8949 // operate on vector float types.
8950 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
8951 if (!T->isIntegerType())
8952 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8953 << resultType << Input.get()->getSourceRange());
8954 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00008955 // Vector logical not returns the signed variant of the operand type.
8956 resultType = GetSignedVectorType(resultType);
8957 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008958 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008959 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008960 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008961 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008962
Reid Spencer5f016e22007-07-11 17:01:13 +00008963 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008964 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008965 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008966 break;
John McCall2de56d12010-08-25 11:45:40 +00008967 case UO_Real:
8968 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008969 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008970 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8971 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008972 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008973 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8974 if (Input.get()->getValueKind() != VK_RValue &&
8975 Input.get()->getObjectKind() == OK_Ordinary)
8976 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008977 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008978 // In C, a volatile scalar is read by __imag. In C++, it is not.
8979 Input = DefaultLvalueConversion(Input.take());
8980 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008981 break;
John McCall2de56d12010-08-25 11:45:40 +00008982 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008983 resultType = Input.get()->getType();
8984 VK = Input.get()->getValueKind();
8985 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008986 break;
8987 }
John Wiegley429bb272011-04-08 18:41:53 +00008988 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008989 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008990
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008991 // Check for array bounds violations in the operand of the UnaryOperator,
8992 // except for the '*' and '&' operators that have to be handled specially
8993 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8994 // that are explicitly defined as valid by the standard).
8995 if (Opc != UO_AddrOf && Opc != UO_Deref)
8996 CheckArrayAccess(Input.get());
8997
John Wiegley429bb272011-04-08 18:41:53 +00008998 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008999 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00009000}
9001
Douglas Gregord3d08532011-12-14 21:23:13 +00009002/// \brief Determine whether the given expression is a qualified member
9003/// access expression, of a form that could be turned into a pointer to member
9004/// with the address-of operator.
9005static bool isQualifiedMemberAccess(Expr *E) {
9006 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9007 if (!DRE->getQualifier())
9008 return false;
9009
9010 ValueDecl *VD = DRE->getDecl();
9011 if (!VD->isCXXClassMember())
9012 return false;
9013
9014 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9015 return true;
9016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9017 return Method->isInstance();
9018
9019 return false;
9020 }
9021
9022 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9023 if (!ULE->getQualifier())
9024 return false;
9025
9026 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9027 DEnd = ULE->decls_end();
9028 D != DEnd; ++D) {
9029 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9030 if (Method->isInstance())
9031 return true;
9032 } else {
9033 // Overload set does not contain methods.
9034 break;
9035 }
9036 }
9037
9038 return false;
9039 }
9040
9041 return false;
9042}
9043
John McCall60d7b3a2010-08-24 06:29:42 +00009044ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009045 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00009046 // First things first: handle placeholders so that the
9047 // overloaded-operator check considers the right type.
9048 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9049 // Increment and decrement of pseudo-object references.
9050 if (pty->getKind() == BuiltinType::PseudoObject &&
9051 UnaryOperator::isIncrementDecrementOp(Opc))
9052 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9053
9054 // extension is always a builtin operator.
9055 if (Opc == UO_Extension)
9056 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9057
9058 // & gets special logic for several kinds of placeholder.
9059 // The builtin code knows what to do.
9060 if (Opc == UO_AddrOf &&
9061 (pty->getKind() == BuiltinType::Overload ||
9062 pty->getKind() == BuiltinType::UnknownAny ||
9063 pty->getKind() == BuiltinType::BoundMember))
9064 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9065
9066 // Anything else needs to be handled now.
9067 ExprResult Result = CheckPlaceholderExpr(Input);
9068 if (Result.isInvalid()) return ExprError();
9069 Input = Result.take();
9070 }
9071
David Blaikie4e4d0842012-03-11 07:00:24 +00009072 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00009073 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9074 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009075 // Find all of the overloaded operators visible from this
9076 // point. We perform both an operator-name lookup from the local
9077 // scope and an argument-dependent lookup based on the types of
9078 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00009079 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009080 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00009081 if (S && OverOp != OO_None)
9082 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9083 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009084
John McCall9ae2f072010-08-23 23:25:46 +00009085 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009086 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009087
John McCall9ae2f072010-08-23 23:25:46 +00009088 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009089}
9090
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009091// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009092ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00009093 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00009094 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009095}
9096
Steve Naroff1b273c42007-09-16 14:56:35 +00009097/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009098ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00009099 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009100 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00009101 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009102 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009103 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00009104}
9105
John McCallf85e1932011-06-15 23:02:42 +00009106/// Given the last statement in a statement-expression, check whether
9107/// the result is a producing expression (like a call to an
9108/// ns_returns_retained function) and, if so, rebuild it to hoist the
9109/// release out of the full-expression. Otherwise, return null.
9110/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00009111static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00009112 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00009113 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00009114 if (!cleanups) return 0;
9115
9116 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00009117 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00009118 return 0;
9119
9120 // Splice out the cast. This shouldn't modify any interesting
9121 // features of the statement.
9122 Expr *producer = cast->getSubExpr();
9123 assert(producer->getType() == cast->getType());
9124 assert(producer->getValueKind() == cast->getValueKind());
9125 cleanups->setSubExpr(producer);
9126 return cleanups;
9127}
9128
John McCall73f428c2012-04-04 01:27:53 +00009129void Sema::ActOnStartStmtExpr() {
9130 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9131}
9132
9133void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00009134 // Note that function is also called by TreeTransform when leaving a
9135 // StmtExpr scope without rebuilding anything.
9136
John McCall73f428c2012-04-04 01:27:53 +00009137 DiscardCleanupsInEvaluationContext();
9138 PopExpressionEvaluationContext();
9139}
9140
John McCall60d7b3a2010-08-24 06:29:42 +00009141ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009142Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009143 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009144 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9145 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9146
John McCall73f428c2012-04-04 01:27:53 +00009147 if (hasAnyUnrecoverableErrorsInThisFunction())
9148 DiscardCleanupsInEvaluationContext();
9149 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9150 PopExpressionEvaluationContext();
9151
Douglas Gregordd8f5692010-03-10 04:54:39 +00009152 bool isFileScope
9153 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009154 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009155 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009156
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009157 // FIXME: there are a variety of strange constraints to enforce here, for
9158 // example, it is not possible to goto into a stmt expression apparently.
9159 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009160
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009161 // If there are sub stmts in the compound stmt, take the type of the last one
9162 // as the type of the stmtexpr.
9163 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009164 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009165 if (!Compound->body_empty()) {
9166 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009167 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009168 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009169 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9170 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009171 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009172 }
John McCallf85e1932011-06-15 23:02:42 +00009173
John Wiegley429bb272011-04-08 18:41:53 +00009174 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009175 // Do function/array conversion on the last expression, but not
9176 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009177 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9178 if (LastExpr.isInvalid())
9179 return ExprError();
9180 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009181
John Wiegley429bb272011-04-08 18:41:53 +00009182 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009183 // In ARC, if the final expression ends in a consume, splice
9184 // the consume out and bind it later. In the alternate case
9185 // (when dealing with a retainable type), the result
9186 // initialization will create a produce. In both cases the
9187 // result will be +1, and we'll need to balance that out with
9188 // a bind.
9189 if (Expr *rebuiltLastStmt
9190 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9191 LastExpr = rebuiltLastStmt;
9192 } else {
9193 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009194 InitializedEntity::InitializeResult(LPLoc,
9195 Ty,
9196 false),
9197 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009198 LastExpr);
9199 }
9200
John Wiegley429bb272011-04-08 18:41:53 +00009201 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009202 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009203 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009204 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009205 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009206 else
John Wiegley429bb272011-04-08 18:41:53 +00009207 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009208 StmtExprMayBindToTemp = true;
9209 }
9210 }
9211 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009212 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009213
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009214 // FIXME: Check that expression type is complete/non-abstract; statement
9215 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009216 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9217 if (StmtExprMayBindToTemp)
9218 return MaybeBindToTemporary(ResStmtExpr);
9219 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009220}
Steve Naroffd34e9152007-08-01 22:05:33 +00009221
John McCall60d7b3a2010-08-24 06:29:42 +00009222ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009223 TypeSourceInfo *TInfo,
9224 OffsetOfComponent *CompPtr,
9225 unsigned NumComponents,
9226 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009227 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009228 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009229 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009230
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009231 // We must have at least one component that refers to the type, and the first
9232 // one is known to be a field designator. Verify that the ArgTy represents
9233 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009234 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009235 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9236 << ArgTy << TypeRange);
9237
9238 // Type must be complete per C99 7.17p3 because a declaring a variable
9239 // with an incomplete type would be ill-formed.
9240 if (!Dependent
9241 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009242 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009243 return ExprError();
9244
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009245 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9246 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009247 // FIXME: This diagnostic isn't actually visible because the location is in
9248 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009249 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009250 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9251 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009252
9253 bool DidWarnAboutNonPOD = false;
9254 QualType CurrentType = ArgTy;
9255 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009256 SmallVector<OffsetOfNode, 4> Comps;
9257 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009258 for (unsigned i = 0; i != NumComponents; ++i) {
9259 const OffsetOfComponent &OC = CompPtr[i];
9260 if (OC.isBrackets) {
9261 // Offset of an array sub-field. TODO: Should we allow vector elements?
9262 if (!CurrentType->isDependentType()) {
9263 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9264 if(!AT)
9265 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9266 << CurrentType);
9267 CurrentType = AT->getElementType();
9268 } else
9269 CurrentType = Context.DependentTy;
9270
Richard Smithea011432011-10-17 23:29:39 +00009271 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9272 if (IdxRval.isInvalid())
9273 return ExprError();
9274 Expr *Idx = IdxRval.take();
9275
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009276 // The expression must be an integral expression.
9277 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009278 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9279 !Idx->getType()->isIntegerType())
9280 return ExprError(Diag(Idx->getLocStart(),
9281 diag::err_typecheck_subscript_not_integer)
9282 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009283
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009284 // Record this array index.
9285 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009286 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009287 continue;
9288 }
9289
9290 // Offset of a field.
9291 if (CurrentType->isDependentType()) {
9292 // We have the offset of a field, but we can't look into the dependent
9293 // type. Just record the identifier of the field.
9294 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9295 CurrentType = Context.DependentTy;
9296 continue;
9297 }
9298
9299 // We need to have a complete type to look into.
9300 if (RequireCompleteType(OC.LocStart, CurrentType,
9301 diag::err_offsetof_incomplete_type))
9302 return ExprError();
9303
9304 // Look for the designated field.
9305 const RecordType *RC = CurrentType->getAs<RecordType>();
9306 if (!RC)
9307 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9308 << CurrentType);
9309 RecordDecl *RD = RC->getDecl();
9310
9311 // C++ [lib.support.types]p5:
9312 // The macro offsetof accepts a restricted set of type arguments in this
9313 // International Standard. type shall be a POD structure or a POD union
9314 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009315 // C++11 [support.types]p4:
9316 // If type is not a standard-layout class (Clause 9), the results are
9317 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009318 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00009319 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009320 unsigned DiagID =
Richard Smith80ad52f2013-01-02 11:42:31 +00009321 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009322 : diag::warn_offsetof_non_pod_type;
9323
9324 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009325 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009326 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009327 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9328 << CurrentType))
9329 DidWarnAboutNonPOD = true;
9330 }
9331
9332 // Look for the field.
9333 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9334 LookupQualifiedName(R, RD);
9335 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009336 IndirectFieldDecl *IndirectMemberDecl = 0;
9337 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009338 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009339 MemberDecl = IndirectMemberDecl->getAnonField();
9340 }
9341
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009342 if (!MemberDecl)
9343 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9344 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9345 OC.LocEnd));
9346
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009347 // C99 7.17p3:
9348 // (If the specified member is a bit-field, the behavior is undefined.)
9349 //
9350 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009351 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009352 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9353 << MemberDecl->getDeclName()
9354 << SourceRange(BuiltinLoc, RParenLoc);
9355 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9356 return ExprError();
9357 }
Eli Friedman19410a72010-08-05 10:11:36 +00009358
9359 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009360 if (IndirectMemberDecl)
9361 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009362
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009363 // If the member was found in a base class, introduce OffsetOfNodes for
9364 // the base class indirections.
9365 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9366 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009367 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009368 CXXBasePath &Path = Paths.front();
9369 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9370 B != BEnd; ++B)
9371 Comps.push_back(OffsetOfNode(B->Base));
9372 }
Eli Friedman19410a72010-08-05 10:11:36 +00009373
Francois Pichet87c2e122010-11-21 06:08:52 +00009374 if (IndirectMemberDecl) {
9375 for (IndirectFieldDecl::chain_iterator FI =
9376 IndirectMemberDecl->chain_begin(),
9377 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9378 assert(isa<FieldDecl>(*FI));
9379 Comps.push_back(OffsetOfNode(OC.LocStart,
9380 cast<FieldDecl>(*FI), OC.LocEnd));
9381 }
9382 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009383 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009384
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009385 CurrentType = MemberDecl->getType().getNonReferenceType();
9386 }
9387
9388 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009389 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009390}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009391
John McCall60d7b3a2010-08-24 06:29:42 +00009392ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009393 SourceLocation BuiltinLoc,
9394 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009395 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009396 OffsetOfComponent *CompPtr,
9397 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009398 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009399
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009400 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009401 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009402 if (ArgTy.isNull())
9403 return ExprError();
9404
Eli Friedman5a15dc12010-08-05 10:15:45 +00009405 if (!ArgTInfo)
9406 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9407
9408 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009409 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009410}
9411
9412
John McCall60d7b3a2010-08-24 06:29:42 +00009413ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009414 Expr *CondExpr,
9415 Expr *LHSExpr, Expr *RHSExpr,
9416 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009417 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9418
John McCallf89e55a2010-11-18 06:31:45 +00009419 ExprValueKind VK = VK_RValue;
9420 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009421 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009422 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009423 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009424 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009425 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009426 } else {
9427 // The conditional expression is required to be a constant expression.
9428 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009429 ExprResult CondICE
9430 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9431 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009432 if (CondICE.isInvalid())
9433 return ExprError();
9434 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009435
Sebastian Redl28507842009-02-26 14:39:58 +00009436 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009437 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9438
9439 resType = ActiveExpr->getType();
9440 ValueDependent = ActiveExpr->isValueDependent();
9441 VK = ActiveExpr->getValueKind();
9442 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009443 }
9444
Sebastian Redlf53597f2009-03-15 17:47:39 +00009445 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009446 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009447 resType->isDependentType(),
9448 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009449}
9450
Steve Naroff4eb206b2008-09-03 18:15:37 +00009451//===----------------------------------------------------------------------===//
9452// Clang Extensions.
9453//===----------------------------------------------------------------------===//
9454
9455/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009456void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009457 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009458 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009459 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009460 if (CurScope)
9461 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009462 else
9463 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009464
Eli Friedman84b007f2012-01-26 03:00:14 +00009465 getCurBlock()->HasImplicitReturnType = true;
9466
John McCall538773c2011-11-11 03:19:12 +00009467 // Enter a new evaluation context to insulate the block from any
9468 // cleanups from the enclosing full-expression.
9469 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009470}
9471
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009472void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9473 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009474 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009475 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009476 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009477
John McCallbf1a0282010-06-04 23:28:52 +00009478 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009479 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009480
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009481 // FIXME: We should allow unexpanded parameter packs here, but that would,
9482 // in turn, make the block expression contain unexpanded parameter packs.
9483 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9484 // Drop the parameters.
9485 FunctionProtoType::ExtProtoInfo EPI;
9486 EPI.HasTrailingReturn = false;
9487 EPI.TypeQuals |= DeclSpec::TQ_const;
9488 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9489 EPI);
9490 Sig = Context.getTrivialTypeSourceInfo(T);
9491 }
9492
John McCall711c52b2011-01-05 12:14:39 +00009493 // GetTypeForDeclarator always produces a function type for a block
9494 // literal signature. Furthermore, it is always a FunctionProtoType
9495 // unless the function was written with a typedef.
9496 assert(T->isFunctionType() &&
9497 "GetTypeForDeclarator made a non-function block signature");
9498
9499 // Look for an explicit signature in that function type.
9500 FunctionProtoTypeLoc ExplicitSignature;
9501
9502 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00009503 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
John McCall711c52b2011-01-05 12:14:39 +00009504
9505 // Check whether that explicit signature was synthesized by
9506 // GetTypeForDeclarator. If so, don't save that as part of the
9507 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009508 if (ExplicitSignature.getLocalRangeBegin() ==
9509 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009510 // This would be much cheaper if we stored TypeLocs instead of
9511 // TypeSourceInfos.
9512 TypeLoc Result = ExplicitSignature.getResultLoc();
9513 unsigned Size = Result.getFullDataSize();
9514 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9515 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9516
9517 ExplicitSignature = FunctionProtoTypeLoc();
9518 }
John McCall82dc0092010-06-04 11:21:44 +00009519 }
Mike Stump1eb44332009-09-09 15:08:12 +00009520
John McCall711c52b2011-01-05 12:14:39 +00009521 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9522 CurBlock->FunctionType = T;
9523
9524 const FunctionType *Fn = T->getAs<FunctionType>();
9525 QualType RetTy = Fn->getResultType();
9526 bool isVariadic =
9527 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9528
John McCallc71a4912010-06-04 19:02:56 +00009529 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009530
John McCall82dc0092010-06-04 11:21:44 +00009531 // Don't allow returning a objc interface by value.
9532 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009533 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009534 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9535 return;
9536 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009537
John McCall82dc0092010-06-04 11:21:44 +00009538 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009539 // return type. TODO: what should we do with declarators like:
9540 // ^ * { ... }
9541 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009542 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009543 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009544 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009545 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009546 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009547
John McCall82dc0092010-06-04 11:21:44 +00009548 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009549 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009550 if (ExplicitSignature) {
9551 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9552 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009553 if (Param->getIdentifier() == 0 &&
9554 !Param->isImplicit() &&
9555 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009556 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009557 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009558 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009559 }
John McCall82dc0092010-06-04 11:21:44 +00009560
9561 // Fake up parameter variables if we have a typedef, like
9562 // ^ fntype { ... }
9563 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9564 for (FunctionProtoType::arg_type_iterator
9565 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9566 ParmVarDecl *Param =
9567 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009568 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009569 *I);
John McCallc71a4912010-06-04 19:02:56 +00009570 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009571 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009572 }
John McCall82dc0092010-06-04 11:21:44 +00009573
John McCallc71a4912010-06-04 19:02:56 +00009574 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009575 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009576 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009577 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9578 CurBlock->TheDecl->param_end(),
9579 /*CheckParameterNames=*/false);
9580 }
9581
John McCall82dc0092010-06-04 11:21:44 +00009582 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009583 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009584
John McCall82dc0092010-06-04 11:21:44 +00009585 // Put the parameter variables in scope. We can bail out immediately
9586 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009587 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009588 return;
9589
Steve Naroff090276f2008-10-10 01:28:17 +00009590 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009591 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9592 (*AI)->setOwningFunction(CurBlock->TheDecl);
9593
Steve Naroff090276f2008-10-10 01:28:17 +00009594 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009595 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009596 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009597
Steve Naroff090276f2008-10-10 01:28:17 +00009598 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009599 }
John McCall7a9813c2010-01-22 00:28:27 +00009600 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009601}
9602
9603/// ActOnBlockError - If there is an error parsing a block, this callback
9604/// is invoked to pop the information about the block from the action impl.
9605void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009606 // Leave the expression-evaluation context.
9607 DiscardCleanupsInEvaluationContext();
9608 PopExpressionEvaluationContext();
9609
Steve Naroff4eb206b2008-09-03 18:15:37 +00009610 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009611 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009612 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009613}
9614
9615/// ActOnBlockStmtExpr - This is called when the body of a block statement
9616/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009617ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009618 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009619 // If blocks are disabled, emit an error.
9620 if (!LangOpts.Blocks)
9621 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009622
John McCall538773c2011-11-11 03:19:12 +00009623 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009624 if (hasAnyUnrecoverableErrorsInThisFunction())
9625 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009626 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9627 PopExpressionEvaluationContext();
9628
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009629 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009630
9631 if (BSI->HasImplicitReturnType)
9632 deduceClosureReturnType(*BSI);
9633
Steve Naroff090276f2008-10-10 01:28:17 +00009634 PopDeclContext();
9635
Steve Naroff4eb206b2008-09-03 18:15:37 +00009636 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009637 if (!BSI->ReturnType.isNull())
9638 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009639
Mike Stump56925862009-07-28 22:04:01 +00009640 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009641 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009642
John McCall469a1eb2011-02-02 13:00:07 +00009643 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009644 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9645 SmallVector<BlockDecl::Capture, 4> Captures;
9646 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9647 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9648 if (Cap.isThisCapture())
9649 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009650 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009651 Cap.isNested(), Cap.getCopyExpr());
9652 Captures.push_back(NewCap);
9653 }
9654 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9655 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009656
John McCallc71a4912010-06-04 19:02:56 +00009657 // If the user wrote a function type in some form, try to use that.
9658 if (!BSI->FunctionType.isNull()) {
9659 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9660
9661 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9662 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9663
9664 // Turn protoless block types into nullary block types.
9665 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009666 FunctionProtoType::ExtProtoInfo EPI;
9667 EPI.ExtInfo = Ext;
9668 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009669
9670 // Otherwise, if we don't need to change anything about the function type,
9671 // preserve its sugar structure.
9672 } else if (FTy->getResultType() == RetTy &&
9673 (!NoReturn || FTy->getNoReturnAttr())) {
9674 BlockTy = BSI->FunctionType;
9675
9676 // Otherwise, make the minimal modifications to the function type.
9677 } else {
9678 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009679 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9680 EPI.TypeQuals = 0; // FIXME: silently?
9681 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009682 BlockTy = Context.getFunctionType(RetTy,
9683 FPT->arg_type_begin(),
9684 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009685 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009686 }
9687
9688 // If we don't have a function type, just build one from nothing.
9689 } else {
John McCalle23cf432010-12-14 08:05:40 +00009690 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009691 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009692 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009693 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009694
John McCallc71a4912010-06-04 19:02:56 +00009695 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9696 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009697 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009698
Chris Lattner17a78302009-04-19 05:28:12 +00009699 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009700 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009701 !hasAnyUnrecoverableErrorsInThisFunction() &&
9702 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009703 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009704
Chris Lattnere476bdc2011-02-17 23:58:47 +00009705 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009706
Jordan Rose7dd900e2012-07-02 21:19:23 +00009707 // Try to apply the named return value optimization. We have to check again
9708 // if we can do this, though, because blocks keep return statements around
9709 // to deduce an implicit return type.
9710 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9711 !BSI->TheDecl->isDependentContext())
9712 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009713
Benjamin Kramerd2486192011-07-12 14:11:05 +00009714 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9715 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009716 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009717
John McCall80ee6e82011-11-10 05:35:25 +00009718 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009719 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009720 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009721 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009722 ExprCleanupObjects.push_back(Result->getBlockDecl());
9723 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009724
9725 // It also gets a branch-protected scope if any of the captured
9726 // variables needs destruction.
9727 for (BlockDecl::capture_const_iterator
9728 ci = Result->getBlockDecl()->capture_begin(),
9729 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9730 const VarDecl *var = ci->getVariable();
9731 if (var->getType().isDestructedType() != QualType::DK_none) {
9732 getCurFunction()->setHasBranchProtectedScope();
9733 break;
9734 }
9735 }
John McCall80ee6e82011-11-10 05:35:25 +00009736 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009737
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009738 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009739}
9740
John McCall60d7b3a2010-08-24 06:29:42 +00009741ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009742 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009743 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009744 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009745 GetTypeFromParser(Ty, &TInfo);
9746 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009747}
9748
John McCall60d7b3a2010-08-24 06:29:42 +00009749ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009750 Expr *E, TypeSourceInfo *TInfo,
9751 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009752 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009753
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009754 // Get the va_list type
9755 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009756 if (VaListType->isArrayType()) {
9757 // Deal with implicit array decay; for example, on x86-64,
9758 // va_list is an array, but it's supposed to decay to
9759 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009760 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009761 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009762 ExprResult Result = UsualUnaryConversions(E);
9763 if (Result.isInvalid())
9764 return ExprError();
9765 E = Result.take();
Logan Chienb687f3b2012-10-20 06:11:33 +00009766 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9767 // If va_list is a record type and we are compiling in C++ mode,
9768 // check the argument using reference binding.
9769 InitializedEntity Entity
9770 = InitializedEntity::InitializeParameter(Context,
9771 Context.getLValueReferenceType(VaListType), false);
9772 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9773 if (Init.isInvalid())
9774 return ExprError();
9775 E = Init.takeAs<Expr>();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009776 } else {
9777 // Otherwise, the va_list argument must be an l-value because
9778 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009779 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009780 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009781 return ExprError();
9782 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009783
Douglas Gregordd027302009-05-19 23:10:31 +00009784 if (!E->isTypeDependent() &&
9785 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009786 return ExprError(Diag(E->getLocStart(),
9787 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009788 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009789 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009790
David Majnemer0adde122011-06-14 05:17:32 +00009791 if (!TInfo->getType()->isDependentType()) {
9792 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009793 diag::err_second_parameter_to_va_arg_incomplete,
9794 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009795 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009796
David Majnemer0adde122011-06-14 05:17:32 +00009797 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009798 TInfo->getType(),
9799 diag::err_second_parameter_to_va_arg_abstract,
9800 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009801 return ExprError();
9802
Douglas Gregor4eb75222011-07-30 06:45:27 +00009803 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009804 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009805 TInfo->getType()->isObjCLifetimeType()
9806 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9807 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009808 << TInfo->getType()
9809 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009810 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009811
9812 // Check for va_arg where arguments of the given type will be promoted
9813 // (i.e. this va_arg is guaranteed to have undefined behavior).
9814 QualType PromoteType;
9815 if (TInfo->getType()->isPromotableIntegerType()) {
9816 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9817 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9818 PromoteType = QualType();
9819 }
9820 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9821 PromoteType = Context.DoubleTy;
9822 if (!PromoteType.isNull())
Ted Kremenekcbb99ef2013-01-08 01:50:40 +00009823 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
9824 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
9825 << TInfo->getType()
9826 << PromoteType
9827 << TInfo->getTypeLoc().getSourceRange());
David Majnemer0adde122011-06-14 05:17:32 +00009828 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009829
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009830 QualType T = TInfo->getType().getNonLValueExprType(Context);
9831 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009832}
9833
John McCall60d7b3a2010-08-24 06:29:42 +00009834ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009835 // The type of __null will be int or long, depending on the size of
9836 // pointers on the target.
9837 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009838 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9839 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009840 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009841 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009842 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009843 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009844 Ty = Context.LongLongTy;
9845 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009846 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009847 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009848
Sebastian Redlf53597f2009-03-15 17:47:39 +00009849 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009850}
9851
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009852static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009853 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009854 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009855 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009856
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009857 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9858 if (!PT)
9859 return;
9860
9861 // Check if the destination is of type 'id'.
9862 if (!PT->isObjCIdType()) {
9863 // Check if the destination is the 'NSString' interface.
9864 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9865 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9866 return;
9867 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009868
John McCall4b9c2d22011-11-06 09:01:30 +00009869 // Ignore any parens, implicit casts (should only be
9870 // array-to-pointer decays), and not-so-opaque values. The last is
9871 // important for making this trigger for property assignments.
9872 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9873 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9874 if (OV->getSourceExpr())
9875 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9876
9877 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009878 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009879 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009880
Douglas Gregor849b2432010-03-31 17:46:05 +00009881 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009882}
9883
Chris Lattner5cf216b2008-01-04 18:04:52 +00009884bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9885 SourceLocation Loc,
9886 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009887 Expr *SrcExpr, AssignmentAction Action,
9888 bool *Complained) {
9889 if (Complained)
9890 *Complained = false;
9891
Chris Lattner5cf216b2008-01-04 18:04:52 +00009892 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009893 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009894 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009895 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009896 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009897 ConversionFixItGenerator ConvHints;
9898 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009899 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009900
Chris Lattner5cf216b2008-01-04 18:04:52 +00009901 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009902 case Compatible:
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00009903 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9904 return false;
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009905
Chris Lattnerb7b61152008-01-04 18:22:42 +00009906 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009907 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009908 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9909 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009910 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009911 case IntToPointer:
9912 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009913 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9914 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009915 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009916 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009917 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009918 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009919 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9920 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009921 if (Hint.isNull() && !CheckInferredResultType) {
9922 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9923 }
9924 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009925 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009926 case IncompatiblePointerSign:
9927 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9928 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009929 case FunctionVoidPointer:
9930 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9931 break;
John McCall86c05f32011-02-01 00:10:29 +00009932 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009933 // Perform array-to-pointer decay if necessary.
9934 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9935
John McCall86c05f32011-02-01 00:10:29 +00009936 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9937 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9938 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9939 DiagKind = diag::err_typecheck_incompatible_address_space;
9940 break;
John McCallf85e1932011-06-15 23:02:42 +00009941
9942
9943 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009944 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009945 break;
John McCall86c05f32011-02-01 00:10:29 +00009946 }
9947
9948 llvm_unreachable("unknown error case for discarding qualifiers!");
9949 // fallthrough
9950 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009951 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009952 // If the qualifiers lost were because we were applying the
9953 // (deprecated) C++ conversion from a string literal to a char*
9954 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9955 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009956 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009957 // bit of refactoring (so that the second argument is an
9958 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009959 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009960 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009961 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009962 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9963 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009964 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9965 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009966 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009967 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009968 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009969 case IntToBlockPointer:
9970 DiagKind = diag::err_int_to_block_pointer;
9971 break;
9972 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009973 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009974 break;
Steve Naroff39579072008-10-14 22:18:38 +00009975 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009976 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009977 // it can give a more specific diagnostic.
9978 DiagKind = diag::warn_incompatible_qualified_id;
9979 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009980 case IncompatibleVectors:
9981 DiagKind = diag::warn_incompatible_vectors;
9982 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009983 case IncompatibleObjCWeakRef:
9984 DiagKind = diag::err_arc_weak_unavailable_assign;
9985 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009986 case Incompatible:
9987 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009988 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9989 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009990 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009991 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009992 break;
9993 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009994
Douglas Gregord4eea832010-04-09 00:35:39 +00009995 QualType FirstType, SecondType;
9996 switch (Action) {
9997 case AA_Assigning:
9998 case AA_Initializing:
9999 // The destination type comes first.
10000 FirstType = DstType;
10001 SecondType = SrcType;
10002 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010003
Douglas Gregord4eea832010-04-09 00:35:39 +000010004 case AA_Returning:
10005 case AA_Passing:
10006 case AA_Converting:
10007 case AA_Sending:
10008 case AA_Casting:
10009 // The source type comes first.
10010 FirstType = SrcType;
10011 SecondType = DstType;
10012 break;
10013 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010014
Anna Zaks67221552011-07-28 19:51:27 +000010015 PartialDiagnostic FDiag = PDiag(DiagKind);
10016 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10017
10018 // If we can fix the conversion, suggest the FixIts.
10019 assert(ConvHints.isNull() || Hint.isNull());
10020 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +000010021 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10022 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +000010023 FDiag << *HI;
10024 } else {
10025 FDiag << Hint;
10026 }
10027 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10028
Richard Trieu6efd4c52011-11-23 22:32:32 +000010029 if (MayHaveFunctionDiff)
10030 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10031
Anna Zaks67221552011-07-28 19:51:27 +000010032 Diag(Loc, FDiag);
10033
Richard Trieu6efd4c52011-11-23 22:32:32 +000010034 if (SecondType == Context.OverloadTy)
10035 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10036 FirstType);
10037
Douglas Gregor926df6c2011-06-11 01:09:30 +000010038 if (CheckInferredResultType)
10039 EmitRelatedResultTypeNote(SrcExpr);
10040
Douglas Gregora41a8c52010-04-22 00:20:18 +000010041 if (Complained)
10042 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010043 return isInvalid;
10044}
Anders Carlssone21555e2008-11-30 19:50:32 +000010045
Richard Smith282e7e62012-02-04 09:53:13 +000010046ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10047 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010048 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10049 public:
10050 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10051 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10052 }
10053 } Diagnoser;
10054
10055 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10056}
10057
10058ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10059 llvm::APSInt *Result,
10060 unsigned DiagID,
10061 bool AllowFold) {
10062 class IDDiagnoser : public VerifyICEDiagnoser {
10063 unsigned DiagID;
10064
10065 public:
10066 IDDiagnoser(unsigned DiagID)
10067 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10068
10069 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10070 S.Diag(Loc, DiagID) << SR;
10071 }
10072 } Diagnoser(DiagID);
10073
10074 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10075}
10076
10077void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10078 SourceRange SR) {
10079 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +000010080}
10081
Benjamin Kramerd448ce02012-04-18 14:22:41 +000010082ExprResult
10083Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010084 VerifyICEDiagnoser &Diagnoser,
10085 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010086 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +000010087
Richard Smith80ad52f2013-01-02 11:42:31 +000010088 if (getLangOpts().CPlusPlus11) {
Richard Smith282e7e62012-02-04 09:53:13 +000010089 // C++11 [expr.const]p5:
10090 // If an expression of literal class type is used in a context where an
10091 // integral constant expression is required, then that class type shall
10092 // have a single non-explicit conversion function to an integral or
10093 // unscoped enumeration type
10094 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +000010095 if (!Diagnoser.Suppress) {
10096 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10097 public:
10098 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
10099
10100 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10101 QualType T) {
10102 return S.Diag(Loc, diag::err_ice_not_integral) << T;
10103 }
10104
10105 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10106 SourceLocation Loc,
10107 QualType T) {
10108 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10109 }
10110
10111 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10112 SourceLocation Loc,
10113 QualType T,
10114 QualType ConvTy) {
10115 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10116 }
10117
10118 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10119 CXXConversionDecl *Conv,
10120 QualType ConvTy) {
10121 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10122 << ConvTy->isEnumeralType() << ConvTy;
10123 }
10124
10125 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10126 QualType T) {
10127 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10128 }
10129
10130 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10131 CXXConversionDecl *Conv,
10132 QualType ConvTy) {
10133 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10134 << ConvTy->isEnumeralType() << ConvTy;
10135 }
10136
10137 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10138 SourceLocation Loc,
10139 QualType T,
10140 QualType ConvTy) {
10141 return DiagnosticBuilder::getEmpty();
10142 }
10143 } ConvertDiagnoser;
10144
10145 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10146 ConvertDiagnoser,
10147 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +000010148 } else {
10149 // The caller wants to silently enquire whether this is an ICE. Don't
10150 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010151 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10152 public:
10153 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10154
10155 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10156 QualType T) {
10157 return DiagnosticBuilder::getEmpty();
10158 }
10159
10160 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10161 SourceLocation Loc,
10162 QualType T) {
10163 return DiagnosticBuilder::getEmpty();
10164 }
10165
10166 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10167 SourceLocation Loc,
10168 QualType T,
10169 QualType ConvTy) {
10170 return DiagnosticBuilder::getEmpty();
10171 }
10172
10173 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10174 CXXConversionDecl *Conv,
10175 QualType ConvTy) {
10176 return DiagnosticBuilder::getEmpty();
10177 }
10178
10179 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10180 QualType T) {
10181 return DiagnosticBuilder::getEmpty();
10182 }
10183
10184 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10185 CXXConversionDecl *Conv,
10186 QualType ConvTy) {
10187 return DiagnosticBuilder::getEmpty();
10188 }
10189
10190 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10191 SourceLocation Loc,
10192 QualType T,
10193 QualType ConvTy) {
10194 return DiagnosticBuilder::getEmpty();
10195 }
10196 } ConvertDiagnoser;
10197
10198 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10199 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +000010200 }
10201 if (Converted.isInvalid())
10202 return Converted;
10203 E = Converted.take();
10204 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10205 return ExprError();
10206 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10207 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010208 if (!Diagnoser.Suppress)
10209 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000010210 return ExprError();
10211 }
10212
Richard Smithdaaefc52011-12-14 23:32:26 +000010213 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10214 // in the non-ICE case.
Richard Smith80ad52f2013-01-02 11:42:31 +000010215 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000010216 if (Result)
10217 *Result = E->EvaluateKnownConstInt(Context);
10218 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010219 }
10220
Anders Carlssone21555e2008-11-30 19:50:32 +000010221 Expr::EvalResult EvalResult;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010222 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdd1f29b2011-12-12 09:28:41 +000010223 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000010224
Richard Smithdaaefc52011-12-14 23:32:26 +000010225 // Try to evaluate the expression, and produce diagnostics explaining why it's
10226 // not a constant expression as a side-effect.
10227 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10228 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10229
10230 // In C++11, we can rely on diagnostics being produced for any expression
10231 // which is not a constant expression. If no diagnostics were produced, then
10232 // this is a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +000010233 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010234 if (Result)
10235 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010236 return Owned(E);
10237 }
10238
10239 // If our only note is the usual "invalid subexpression" note, just point
10240 // the caret at its location rather than producing an essentially
10241 // redundant note.
10242 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10243 diag::note_invalid_subexpr_in_const_expr) {
10244 DiagLoc = Notes[0].first;
10245 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010246 }
10247
10248 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010249 if (!Diagnoser.Suppress) {
10250 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010251 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10252 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010253 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010254
Richard Smith282e7e62012-02-04 09:53:13 +000010255 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010256 }
10257
Douglas Gregorab41fe92012-05-04 22:38:52 +000010258 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010259 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10260 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010261
Anders Carlssone21555e2008-11-30 19:50:32 +000010262 if (Result)
10263 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010264 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010265}
Douglas Gregore0762c92009-06-19 23:52:42 +000010266
Eli Friedmanef331b72012-01-20 01:26:23 +000010267namespace {
10268 // Handle the case where we conclude a expression which we speculatively
10269 // considered to be unevaluated is actually evaluated.
10270 class TransformToPE : public TreeTransform<TransformToPE> {
10271 typedef TreeTransform<TransformToPE> BaseTransform;
10272
10273 public:
10274 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10275
10276 // Make sure we redo semantic analysis
10277 bool AlwaysRebuild() { return true; }
10278
Eli Friedman56ff2832012-02-06 23:29:57 +000010279 // Make sure we handle LabelStmts correctly.
10280 // FIXME: This does the right thing, but maybe we need a more general
10281 // fix to TreeTransform?
10282 StmtResult TransformLabelStmt(LabelStmt *S) {
10283 S->getDecl()->setStmt(0);
10284 return BaseTransform::TransformLabelStmt(S);
10285 }
10286
Eli Friedmanef331b72012-01-20 01:26:23 +000010287 // We need to special-case DeclRefExprs referring to FieldDecls which
10288 // are not part of a member pointer formation; normal TreeTransforming
10289 // doesn't catch this case because of the way we represent them in the AST.
10290 // FIXME: This is a bit ugly; is it really the best way to handle this
10291 // case?
10292 //
10293 // Error on DeclRefExprs referring to FieldDecls.
10294 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10295 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010296 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010297 return SemaRef.Diag(E->getLocation(),
10298 diag::err_invalid_non_static_member_use)
10299 << E->getDecl() << E->getSourceRange();
10300
10301 return BaseTransform::TransformDeclRefExpr(E);
10302 }
10303
10304 // Exception: filter out member pointer formation
10305 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10306 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10307 return E;
10308
10309 return BaseTransform::TransformUnaryOperator(E);
10310 }
10311
Douglas Gregore2c59132012-02-09 08:14:43 +000010312 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10313 // Lambdas never need to be transformed.
10314 return E;
10315 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010316 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010317}
10318
Benjamin Krameraccaf192012-11-14 15:08:31 +000010319ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010320 assert(ExprEvalContexts.back().Context == Unevaluated &&
10321 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010322 ExprEvalContexts.back().Context =
10323 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10324 if (ExprEvalContexts.back().Context == Unevaluated)
10325 return E;
10326 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010327}
10328
Douglas Gregor2afce722009-11-26 00:44:06 +000010329void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010330Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010331 Decl *LambdaContextDecl,
10332 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010333 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010334 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010335 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010336 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010337 LambdaContextDecl,
10338 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010339 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010340 if (!MaybeODRUseExprs.empty())
10341 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010342}
10343
Eli Friedman80bfa3d2012-09-26 04:34:21 +000010344void
10345Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10346 ReuseLambdaContextDecl_t,
10347 bool IsDecltype) {
10348 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10349 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10350}
10351
Richard Trieu67e29332011-08-02 04:35:43 +000010352void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010353 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010354
Douglas Gregore2c59132012-02-09 08:14:43 +000010355 if (!Rec.Lambdas.empty()) {
10356 if (Rec.Context == Unevaluated) {
10357 // C++11 [expr.prim.lambda]p2:
10358 // A lambda-expression shall not appear in an unevaluated operand
10359 // (Clause 5).
10360 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10361 Diag(Rec.Lambdas[I]->getLocStart(),
10362 diag::err_lambda_unevaluated_operand);
10363 } else {
10364 // Mark the capture expressions odr-used. This was deferred
10365 // during lambda expression creation.
10366 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10367 LambdaExpr *Lambda = Rec.Lambdas[I];
10368 for (LambdaExpr::capture_init_iterator
10369 C = Lambda->capture_init_begin(),
10370 CEnd = Lambda->capture_init_end();
10371 C != CEnd; ++C) {
10372 MarkDeclarationsReferencedInExpr(*C);
10373 }
10374 }
10375 }
10376 }
10377
Douglas Gregor2afce722009-11-26 00:44:06 +000010378 // When are coming out of an unevaluated context, clear out any
10379 // temporaries that we may have created as part of the evaluation of
10380 // the expression in that context: they aren't relevant because they
10381 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010382 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010383 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10384 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010385 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010386 CleanupVarDeclMarking();
10387 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010388 // Otherwise, merge the contexts together.
10389 } else {
10390 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010391 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10392 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010393 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010394
10395 // Pop the current expression evaluation context off the stack.
10396 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010397}
Douglas Gregore0762c92009-06-19 23:52:42 +000010398
John McCallf85e1932011-06-15 23:02:42 +000010399void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010400 ExprCleanupObjects.erase(
10401 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10402 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010403 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010404 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010405}
10406
Eli Friedman71b8fb52012-01-21 01:01:51 +000010407ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10408 if (!E->getType()->isVariablyModifiedType())
10409 return E;
Benjamin Krameraccaf192012-11-14 15:08:31 +000010410 return TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +000010411}
10412
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010413static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010414 // Do not mark anything as "used" within a dependent context; wait for
10415 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010416 if (SemaRef.CurContext->isDependentContext())
10417 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010418
Eli Friedman5f2987c2012-02-02 03:46:19 +000010419 switch (SemaRef.ExprEvalContexts.back().Context) {
10420 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010421 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010422 // (Depending on how you read the standard, we actually do need to do
10423 // something here for null pointer constants, but the standard's
10424 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010425 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010426
Eli Friedman5f2987c2012-02-02 03:46:19 +000010427 case Sema::ConstantEvaluated:
10428 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010429 // We are in a potentially evaluated expression (or a constant-expression
10430 // in C++03); we need to do implicit template instantiation, implicitly
10431 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010432 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010433
Eli Friedman5f2987c2012-02-02 03:46:19 +000010434 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010435 // Referenced declarations will only be used if the construct in the
10436 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010437 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010438 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010439 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010440}
10441
10442/// \brief Mark a function referenced, and check whether it is odr-used
10443/// (C++ [basic.def.odr]p2, C99 6.9p3)
10444void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10445 assert(Func && "No function?");
10446
10447 Func->setReferenced();
10448
Richard Smithce2661f2012-11-07 01:14:25 +000010449 // C++11 [basic.def.odr]p3:
10450 // A function whose name appears as a potentially-evaluated expression is
10451 // odr-used if it is the unique lookup result or the selected member of a
10452 // set of overloaded functions [...].
10453 //
10454 // We (incorrectly) mark overload resolution as an unevaluated context, so we
10455 // can just check that here. Skip the rest of this function if we've already
10456 // marked the function as used.
10457 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10458 // C++11 [temp.inst]p3:
10459 // Unless a function template specialization has been explicitly
10460 // instantiated or explicitly specialized, the function template
10461 // specialization is implicitly instantiated when the specialization is
10462 // referenced in a context that requires a function definition to exist.
10463 //
10464 // We consider constexpr function templates to be referenced in a context
10465 // that requires a definition to exist whenever they are referenced.
10466 //
10467 // FIXME: This instantiates constexpr functions too frequently. If this is
10468 // really an unevaluated context (and we're not just in the definition of a
10469 // function template or overload resolution or other cases which we
10470 // incorrectly consider to be unevaluated contexts), and we're not in a
10471 // subexpression which we actually need to evaluate (for instance, a
10472 // template argument, array bound or an expression in a braced-init-list),
10473 // we are not permitted to instantiate this constexpr function definition.
10474 //
10475 // FIXME: This also implicitly defines special members too frequently. They
10476 // are only supposed to be implicitly defined if they are odr-used, but they
10477 // are not odr-used from constant expressions in unevaluated contexts.
10478 // However, they cannot be referenced if they are deleted, and they are
10479 // deleted whenever the implicit definition of the special member would
10480 // fail.
10481 if (!Func->isConstexpr() || Func->getBody())
10482 return;
10483 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10484 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10485 return;
10486 }
Mike Stump1eb44332009-09-09 15:08:12 +000010487
Douglas Gregore0762c92009-06-19 23:52:42 +000010488 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010489 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010490 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010491 if (Constructor->isDefaultConstructor()) {
10492 if (Constructor->isTrivial())
10493 return;
10494 if (!Constructor->isUsed(false))
10495 DefineImplicitDefaultConstructor(Loc, Constructor);
10496 } else if (Constructor->isCopyConstructor()) {
10497 if (!Constructor->isUsed(false))
10498 DefineImplicitCopyConstructor(Loc, Constructor);
10499 } else if (Constructor->isMoveConstructor()) {
10500 if (!Constructor->isUsed(false))
10501 DefineImplicitMoveConstructor(Loc, Constructor);
10502 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010503 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010504
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010505 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010506 } else if (CXXDestructorDecl *Destructor =
10507 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010508 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10509 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010510 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010511 if (Destructor->isVirtual())
10512 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010513 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010514 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10515 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010516 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010517 if (!MethodDecl->isUsed(false)) {
10518 if (MethodDecl->isCopyAssignmentOperator())
10519 DefineImplicitCopyAssignment(Loc, MethodDecl);
10520 else
10521 DefineImplicitMoveAssignment(Loc, MethodDecl);
10522 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010523 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10524 MethodDecl->getParent()->isLambda()) {
10525 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10526 if (Conversion->isLambdaToBlockPointerConversion())
10527 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10528 else
10529 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010530 } else if (MethodDecl->isVirtual())
10531 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010532 }
John McCall15e310a2011-02-19 02:53:41 +000010533
Eli Friedman5f2987c2012-02-02 03:46:19 +000010534 // Recursive functions should be marked when used from another function.
10535 // FIXME: Is this really right?
10536 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010537
Richard Smithb9d0b762012-07-27 04:22:15 +000010538 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010539 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010540 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010541 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10542 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010543
Eli Friedman5f2987c2012-02-02 03:46:19 +000010544 // Implicit instantiation of function templates and member functions of
10545 // class templates.
10546 if (Func->isImplicitlyInstantiable()) {
10547 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010548 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010549 if (FunctionTemplateSpecializationInfo *SpecInfo
10550 = Func->getTemplateSpecializationInfo()) {
10551 if (SpecInfo->getPointOfInstantiation().isInvalid())
10552 SpecInfo->setPointOfInstantiation(Loc);
10553 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010554 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010555 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010556 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10557 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010558 } else if (MemberSpecializationInfo *MSInfo
10559 = Func->getMemberSpecializationInfo()) {
10560 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010561 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010562 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010563 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010564 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010565 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10566 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010567 }
Mike Stump1eb44332009-09-09 15:08:12 +000010568
Richard Smith57b9c4e2012-02-14 22:25:15 +000010569 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010570 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10571 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010572 PendingLocalImplicitInstantiations.push_back(
10573 std::make_pair(Func, PointOfInstantiation));
10574 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010575 // Do not defer instantiations of constexpr functions, to avoid the
10576 // expression evaluator needing to call back into Sema if it sees a
10577 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010578 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010579 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010580 PendingInstantiations.push_back(std::make_pair(Func,
10581 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010582 // Notify the consumer that a function was implicitly instantiated.
10583 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10584 }
John McCall15e310a2011-02-19 02:53:41 +000010585 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010586 } else {
10587 // Walk redefinitions, as some of them may be instantiable.
10588 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10589 e(Func->redecls_end()); i != e; ++i) {
10590 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10591 MarkFunctionReferenced(Loc, *i);
10592 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010593 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010594
10595 // Keep track of used but undefined functions.
Nick Lewyckycd0655b2013-02-01 08:13:20 +000010596 if (!Func->isDefined()) {
10597 if (Func->getLinkage() != ExternalLinkage)
10598 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10599 else if (Func->getMostRecentDecl()->isInlined() &&
10600 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10601 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
10602 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010603 }
10604
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010605 // Normally the must current decl is marked used while processing the use and
10606 // any subsequent decls are marked used by decl merging. This fails with
10607 // template instantiation since marking can happen at the end of the file
10608 // and, because of the two phase lookup, this function is called with at
10609 // decl in the middle of a decl chain. We loop to maintain the invariant
10610 // that once a decl is used, all decls after it are also used.
Rafael Espindolaa6d20202013-01-08 19:58:34 +000010611 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010612 F->setUsed(true);
10613 if (F == Func)
10614 break;
Rafael Espindolab9725cf2013-01-08 19:43:34 +000010615 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010616}
10617
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010618static void
10619diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10620 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010621 DeclContext *VarDC = var->getDeclContext();
10622
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010623 // If the parameter still belongs to the translation unit, then
10624 // we're actually just using one parameter in the declaration of
10625 // the next.
10626 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010627 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010628 return;
10629
Eli Friedman0a294222012-02-07 00:15:00 +000010630 // For C code, don't diagnose about capture if we're not actually in code
10631 // right now; it's impossible to write a non-constant expression outside of
10632 // function context, so we'll get other (more useful) diagnostics later.
10633 //
10634 // For C++, things get a bit more nasty... it would be nice to suppress this
10635 // diagnostic for certain cases like using a local variable in an array bound
10636 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010637 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010638 return;
10639
Eli Friedman0a294222012-02-07 00:15:00 +000010640 if (isa<CXXMethodDecl>(VarDC) &&
10641 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10642 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10643 << var->getIdentifier();
10644 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10645 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10646 << var->getIdentifier() << fn->getDeclName();
10647 } else if (isa<BlockDecl>(VarDC)) {
10648 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10649 << var->getIdentifier();
10650 } else {
10651 // FIXME: Is there any other context where a local variable can be
10652 // declared?
10653 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10654 << var->getIdentifier();
10655 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010656
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010657 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10658 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010659
10660 // FIXME: Add additional diagnostic info about class etc. which prevents
10661 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010662}
10663
Douglas Gregorf8af9822012-02-12 18:42:33 +000010664/// \brief Capture the given variable in the given lambda expression.
10665static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010666 VarDecl *Var, QualType FieldType,
10667 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010668 SourceLocation Loc,
10669 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010670 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010671
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010672 // Build the non-static data member.
10673 FieldDecl *Field
10674 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10675 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010676 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010677 Field->setImplicit(true);
10678 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010679 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010680
10681 // C++11 [expr.prim.lambda]p21:
10682 // When the lambda-expression is evaluated, the entities that
10683 // are captured by copy are used to direct-initialize each
10684 // corresponding non-static data member of the resulting closure
10685 // object. (For array members, the array elements are
10686 // direct-initialized in increasing subscript order.) These
10687 // initializations are performed in the (unspecified) order in
10688 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010689
Douglas Gregore2c59132012-02-09 08:14:43 +000010690 // Introduce a new evaluation context for the initialization, so
10691 // that temporaries introduced as part of the capture are retained
10692 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010693 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10694
Douglas Gregor73d90922012-02-10 09:26:04 +000010695 // C++ [expr.prim.labda]p12:
10696 // An entity captured by a lambda-expression is odr-used (3.2) in
10697 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010698 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10699 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010700 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010701 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010702
10703 // When the field has array type, create index variables for each
10704 // dimension of the array. We use these index variables to subscript
10705 // the source array, and other clients (e.g., CodeGen) will perform
10706 // the necessary iteration with these index variables.
10707 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010708 QualType BaseType = FieldType;
10709 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010710 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010711 while (const ConstantArrayType *Array
10712 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010713 // Create the iteration variable for this array index.
10714 IdentifierInfo *IterationVarName = 0;
10715 {
10716 SmallString<8> Str;
10717 llvm::raw_svector_ostream OS(Str);
10718 OS << "__i" << IndexVariables.size();
10719 IterationVarName = &S.Context.Idents.get(OS.str());
10720 }
10721 VarDecl *IterationVar
10722 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10723 IterationVarName, SizeType,
10724 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10725 SC_None, SC_None);
10726 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010727 LSI->ArrayIndexVars.push_back(IterationVar);
10728
Douglas Gregor18fe0842012-02-09 02:45:47 +000010729 // Create a reference to the iteration variable.
10730 ExprResult IterationVarRef
10731 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10732 assert(!IterationVarRef.isInvalid() &&
10733 "Reference to invented variable cannot fail!");
10734 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10735 assert(!IterationVarRef.isInvalid() &&
10736 "Conversion of invented variable cannot fail!");
10737
10738 // Subscript the array with this iteration variable.
10739 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10740 Ref, Loc, IterationVarRef.take(), Loc);
10741 if (Subscript.isInvalid()) {
10742 S.CleanupVarDeclMarking();
10743 S.DiscardCleanupsInEvaluationContext();
10744 S.PopExpressionEvaluationContext();
10745 return ExprError();
10746 }
10747
10748 Ref = Subscript.take();
10749 BaseType = Array->getElementType();
10750 }
10751
10752 // Construct the entity that we will be initializing. For an array, this
10753 // will be first element in the array, which may require several levels
10754 // of array-subscript entities.
10755 SmallVector<InitializedEntity, 4> Entities;
10756 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010757 Entities.push_back(
10758 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010759 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10760 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10761 0,
10762 Entities.back()));
10763
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010764 InitializationKind InitKind
10765 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010766 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010767 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010768 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010769 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010770
10771 // If this initialization requires any cleanups (e.g., due to a
10772 // default argument to a copy constructor), note that for the
10773 // lambda.
10774 if (S.ExprNeedsCleanups)
10775 LSI->ExprNeedsCleanups = true;
10776
10777 // Exit the expression evaluation context used for the capture.
10778 S.CleanupVarDeclMarking();
10779 S.DiscardCleanupsInEvaluationContext();
10780 S.PopExpressionEvaluationContext();
10781 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010782}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010783
Douglas Gregor999713e2012-02-18 09:37:24 +000010784bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10785 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10786 bool BuildAndDiagnose,
10787 QualType &CaptureType,
10788 QualType &DeclRefType) {
10789 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010790
Eli Friedmanb942cb22012-02-03 22:47:37 +000010791 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010792 if (Var->getDeclContext() == DC) return true;
10793 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010794
Douglas Gregorf8af9822012-02-12 18:42:33 +000010795 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010796
Douglas Gregor999713e2012-02-18 09:37:24 +000010797 // Walk up the stack to determine whether we can capture the variable,
10798 // performing the "simple" checks that don't depend on type. We stop when
10799 // we've either hit the declared scope of the variable or find an existing
10800 // capture of that variable.
10801 CaptureType = Var->getType();
10802 DeclRefType = CaptureType.getNonReferenceType();
10803 bool Explicit = (Kind != TryCapture_Implicit);
10804 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010805 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010806 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010807 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010808 DeclContext *ParentDC;
10809 if (isa<BlockDecl>(DC))
10810 ParentDC = DC->getParent();
10811 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010812 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010813 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10814 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010815 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010816 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010817 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010818 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010819 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010820
Eli Friedmanb942cb22012-02-03 22:47:37 +000010821 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010822 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010823
Eli Friedmanb942cb22012-02-03 22:47:37 +000010824 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010825 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010826 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010827 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010828
10829 // Retrieve the capture type for this variable.
10830 CaptureType = CSI->getCapture(Var).getCaptureType();
10831
10832 // Compute the type of an expression that refers to this variable.
10833 DeclRefType = CaptureType.getNonReferenceType();
10834
10835 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10836 if (Cap.isCopyCapture() &&
10837 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10838 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010839 break;
10840 }
10841
Douglas Gregorf8af9822012-02-12 18:42:33 +000010842 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010843 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010844
10845 // Lambdas are not allowed to capture unnamed variables
10846 // (e.g. anonymous unions).
10847 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10848 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010849 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010850 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010851 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10852 Diag(Var->getLocation(), diag::note_declared_at);
10853 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010854 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010855 }
10856
10857 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010858 if (Var->getType()->isVariablyModifiedType()) {
10859 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010860 if (IsBlock)
10861 Diag(Loc, diag::err_ref_vm_type);
10862 else
10863 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10864 Diag(Var->getLocation(), diag::note_previous_decl)
10865 << Var->getDeclName();
10866 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010867 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010868 }
Fariborz Jahanianb20eb102013-01-08 23:48:48 +000010869 // Prohibit structs with flexible array members too.
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000010870 // We cannot capture what is in the tail end of the struct.
10871 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
Fariborz Jahaniane178e702013-01-09 00:09:15 +000010872 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000010873 if (BuildAndDiagnose) {
10874 if (IsBlock)
10875 Diag(Loc, diag::err_ref_flexarray_type);
Fariborz Jahaniane178e702013-01-09 00:09:15 +000010876 else
10877 Diag(Loc, diag::err_lambda_capture_flexarray_type)
10878 << Var->getDeclName();
Fariborz Jahanian9c0816f2013-01-08 23:17:51 +000010879 Diag(Var->getLocation(), diag::note_previous_decl)
10880 << Var->getDeclName();
10881 }
10882 return true;
10883 }
10884 }
Eli Friedmanb942cb22012-02-03 22:47:37 +000010885 // Lambdas are not allowed to capture __block variables; they don't
10886 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010887 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010888 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010889 Diag(Loc, diag::err_lambda_capture_block)
10890 << Var->getDeclName();
10891 Diag(Var->getLocation(), diag::note_previous_decl)
10892 << Var->getDeclName();
10893 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010894 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010895 }
10896
Douglas Gregorf8af9822012-02-12 18:42:33 +000010897 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10898 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010899 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010900 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10901 Diag(Var->getLocation(), diag::note_previous_decl)
10902 << Var->getDeclName();
10903 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10904 diag::note_lambda_decl);
10905 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010906 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010907 }
10908
10909 FunctionScopesIndex--;
10910 DC = ParentDC;
10911 Explicit = false;
10912 } while (!Var->getDeclContext()->Equals(DC));
10913
Douglas Gregor999713e2012-02-18 09:37:24 +000010914 // Walk back down the scope stack, computing the type of the capture at
10915 // each step, checking type-specific requirements, and adding captures if
10916 // requested.
10917 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10918 ++I) {
10919 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010920
Douglas Gregor999713e2012-02-18 09:37:24 +000010921 // Compute the type of the capture and of a reference to the capture within
10922 // this scope.
10923 if (isa<BlockScopeInfo>(CSI)) {
10924 Expr *CopyExpr = 0;
10925 bool ByRef = false;
10926
10927 // Blocks are not allowed to capture arrays.
10928 if (CaptureType->isArrayType()) {
10929 if (BuildAndDiagnose) {
10930 Diag(Loc, diag::err_ref_array_type);
10931 Diag(Var->getLocation(), diag::note_previous_decl)
10932 << Var->getDeclName();
10933 }
10934 return true;
10935 }
10936
John McCall100c6492012-03-30 05:23:48 +000010937 // Forbid the block-capture of autoreleasing variables.
10938 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10939 if (BuildAndDiagnose) {
10940 Diag(Loc, diag::err_arc_autoreleasing_capture)
10941 << /*block*/ 0;
10942 Diag(Var->getLocation(), diag::note_previous_decl)
10943 << Var->getDeclName();
10944 }
10945 return true;
10946 }
10947
Douglas Gregor999713e2012-02-18 09:37:24 +000010948 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10949 // Block capture by reference does not change the capture or
10950 // declaration reference types.
10951 ByRef = true;
10952 } else {
10953 // Block capture by copy introduces 'const'.
10954 CaptureType = CaptureType.getNonReferenceType().withConst();
10955 DeclRefType = CaptureType;
10956
David Blaikie4e4d0842012-03-11 07:00:24 +000010957 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010958 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10959 // The capture logic needs the destructor, so make sure we mark it.
10960 // Usually this is unnecessary because most local variables have
10961 // their destructors marked at declaration time, but parameters are
10962 // an exception because it's technically only the call site that
10963 // actually requires the destructor.
10964 if (isa<ParmVarDecl>(Var))
10965 FinalizeVarWithDestructor(Var, Record);
Douglas Gregor464a01a2012-12-01 01:01:09 +000010966
Douglas Gregor999713e2012-02-18 09:37:24 +000010967 // According to the blocks spec, the capture of a variable from
10968 // the stack requires a const copy constructor. This is not true
10969 // of the copy/move done to move a __block variable to the heap.
Douglas Gregor464a01a2012-12-01 01:01:09 +000010970 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
Douglas Gregor999713e2012-02-18 09:37:24 +000010971 DeclRefType.withConst(),
10972 VK_LValue, Loc);
Douglas Gregor464a01a2012-12-01 01:01:09 +000010973
Douglas Gregor999713e2012-02-18 09:37:24 +000010974 ExprResult Result
10975 = PerformCopyInitialization(
10976 InitializedEntity::InitializeBlock(Var->getLocation(),
10977 CaptureType, false),
10978 Loc, Owned(DeclRef));
10979
10980 // Build a full-expression copy expression if initialization
10981 // succeeded and used a non-trivial constructor. Recover from
10982 // errors by pretending that the copy isn't necessary.
10983 if (!Result.isInvalid() &&
10984 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10985 ->isTrivial()) {
10986 Result = MaybeCreateExprWithCleanups(Result);
10987 CopyExpr = Result.take();
10988 }
10989 }
10990 }
10991 }
10992
10993 // Actually capture the variable.
10994 if (BuildAndDiagnose)
10995 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10996 SourceLocation(), CaptureType, CopyExpr);
10997 Nested = true;
10998 continue;
10999 }
Douglas Gregor68932842012-02-18 05:51:20 +000011000
Douglas Gregor999713e2012-02-18 09:37:24 +000011001 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11002
11003 // Determine whether we are capturing by reference or by value.
11004 bool ByRef = false;
11005 if (I == N - 1 && Kind != TryCapture_Implicit) {
11006 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000011007 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000011008 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000011009 }
Douglas Gregor999713e2012-02-18 09:37:24 +000011010
11011 // Compute the type of the field that will capture this variable.
11012 if (ByRef) {
11013 // C++11 [expr.prim.lambda]p15:
11014 // An entity is captured by reference if it is implicitly or
11015 // explicitly captured but not captured by copy. It is
11016 // unspecified whether additional unnamed non-static data
11017 // members are declared in the closure type for entities
11018 // captured by reference.
11019 //
11020 // FIXME: It is not clear whether we want to build an lvalue reference
11021 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11022 // to do the former, while EDG does the latter. Core issue 1249 will
11023 // clarify, but for now we follow GCC because it's a more permissive and
11024 // easily defensible position.
11025 CaptureType = Context.getLValueReferenceType(DeclRefType);
11026 } else {
11027 // C++11 [expr.prim.lambda]p14:
11028 // For each entity captured by copy, an unnamed non-static
11029 // data member is declared in the closure type. The
11030 // declaration order of these members is unspecified. The type
11031 // of such a data member is the type of the corresponding
11032 // captured entity if the entity is not a reference to an
11033 // object, or the referenced type otherwise. [Note: If the
11034 // captured entity is a reference to a function, the
11035 // corresponding data member is also a reference to a
11036 // function. - end note ]
11037 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11038 if (!RefType->getPointeeType()->isFunctionType())
11039 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011040 }
John McCall100c6492012-03-30 05:23:48 +000011041
11042 // Forbid the lambda copy-capture of autoreleasing variables.
11043 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11044 if (BuildAndDiagnose) {
11045 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11046 Diag(Var->getLocation(), diag::note_previous_decl)
11047 << Var->getDeclName();
11048 }
11049 return true;
11050 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011051 }
11052
Douglas Gregor999713e2012-02-18 09:37:24 +000011053 // Capture this variable in the lambda.
11054 Expr *CopyExpr = 0;
11055 if (BuildAndDiagnose) {
11056 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000011057 DeclRefType, Loc,
Douglas Gregor464a01a2012-12-01 01:01:09 +000011058 Nested);
Douglas Gregor999713e2012-02-18 09:37:24 +000011059 if (!Result.isInvalid())
11060 CopyExpr = Result.take();
11061 }
11062
11063 // Compute the type of a reference to this captured variable.
11064 if (ByRef)
11065 DeclRefType = CaptureType.getNonReferenceType();
11066 else {
11067 // C++ [expr.prim.lambda]p5:
11068 // The closure type for a lambda-expression has a public inline
11069 // function call operator [...]. This function call operator is
11070 // declared const (9.3.1) if and only if the lambda-expression’s
11071 // parameter-declaration-clause is not followed by mutable.
11072 DeclRefType = CaptureType.getNonReferenceType();
11073 if (!LSI->Mutable && !CaptureType->isReferenceType())
11074 DeclRefType.addConst();
11075 }
11076
11077 // Add the capture.
11078 if (BuildAndDiagnose)
11079 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11080 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011081 Nested = true;
11082 }
Douglas Gregor999713e2012-02-18 09:37:24 +000011083
11084 return false;
11085}
11086
11087bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11088 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11089 QualType CaptureType;
11090 QualType DeclRefType;
11091 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11092 /*BuildAndDiagnose=*/true, CaptureType,
11093 DeclRefType);
11094}
11095
11096QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11097 QualType CaptureType;
11098 QualType DeclRefType;
11099
11100 // Determine whether we can capture this variable.
11101 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11102 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11103 return QualType();
11104
11105 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011106}
11107
Eli Friedmand2cce132012-02-02 23:15:15 +000011108static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11109 SourceLocation Loc) {
11110 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000011111 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011112 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000011113 Var->getLinkage() != ExternalLinkage &&
11114 !(Var->isStaticDataMember() && Var->hasInit())) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +000011115 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
Eli Friedmand2cce132012-02-02 23:15:15 +000011116 if (old.isInvalid()) old = Loc;
11117 }
11118
Douglas Gregor999713e2012-02-18 09:37:24 +000011119 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000011120
Eli Friedmand2cce132012-02-02 23:15:15 +000011121 Var->setUsed(true);
11122}
11123
11124void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11125 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11126 // an object that satisfies the requirements for appearing in a
11127 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11128 // is immediately applied." This function handles the lvalue-to-rvalue
11129 // conversion part.
11130 MaybeODRUseExprs.erase(E->IgnoreParens());
11131}
11132
Eli Friedmanac626012012-02-29 03:16:56 +000011133ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11134 if (!Res.isUsable())
11135 return Res;
11136
11137 // If a constant-expression is a reference to a variable where we delay
11138 // deciding whether it is an odr-use, just assume we will apply the
11139 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
11140 // (a non-type template argument), we have special handling anyway.
11141 UpdateMarkingForLValueToRValue(Res.get());
11142 return Res;
11143}
11144
Eli Friedmand2cce132012-02-02 23:15:15 +000011145void Sema::CleanupVarDeclMarking() {
11146 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11147 e = MaybeODRUseExprs.end();
11148 i != e; ++i) {
11149 VarDecl *Var;
11150 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000011151 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011152 Var = cast<VarDecl>(DRE->getDecl());
11153 Loc = DRE->getLocation();
11154 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11155 Var = cast<VarDecl>(ME->getMemberDecl());
11156 Loc = ME->getMemberLoc();
11157 } else {
11158 llvm_unreachable("Unexpcted expression");
11159 }
11160
11161 MarkVarDeclODRUsed(*this, Var, Loc);
11162 }
11163
11164 MaybeODRUseExprs.clear();
11165}
11166
11167// Mark a VarDecl referenced, and perform the necessary handling to compute
11168// odr-uses.
11169static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11170 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011171 Var->setReferenced();
11172
Eli Friedmand2cce132012-02-02 23:15:15 +000011173 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011174 return;
11175
11176 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000011177 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011178 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11179 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000011180 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11181 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011182 (!AlreadyInstantiated ||
11183 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000011184 if (!AlreadyInstantiated) {
11185 // This is a modification of an existing AST node. Notify listeners.
11186 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11187 L->StaticDataMemberInstantiated(Var);
11188 MSInfo->setPointOfInstantiation(Loc);
11189 }
11190 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011191 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011192 // Do not defer instantiations of variables which could be used in a
11193 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000011194 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011195 else
Richard Smith37ce0102012-02-15 02:42:50 +000011196 SemaRef.PendingInstantiations.push_back(
11197 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000011198 }
11199 }
11200
Richard Smith5016a702012-10-20 01:38:33 +000011201 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11202 // the requirements for appearing in a constant expression (5.19) and, if
11203 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedmand2cce132012-02-02 23:15:15 +000011204 // is immediately applied." We check the first part here, and
11205 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11206 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5016a702012-10-20 01:38:33 +000011207 // C++03 depends on whether we get the C++03 version correct. The second
11208 // part does not apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000011209 const VarDecl *DefVD;
Richard Smith5016a702012-10-20 01:38:33 +000011210 if (E && !isa<ParmVarDecl>(Var) &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011211 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Richard Smith5016a702012-10-20 01:38:33 +000011212 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11213 if (!Var->getType()->isReferenceType())
11214 SemaRef.MaybeODRUseExprs.insert(E);
11215 } else
Eli Friedmand2cce132012-02-02 23:15:15 +000011216 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11217}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011218
Eli Friedmand2cce132012-02-02 23:15:15 +000011219/// \brief Mark a variable referenced, and check whether it is odr-used
11220/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11221/// used directly for normal expressions referring to VarDecl.
11222void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11223 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011224}
11225
11226static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011227 Decl *D, Expr *E, bool OdrUse) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011228 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11229 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11230 return;
11231 }
11232
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011233 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011234
11235 // If this is a call to a method via a cast, also mark the method in the
11236 // derived class used in case codegen can devirtualize the call.
11237 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11238 if (!ME)
11239 return;
11240 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11241 if (!MD)
11242 return;
11243 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000011244 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011245 if (!MostDerivedClassDecl)
11246 return;
11247 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Nick Lewyckyd3b4f0e2013-02-14 00:55:17 +000011248 if (!DM || DM->isPure())
Rafael Espindola0713d992012-06-27 17:44:39 +000011249 return;
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011250 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011251}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011252
Eli Friedman5f2987c2012-02-02 03:46:19 +000011253/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11254void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011255 // TODO: update this with DR# once a defect report is filed.
11256 // C++11 defect. The address of a pure member should not be an ODR use, even
11257 // if it's a qualified reference.
11258 bool OdrUse = true;
11259 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
Nick Lewycky7cea1482013-02-05 06:20:31 +000011260 if (Method->isVirtual())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011261 OdrUse = false;
11262 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011263}
11264
11265/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11266void Sema::MarkMemberReferenced(MemberExpr *E) {
Nick Lewycky869709c2013-01-31 03:15:20 +000011267 // C++11 [basic.def.odr]p2:
Nick Lewycky4ceaf332013-01-31 01:34:31 +000011268 // A non-overloaded function whose name appears as a potentially-evaluated
11269 // expression or a member of a set of candidate functions, if selected by
11270 // overload resolution when referred to from a potentially-evaluated
11271 // expression, is odr-used, unless it is a pure virtual function and its
11272 // name is not explicitly qualified.
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011273 bool OdrUse = true;
Nick Lewycky4ceaf332013-01-31 01:34:31 +000011274 if (!E->hasQualifier()) {
11275 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11276 if (Method->isPure())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011277 OdrUse = false;
Nick Lewycky4ceaf332013-01-31 01:34:31 +000011278 }
Nick Lewycky3c86a5c2013-02-12 08:08:54 +000011279 SourceLocation Loc = E->getMemberLoc().isValid() ?
11280 E->getMemberLoc() : E->getLocStart();
11281 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011282}
11283
Douglas Gregor73d90922012-02-10 09:26:04 +000011284/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000011285/// marks the declaration referenced, and performs odr-use checking for functions
11286/// and variables. This method should not be used when building an normal
11287/// expression which refers to a variable.
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011288void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11289 if (OdrUse) {
11290 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11291 MarkVariableReferenced(Loc, VD);
11292 return;
11293 }
11294 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11295 MarkFunctionReferenced(Loc, FD);
11296 return;
11297 }
11298 }
11299 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000011300}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011301
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011302namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011303 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011304 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011305 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011306 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11307 Sema &S;
11308 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011309
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011310 public:
11311 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011312
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011313 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011314
11315 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11316 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011317 };
11318}
11319
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011320bool MarkReferencedDecls::TraverseTemplateArgument(
11321 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011322 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011323 if (Decl *D = Arg.getAsDecl())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000011324 S.MarkAnyDeclReferenced(Loc, D, true);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011325 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011326
11327 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011328}
11329
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011330bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011331 if (ClassTemplateSpecializationDecl *Spec
11332 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11333 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011334 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011335 }
11336
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011337 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011338}
11339
11340void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11341 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011342 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011343}
11344
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011345namespace {
11346 /// \brief Helper class that marks all of the declarations referenced by
11347 /// potentially-evaluated subexpressions as "referenced".
11348 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11349 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011350 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011351
11352 public:
11353 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11354
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011355 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11356 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011357
11358 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011359 // If we were asked not to visit local variables, don't.
11360 if (SkipLocalVariables) {
11361 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11362 if (VD->hasLocalStorage())
11363 return;
11364 }
11365
Eli Friedman5f2987c2012-02-02 03:46:19 +000011366 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011367 }
11368
11369 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011370 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011371 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011372 }
11373
John McCall80ee6e82011-11-10 05:35:25 +000011374 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011375 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011376 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11377 Visit(E->getSubExpr());
11378 }
11379
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011380 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011381 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011382 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011383 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011384 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011385 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011386 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011387
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011388 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11389 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011390 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011391 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11392 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11393 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011394 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011395 S.LookupDestructor(Record));
11396 }
11397
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011398 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011399 }
11400
11401 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011402 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011403 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011404 }
11405
Douglas Gregor102ff972010-10-19 17:17:35 +000011406 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11407 Visit(E->getExpr());
11408 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011409
11410 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11411 Inherited::VisitImplicitCastExpr(E);
11412
11413 if (E->getCastKind() == CK_LValueToRValue)
11414 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11415 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011416 };
11417}
11418
11419/// \brief Mark any declarations that appear within this expression or any
11420/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011421///
11422/// \param SkipLocalVariables If true, don't mark local variables as
11423/// 'referenced'.
11424void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11425 bool SkipLocalVariables) {
11426 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011427}
11428
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011429/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11430/// of the program being compiled.
11431///
11432/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011433/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011434/// possibility that the code will actually be executable. Code in sizeof()
11435/// expressions, code used only during overload resolution, etc., are not
11436/// potentially evaluated. This routine will suppress such diagnostics or,
11437/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011438/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011439/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011440///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011441/// This routine should be used for all diagnostics that describe the run-time
11442/// behavior of a program, such as passing a non-POD value through an ellipsis.
11443/// Failure to do so will likely result in spurious diagnostics or failures
11444/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011445bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011446 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011447 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011448 case Unevaluated:
11449 // The argument will never be evaluated, so don't complain.
11450 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011451
Richard Smithf6702a32011-12-20 02:08:33 +000011452 case ConstantEvaluated:
11453 // Relevant diagnostics should be produced by constant evaluation.
11454 break;
11455
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011456 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011457 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011458 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011459 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011460 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011461 }
11462 else
11463 Diag(Loc, PD);
11464
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011465 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011466 }
11467
11468 return false;
11469}
11470
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011471bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11472 CallExpr *CE, FunctionDecl *FD) {
11473 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11474 return false;
11475
Richard Smith76f3f692012-02-22 02:04:18 +000011476 // If we're inside a decltype's expression, don't check for a valid return
11477 // type or construct temporaries until we know whether this is the last call.
11478 if (ExprEvalContexts.back().IsDecltype) {
11479 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11480 return false;
11481 }
11482
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011483 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011484 FunctionDecl *FD;
11485 CallExpr *CE;
11486
11487 public:
11488 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11489 : FD(FD), CE(CE) { }
11490
11491 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11492 if (!FD) {
11493 S.Diag(Loc, diag::err_call_incomplete_return)
11494 << T << CE->getSourceRange();
11495 return;
11496 }
11497
11498 S.Diag(Loc, diag::err_call_function_incomplete_return)
11499 << CE->getSourceRange() << FD->getDeclName() << T;
11500 S.Diag(FD->getLocation(),
11501 diag::note_function_with_incomplete_return_type_declared_here)
11502 << FD->getDeclName();
11503 }
11504 } Diagnoser(FD, CE);
11505
11506 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011507 return true;
11508
11509 return false;
11510}
11511
Douglas Gregor92c3a042011-01-19 16:50:08 +000011512// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011513// will prevent this condition from triggering, which is what we want.
11514void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11515 SourceLocation Loc;
11516
John McCalla52ef082009-11-11 02:41:58 +000011517 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011518 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011519
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011520 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011521 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011522 return;
11523
Douglas Gregor92c3a042011-01-19 16:50:08 +000011524 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11525
John McCallc8d8ac52009-11-12 00:06:05 +000011526 // Greylist some idioms by putting them into a warning subcategory.
11527 if (ObjCMessageExpr *ME
11528 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11529 Selector Sel = ME->getSelector();
11530
John McCallc8d8ac52009-11-12 00:06:05 +000011531 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011532 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011533 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11534
11535 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011536 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011537 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11538 }
John McCalla52ef082009-11-11 02:41:58 +000011539
John McCall5a881bb2009-10-12 21:59:07 +000011540 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011541 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011542 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011543 return;
11544
Douglas Gregor92c3a042011-01-19 16:50:08 +000011545 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011546 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011547 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11548 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11549 else {
John McCall5a881bb2009-10-12 21:59:07 +000011550 // Not an assignment.
11551 return;
11552 }
11553
Douglas Gregor55b38842010-04-14 16:09:52 +000011554 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011555
Daniel Dunbar96a00142012-03-09 18:35:03 +000011556 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011557 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11558 Diag(Loc, diag::note_condition_assign_silence)
11559 << FixItHint::CreateInsertion(Open, "(")
11560 << FixItHint::CreateInsertion(Close, ")");
11561
Douglas Gregor92c3a042011-01-19 16:50:08 +000011562 if (IsOrAssign)
11563 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11564 << FixItHint::CreateReplacement(Loc, "!=");
11565 else
11566 Diag(Loc, diag::note_condition_assign_to_comparison)
11567 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011568}
11569
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011570/// \brief Redundant parentheses over an equality comparison can indicate
11571/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011572void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011573 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011574 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011575 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11576 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011577 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011578 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011579 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011580
Richard Trieuccd891a2011-09-09 01:45:06 +000011581 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011582
11583 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011584 if (opE->getOpcode() == BO_EQ &&
11585 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11586 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011587 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011588
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011589 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011590 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011591 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011592 << FixItHint::CreateRemoval(ParenERange.getBegin())
11593 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011594 Diag(Loc, diag::note_equality_comparison_to_assign)
11595 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011596 }
11597}
11598
John Wiegley429bb272011-04-08 18:41:53 +000011599ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011600 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011601 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11602 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011603
John McCall864c0412011-04-26 20:42:42 +000011604 ExprResult result = CheckPlaceholderExpr(E);
11605 if (result.isInvalid()) return ExprError();
11606 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011607
John McCall864c0412011-04-26 20:42:42 +000011608 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011609 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011610 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11611
John Wiegley429bb272011-04-08 18:41:53 +000011612 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11613 if (ERes.isInvalid())
11614 return ExprError();
11615 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011616
11617 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011618 if (!T->isScalarType()) { // C99 6.8.4.1p1
11619 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11620 << T << E->getSourceRange();
11621 return ExprError();
11622 }
John McCall5a881bb2009-10-12 21:59:07 +000011623 }
11624
John Wiegley429bb272011-04-08 18:41:53 +000011625 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011626}
Douglas Gregor586596f2010-05-06 17:25:47 +000011627
John McCall60d7b3a2010-08-24 06:29:42 +000011628ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011629 Expr *SubExpr) {
11630 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011631 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011632
Richard Trieuccd891a2011-09-09 01:45:06 +000011633 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011634}
John McCall2a984ca2010-10-12 00:20:44 +000011635
John McCall1de4d4e2011-04-07 08:22:57 +000011636namespace {
John McCall755d8492011-04-12 00:42:48 +000011637 /// A visitor for rebuilding a call to an __unknown_any expression
11638 /// to have an appropriate type.
11639 struct RebuildUnknownAnyFunction
11640 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11641
11642 Sema &S;
11643
11644 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11645
11646 ExprResult VisitStmt(Stmt *S) {
11647 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011648 }
11649
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011650 ExprResult VisitExpr(Expr *E) {
11651 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11652 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011653 return ExprError();
11654 }
11655
11656 /// Rebuild an expression which simply semantically wraps another
11657 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011658 template <class T> ExprResult rebuildSugarExpr(T *E) {
11659 ExprResult SubResult = Visit(E->getSubExpr());
11660 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011661
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011662 Expr *SubExpr = SubResult.take();
11663 E->setSubExpr(SubExpr);
11664 E->setType(SubExpr->getType());
11665 E->setValueKind(SubExpr->getValueKind());
11666 assert(E->getObjectKind() == OK_Ordinary);
11667 return E;
John McCall755d8492011-04-12 00:42:48 +000011668 }
11669
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011670 ExprResult VisitParenExpr(ParenExpr *E) {
11671 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011672 }
11673
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011674 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11675 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011676 }
11677
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011678 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11679 ExprResult SubResult = Visit(E->getSubExpr());
11680 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011681
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011682 Expr *SubExpr = SubResult.take();
11683 E->setSubExpr(SubExpr);
11684 E->setType(S.Context.getPointerType(SubExpr->getType()));
11685 assert(E->getValueKind() == VK_RValue);
11686 assert(E->getObjectKind() == OK_Ordinary);
11687 return E;
John McCall755d8492011-04-12 00:42:48 +000011688 }
11689
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011690 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11691 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011692
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011693 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011694
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011695 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011696 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011697 !(isa<CXXMethodDecl>(VD) &&
11698 cast<CXXMethodDecl>(VD)->isInstance()))
11699 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011700
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011701 return E;
John McCall755d8492011-04-12 00:42:48 +000011702 }
11703
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011704 ExprResult VisitMemberExpr(MemberExpr *E) {
11705 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011706 }
11707
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011708 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11709 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011710 }
11711 };
11712}
11713
11714/// Given a function expression of unknown-any type, try to rebuild it
11715/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011716static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11717 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11718 if (Result.isInvalid()) return ExprError();
11719 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011720}
11721
11722namespace {
John McCall379b5152011-04-11 07:02:50 +000011723 /// A visitor for rebuilding an expression of type __unknown_anytype
11724 /// into one which resolves the type directly on the referring
11725 /// expression. Strict preservation of the original source
11726 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011727 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011728 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011729
11730 Sema &S;
11731
11732 /// The current destination type.
11733 QualType DestType;
11734
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011735 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11736 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011737
John McCalla5fc4722011-04-09 22:50:59 +000011738 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011739 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011740 }
11741
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011742 ExprResult VisitExpr(Expr *E) {
11743 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11744 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011745 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011746 }
11747
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011748 ExprResult VisitCallExpr(CallExpr *E);
11749 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011750
John McCalla5fc4722011-04-09 22:50:59 +000011751 /// Rebuild an expression which simply semantically wraps another
11752 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011753 template <class T> ExprResult rebuildSugarExpr(T *E) {
11754 ExprResult SubResult = Visit(E->getSubExpr());
11755 if (SubResult.isInvalid()) return ExprError();
11756 Expr *SubExpr = SubResult.take();
11757 E->setSubExpr(SubExpr);
11758 E->setType(SubExpr->getType());
11759 E->setValueKind(SubExpr->getValueKind());
11760 assert(E->getObjectKind() == OK_Ordinary);
11761 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011762 }
John McCall1de4d4e2011-04-07 08:22:57 +000011763
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011764 ExprResult VisitParenExpr(ParenExpr *E) {
11765 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011766 }
11767
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011768 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11769 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011770 }
11771
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011772 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11773 const PointerType *Ptr = DestType->getAs<PointerType>();
11774 if (!Ptr) {
11775 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11776 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011777 return ExprError();
11778 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011779 assert(E->getValueKind() == VK_RValue);
11780 assert(E->getObjectKind() == OK_Ordinary);
11781 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011782
11783 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011784 DestType = Ptr->getPointeeType();
11785 ExprResult SubResult = Visit(E->getSubExpr());
11786 if (SubResult.isInvalid()) return ExprError();
11787 E->setSubExpr(SubResult.take());
11788 return E;
John McCall755d8492011-04-12 00:42:48 +000011789 }
11790
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011791 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011792
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011793 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011794
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011795 ExprResult VisitMemberExpr(MemberExpr *E) {
11796 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011797 }
John McCalla5fc4722011-04-09 22:50:59 +000011798
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011799 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11800 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011801 }
11802 };
11803}
11804
John McCall379b5152011-04-11 07:02:50 +000011805/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011806ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11807 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011808
11809 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011810 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011811 FK_FunctionPointer,
11812 FK_BlockPointer
11813 };
11814
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011815 FnKind Kind;
11816 QualType CalleeType = CalleeExpr->getType();
11817 if (CalleeType == S.Context.BoundMemberTy) {
11818 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11819 Kind = FK_MemberFunction;
11820 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11821 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11822 CalleeType = Ptr->getPointeeType();
11823 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011824 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011825 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11826 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011827 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011828 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011829
11830 // Verify that this is a legal result type of a function.
11831 if (DestType->isArrayType() || DestType->isFunctionType()) {
11832 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011833 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011834 diagID = diag::err_block_returning_array_function;
11835
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011836 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011837 << DestType->isFunctionType() << DestType;
11838 return ExprError();
11839 }
11840
11841 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011842 E->setType(DestType.getNonLValueExprType(S.Context));
11843 E->setValueKind(Expr::getValueKindForType(DestType));
11844 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011845
11846 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011847 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011848 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011849 Proto->arg_type_begin(),
11850 Proto->getNumArgs(),
11851 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011852 else
11853 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011854 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011855
11856 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011857 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011858 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011859 // Nothing to do.
11860 break;
11861
11862 case FK_FunctionPointer:
11863 DestType = S.Context.getPointerType(DestType);
11864 break;
11865
11866 case FK_BlockPointer:
11867 DestType = S.Context.getBlockPointerType(DestType);
11868 break;
11869 }
11870
11871 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011872 ExprResult CalleeResult = Visit(CalleeExpr);
11873 if (!CalleeResult.isUsable()) return ExprError();
11874 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011875
11876 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011877 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011878}
11879
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011880ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011881 // Verify that this is a legal result type of a call.
11882 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011883 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011884 << DestType->isFunctionType() << DestType;
11885 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011886 }
11887
John McCall48218c62011-07-13 17:56:40 +000011888 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011889 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11890 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11891 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011892 }
John McCall755d8492011-04-12 00:42:48 +000011893
John McCall379b5152011-04-11 07:02:50 +000011894 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011895 E->setType(DestType.getNonReferenceType());
11896 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011897
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011898 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011899}
11900
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011901ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011902 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011903 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011904 assert(E->getValueKind() == VK_RValue);
11905 assert(E->getObjectKind() == OK_Ordinary);
11906
11907 E->setType(DestType);
11908
11909 // Rebuild the sub-expression as the pointee (function) type.
11910 DestType = DestType->castAs<PointerType>()->getPointeeType();
11911
11912 ExprResult Result = Visit(E->getSubExpr());
11913 if (!Result.isUsable()) return ExprError();
11914
11915 E->setSubExpr(Result.take());
11916 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011917 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011918 assert(E->getValueKind() == VK_RValue);
11919 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011920
Sean Callanance9c8312012-03-06 21:34:12 +000011921 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011922
Sean Callanance9c8312012-03-06 21:34:12 +000011923 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011924
Sean Callanance9c8312012-03-06 21:34:12 +000011925 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11926 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011927
Sean Callanance9c8312012-03-06 21:34:12 +000011928 ExprResult Result = Visit(E->getSubExpr());
11929 if (!Result.isUsable()) return ExprError();
11930
11931 E->setSubExpr(Result.take());
11932 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011933 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011934 llvm_unreachable("Unhandled cast type!");
11935 }
John McCall379b5152011-04-11 07:02:50 +000011936}
11937
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011938ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11939 ExprValueKind ValueKind = VK_LValue;
11940 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011941
11942 // We know how to make this work for certain kinds of decls:
11943
11944 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011945 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11946 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11947 DestType = Ptr->getPointeeType();
11948 ExprResult Result = resolveDecl(E, VD);
11949 if (Result.isInvalid()) return ExprError();
11950 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011951 CK_FunctionToPointerDecay, VK_RValue);
11952 }
11953
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011954 if (!Type->isFunctionType()) {
11955 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11956 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011957 return ExprError();
11958 }
John McCall379b5152011-04-11 07:02:50 +000011959
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011960 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11961 if (MD->isInstance()) {
11962 ValueKind = VK_RValue;
11963 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011964 }
11965
John McCall379b5152011-04-11 07:02:50 +000011966 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011967 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011968 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011969
11970 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011971 } else if (isa<VarDecl>(VD)) {
11972 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11973 Type = RefTy->getPointeeType();
11974 } else if (Type->isFunctionType()) {
11975 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11976 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011977 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011978 }
11979
11980 // - nothing else
11981 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011982 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11983 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011984 return ExprError();
11985 }
11986
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011987 VD->setType(DestType);
11988 E->setType(Type);
11989 E->setValueKind(ValueKind);
11990 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011991}
11992
John McCall1de4d4e2011-04-07 08:22:57 +000011993/// Check a cast of an unknown-any type. We intentionally only
11994/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011995ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11996 Expr *CastExpr, CastKind &CastKind,
11997 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011998 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011999 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000012000 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000012001
Richard Trieuccd891a2011-09-09 01:45:06 +000012002 CastExpr = result.take();
12003 VK = CastExpr->getValueKind();
12004 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000012005
Richard Trieuccd891a2011-09-09 01:45:06 +000012006 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000012007}
12008
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000012009ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12010 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12011}
12012
John McCall48f90422013-03-04 07:34:02 +000012013ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12014 Expr *arg, QualType &paramType) {
12015 // If the syntactic form of the argument is not an explicit cast of
12016 // any sort, just do default argument promotion.
12017 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12018 if (!castArg) {
12019 ExprResult result = DefaultArgumentPromotion(arg);
12020 if (result.isInvalid()) return ExprError();
12021 paramType = result.get()->getType();
12022 return result;
John McCallb8a8de32012-11-14 00:49:39 +000012023 }
12024
John McCall48f90422013-03-04 07:34:02 +000012025 // Otherwise, use the type that was written in the explicit cast.
12026 assert(!arg->hasPlaceholderType());
12027 paramType = castArg->getTypeAsWritten();
12028
12029 // Copy-initialize a parameter of that type.
12030 InitializedEntity entity =
12031 InitializedEntity::InitializeParameter(Context, paramType,
12032 /*consumed*/ false);
12033 return PerformCopyInitialization(entity, callLoc, Owned(arg));
John McCallb8a8de32012-11-14 00:49:39 +000012034}
12035
Richard Trieuccd891a2011-09-09 01:45:06 +000012036static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12037 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000012038 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000012039 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000012040 E = E->IgnoreParenImpCasts();
12041 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12042 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000012043 diagID = diag::err_uncasted_call_of_unknown_any;
12044 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000012045 break;
John McCall379b5152011-04-11 07:02:50 +000012046 }
John McCall1de4d4e2011-04-07 08:22:57 +000012047 }
12048
John McCall379b5152011-04-11 07:02:50 +000012049 SourceLocation loc;
12050 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000012051 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000012052 loc = ref->getLocation();
12053 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000012054 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000012055 loc = mem->getMemberLoc();
12056 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000012057 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000012058 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000012059 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000012060 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000012061 if (!d) {
12062 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12063 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12064 << orig->getSourceRange();
12065 return ExprError();
12066 }
John McCall379b5152011-04-11 07:02:50 +000012067 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000012068 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12069 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000012070 return ExprError();
12071 }
12072
12073 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000012074
12075 // Never recoverable.
12076 return ExprError();
12077}
12078
John McCall2a984ca2010-10-12 00:20:44 +000012079/// Check for operands with placeholder types and complain if found.
12080/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000012081ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000012082 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12083 if (!placeholderType) return Owned(E);
12084
12085 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000012086
John McCall1de4d4e2011-04-07 08:22:57 +000012087 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000012088 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000012089 // Try to resolve a single function template specialization.
12090 // This is obligatory.
12091 ExprResult result = Owned(E);
12092 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12093 return result;
12094
12095 // If that failed, try to recover with a call.
12096 } else {
12097 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12098 /*complain*/ true);
12099 return result;
12100 }
12101 }
John McCall1de4d4e2011-04-07 08:22:57 +000012102
John McCall864c0412011-04-26 20:42:42 +000012103 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000012104 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000012105 ExprResult result = Owned(E);
12106 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12107 /*complain*/ true);
12108 return result;
John McCall5acb0c92011-10-17 18:40:02 +000012109 }
12110
12111 // ARC unbridged casts.
12112 case BuiltinType::ARCUnbridgedCast: {
12113 Expr *realCast = stripARCUnbridgedCast(E);
12114 diagnoseARCUnbridgedCast(realCast);
12115 return Owned(realCast);
12116 }
John McCall864c0412011-04-26 20:42:42 +000012117
John McCall1de4d4e2011-04-07 08:22:57 +000012118 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000012119 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000012120 return diagnoseUnknownAnyExpr(*this, E);
12121
John McCall3c3b7f92011-10-25 17:37:35 +000012122 // Pseudo-objects.
12123 case BuiltinType::PseudoObject:
12124 return checkPseudoObjectRValue(E);
12125
Eli Friedmana6c66ce2012-08-31 00:14:07 +000012126 case BuiltinType::BuiltinFn:
12127 Diag(E->getLocStart(), diag::err_builtin_fn_use);
12128 return ExprError();
12129
John McCalle0a22d02011-10-18 21:02:43 +000012130 // Everything else should be impossible.
12131#define BUILTIN_TYPE(Id, SingletonId) \
12132 case BuiltinType::Id:
12133#define PLACEHOLDER_TYPE(Id, SingletonId)
12134#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000012135 break;
12136 }
12137
12138 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000012139}
Richard Trieubb9b80c2011-04-21 21:44:26 +000012140
Richard Trieuccd891a2011-09-09 01:45:06 +000012141bool Sema::CheckCaseExpression(Expr *E) {
12142 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000012143 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000012144 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12145 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000012146 return false;
12147}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012148
12149/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12150ExprResult
12151Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12152 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12153 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000012154 QualType BoolT = Context.ObjCBuiltinBoolTy;
12155 if (!Context.getBOOLDecl()) {
Fariborz Jahanian1c9a2da2012-10-16 17:08:11 +000012156 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanian96171302012-08-30 18:49:41 +000012157 Sema::LookupOrdinaryName);
Fariborz Jahanian9f5933a2012-10-16 16:21:20 +000012158 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanian96171302012-08-30 18:49:41 +000012159 NamedDecl *ND = Result.getFoundDecl();
12160 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12161 Context.setBOOLDecl(TD);
12162 }
12163 }
12164 if (Context.getBOOLDecl())
12165 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012166 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000012167 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000012168}