blob: dcb3736bd7b5bf5243d227d5cfb188ccdc94719a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedmanef331b72012-01-20 01:26:23 +000044#include "TreeTransform.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000046using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Sebastian Redl14b0c192011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redl14b0c192011-09-24 17:48:00 +000066 return true;
67}
David Chisnall0f436562009-08-17 16:35:33 +000068
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000069static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000072 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000073 if (!DC->hasAttr<UnusedAttr>())
74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75 }
76}
77
Ted Kremenekd6cf9122012-02-10 02:45:47 +000078static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000079 NamedDecl *D, SourceLocation Loc,
80 const ObjCInterfaceDecl *UnknownObjCClass) {
81 // See if this declaration is unavailable or deprecated.
82 std::string Message;
83 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000084 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85 if (Result == AR_Available) {
86 const DeclContext *DC = ECD->getDeclContext();
87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88 Result = TheEnumDecl->getAvailability(&Message);
89 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +000090 const ObjCPropertyDecl *ObjCPDecl = 0;
91 if (Result == AR_Deprecated || Result == AR_Unavailable)
92 if (ObjCPropertyDecl *ND = S.PropertyIfSetterOrGetter(D)) {
93 AvailabilityResult PDeclResult = ND->getAvailability(0);
94 if (PDeclResult == Result)
95 ObjCPDecl = ND;
96 }
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000097
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000098 switch (Result) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000104 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000105 break;
106
107 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000108 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000109 if (Message.empty()) {
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000110 if (!UnknownObjCClass) {
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000111 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000112 if (ObjCPDecl)
113 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
114 << ObjCPDecl->getDeclName() << 1;
115 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000116 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000117 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000118 << D->getDeclName();
119 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000120 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000121 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000122 << D->getDeclName() << Message;
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000123 S.Diag(D->getLocation(), diag::note_unavailable_here)
124 << isa<FunctionDecl>(D) << false;
125 if (ObjCPDecl)
126 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
127 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000128 }
129 break;
130 }
131 return Result;
132}
133
Richard Smith6c4c36c2012-03-30 20:53:28 +0000134/// \brief Emit a note explaining that this function is deleted or unavailable.
135void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
136 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
137
Richard Smith5bdaac52012-04-02 20:59:25 +0000138 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
139 // If the method was explicitly defaulted, point at that declaration.
140 if (!Method->isImplicit())
141 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
142
143 // Try to diagnose why this special member function was implicitly
144 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000145 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000146 if (CSM != CXXInvalid)
147 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
148
149 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000150 }
151
152 Diag(Decl->getLocation(), diag::note_unavailable_here)
153 << 1 << Decl->isDeleted();
154}
155
Jordan Rose0eb3f452012-06-18 22:09:19 +0000156/// \brief Determine whether a FunctionDecl was ever declared with an
157/// explicit storage class.
158static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
159 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
160 E = D->redecls_end();
161 I != E; ++I) {
162 if (I->getStorageClassAsWritten() != SC_None)
163 return true;
164 }
165 return false;
166}
167
168/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000169/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000170///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000171/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000172/// in many cases it will not behave correctly. This is not enabled in C++ mode
173/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
174/// and so while there may still be user mistakes, most of the time we can't
175/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000176static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
177 const NamedDecl *D,
178 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000179 // This is disabled under C++; there are too many ways for this to fire in
180 // contexts where the warning is a false positive, or where it is technically
181 // correct but benign.
182 if (S.getLangOpts().CPlusPlus)
183 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000184
185 // Check if this is an inlined function or method.
186 FunctionDecl *Current = S.getCurFunctionDecl();
187 if (!Current)
188 return;
189 if (!Current->isInlined())
190 return;
191 if (Current->getLinkage() != ExternalLinkage)
192 return;
193
194 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000195 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000196 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000197
Jordan Rose05233272012-06-21 05:54:50 +0000198 // Downgrade from ExtWarn to Extension if
199 // (1) the supposedly external inline function is in the main file,
200 // and probably won't be included anywhere else.
201 // (2) the thing we're referencing is a pure function.
202 // (3) the thing we're referencing is another inline function.
203 // This last can give us false negatives, but it's better than warning on
204 // wrappers for simple C library functions.
205 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
206 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
207 if (!DowngradeWarning && UsedFn)
208 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
209
210 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
211 : diag::warn_internal_in_extern_inline)
212 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000213
214 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000215 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000216 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
217 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
218 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
219 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
220 }
221
222 S.Diag(D->getCanonicalDecl()->getLocation(),
223 diag::note_internal_decl_declared_here)
224 << D;
225}
226
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000227/// \brief Determine whether the use of this declaration is valid, and
228/// emit any corresponding diagnostics.
229///
230/// This routine diagnoses various problems with referencing
231/// declarations that can occur when using a declaration. For example,
232/// it might warn if a deprecated or unavailable declaration is being
233/// used, or produce an error (and return true) if a C++0x deleted
234/// function is being used.
235///
236/// \returns true if there was an error (this declaration cannot be
237/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000238///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000239bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000240 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000241 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000242 // If there were any diagnostics suppressed by template argument deduction,
243 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000244 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000245 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
246 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000247 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000248 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
249 Diag(Suppressed[I].first, Suppressed[I].second);
250
251 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000252 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000253 // entry from the table, because we want to avoid ever emitting these
254 // diagnostics again.
255 Suppressed.clear();
256 }
257 }
258
Richard Smith34b41d92011-02-20 03:19:35 +0000259 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000260 if (ParsingInitForAutoVars.count(D)) {
261 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
262 << D->getDeclName();
263 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000264 }
265
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000266 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000268 if (FD->isDeleted()) {
269 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000270 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000271 return true;
272 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000273 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000274 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000275
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000276 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000277
Jordan Rose0eb3f452012-06-18 22:09:19 +0000278 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000279
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000280 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000281}
282
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000283/// \brief Retrieve the message suffix that should be added to a
284/// diagnostic complaining about the given function being deleted or
285/// unavailable.
286std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
287 // FIXME: C++0x implicitly-deleted special member functions could be
288 // detected here so that we could improve diagnostics to say, e.g.,
289 // "base class 'A' had a deleted copy constructor".
290 if (FD->isDeleted())
291 return std::string();
292
293 std::string Message;
294 if (FD->getAvailability(&Message))
295 return ": " + Message;
296
297 return std::string();
298}
299
John McCall3323fad2011-09-09 07:56:05 +0000300/// DiagnoseSentinelCalls - This routine checks whether a call or
301/// message-send is to a declaration with the sentinel attribute, and
302/// if so, it checks that the requirements of the sentinel are
303/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000304void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000305 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000306 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000307 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000308 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000309
John McCall3323fad2011-09-09 07:56:05 +0000310 // The number of formal parameters of the declaration.
311 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000312
John McCall3323fad2011-09-09 07:56:05 +0000313 // The kind of declaration. This is also an index into a %select in
314 // the diagnostic.
315 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
316
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000317 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000318 numFormalParams = MD->param_size();
319 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000320 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000321 numFormalParams = FD->param_size();
322 calleeType = CT_Function;
323 } else if (isa<VarDecl>(D)) {
324 QualType type = cast<ValueDecl>(D)->getType();
325 const FunctionType *fn = 0;
326 if (const PointerType *ptr = type->getAs<PointerType>()) {
327 fn = ptr->getPointeeType()->getAs<FunctionType>();
328 if (!fn) return;
329 calleeType = CT_Function;
330 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
331 fn = ptr->getPointeeType()->castAs<FunctionType>();
332 calleeType = CT_Block;
333 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000334 return;
John McCall3323fad2011-09-09 07:56:05 +0000335 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000336
John McCall3323fad2011-09-09 07:56:05 +0000337 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
338 numFormalParams = proto->getNumArgs();
339 } else {
340 numFormalParams = 0;
341 }
342 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000343 return;
344 }
John McCall3323fad2011-09-09 07:56:05 +0000345
346 // "nullPos" is the number of formal parameters at the end which
347 // effectively count as part of the variadic arguments. This is
348 // useful if you would prefer to not have *any* formal parameters,
349 // but the language forces you to have at least one.
350 unsigned nullPos = attr->getNullPos();
351 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
352 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
353
354 // The number of arguments which should follow the sentinel.
355 unsigned numArgsAfterSentinel = attr->getSentinel();
356
357 // If there aren't enough arguments for all the formal parameters,
358 // the sentinel, and the args after the sentinel, complain.
359 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000360 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000361 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000362 return;
363 }
John McCall3323fad2011-09-09 07:56:05 +0000364
365 // Otherwise, find the sentinel expression.
366 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000367 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000368 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000369 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000370
John McCall3323fad2011-09-09 07:56:05 +0000371 // Pick a reasonable string to insert. Optimistically use 'nil' or
372 // 'NULL' if those are actually defined in the context. Only use
373 // 'nil' for ObjC methods, where it's much more likely that the
374 // variadic arguments form a list of object pointers.
375 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000376 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
377 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000378 if (calleeType == CT_Method &&
379 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000380 NullValue = "nil";
381 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
382 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000383 else
John McCall3323fad2011-09-09 07:56:05 +0000384 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000385
386 if (MissingNilLoc.isInvalid())
387 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
388 else
389 Diag(MissingNilLoc, diag::warn_missing_sentinel)
390 << calleeType
391 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000392 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000393}
394
Richard Trieuccd891a2011-09-09 01:45:06 +0000395SourceRange Sema::getExprRange(Expr *E) const {
396 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000397}
398
Chris Lattnere7a2e912008-07-25 21:10:04 +0000399//===----------------------------------------------------------------------===//
400// Standard Promotions and Conversions
401//===----------------------------------------------------------------------===//
402
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000404ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000405 // Handle any placeholder expressions which made it here.
406 if (E->getType()->isPlaceholderType()) {
407 ExprResult result = CheckPlaceholderExpr(E);
408 if (result.isInvalid()) return ExprError();
409 E = result.take();
410 }
411
Chris Lattnere7a2e912008-07-25 21:10:04 +0000412 QualType Ty = E->getType();
413 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
414
Chris Lattnere7a2e912008-07-25 21:10:04 +0000415 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000416 E = ImpCastExprToType(E, Context.getPointerType(Ty),
417 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000418 else if (Ty->isArrayType()) {
419 // In C90 mode, arrays only promote to pointers if the array expression is
420 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
421 // type 'array of type' is converted to an expression that has type 'pointer
422 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
423 // that has type 'array of type' ...". The relevant change is "an lvalue"
424 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000425 //
426 // C++ 4.2p1:
427 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
428 // T" can be converted to an rvalue of type "pointer to T".
429 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000430 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000431 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
432 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000433 }
John Wiegley429bb272011-04-08 18:41:53 +0000434 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000435}
436
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000437static void CheckForNullPointerDereference(Sema &S, Expr *E) {
438 // Check to see if we are dereferencing a null pointer. If so,
439 // and if not volatile-qualified, this is undefined behavior that the
440 // optimizer will delete, so warn about it. People sometimes try to use this
441 // to get a deterministic trap and are surprised by clang's behavior. This
442 // only handles the pattern "*null", which is a very syntactic check.
443 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
444 if (UO->getOpcode() == UO_Deref &&
445 UO->getSubExpr()->IgnoreParenCasts()->
446 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
447 !UO->getType().isVolatileQualified()) {
448 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449 S.PDiag(diag::warn_indirection_through_null)
450 << UO->getSubExpr()->getSourceRange());
451 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
452 S.PDiag(diag::note_indirection_through_null));
453 }
454}
455
John Wiegley429bb272011-04-08 18:41:53 +0000456ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000457 // Handle any placeholder expressions which made it here.
458 if (E->getType()->isPlaceholderType()) {
459 ExprResult result = CheckPlaceholderExpr(E);
460 if (result.isInvalid()) return ExprError();
461 E = result.take();
462 }
463
John McCall0ae287a2010-12-01 04:43:34 +0000464 // C++ [conv.lval]p1:
465 // A glvalue of a non-function, non-array type T can be
466 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000467 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000468
John McCall409fa9a2010-12-06 20:48:59 +0000469 QualType T = E->getType();
470 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000471
John McCall409fa9a2010-12-06 20:48:59 +0000472 // We don't want to throw lvalue-to-rvalue casts on top of
473 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000474 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000475 (E->getType() == Context.OverloadTy ||
476 T->isDependentType() ||
477 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000478 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000479
480 // The C standard is actually really unclear on this point, and
481 // DR106 tells us what the result should be but not why. It's
482 // generally best to say that void types just doesn't undergo
483 // lvalue-to-rvalue at all. Note that expressions of unqualified
484 // 'void' type are never l-values, but qualified void can be.
485 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000486 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000487
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000488 CheckForNullPointerDereference(*this, E);
489
John McCall409fa9a2010-12-06 20:48:59 +0000490 // C++ [conv.lval]p1:
491 // [...] If T is a non-class type, the type of the prvalue is the
492 // cv-unqualified version of T. Otherwise, the type of the
493 // rvalue is T.
494 //
495 // C99 6.3.2.1p2:
496 // If the lvalue has qualified type, the value has the unqualified
497 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000498 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000499 if (T.hasQualifiers())
500 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000501
Eli Friedmand2cce132012-02-02 23:15:15 +0000502 UpdateMarkingForLValueToRValue(E);
503
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000504 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
505 E, 0, VK_RValue));
506
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000507 // C11 6.3.2.1p2:
508 // ... if the lvalue has atomic type, the value has the non-atomic version
509 // of the type of the lvalue ...
510 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
511 T = Atomic->getValueType().getUnqualifiedType();
512 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
513 Res.get(), 0, VK_RValue));
514 }
515
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000516 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000517}
518
John Wiegley429bb272011-04-08 18:41:53 +0000519ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
520 ExprResult Res = DefaultFunctionArrayConversion(E);
521 if (Res.isInvalid())
522 return ExprError();
523 Res = DefaultLvalueConversion(Res.take());
524 if (Res.isInvalid())
525 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000526 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000527}
528
529
Chris Lattnere7a2e912008-07-25 21:10:04 +0000530/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000531/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000532/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000533/// apply if the array is an argument to the sizeof or address (&) operators.
534/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000535ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000536 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000537 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
538 if (Res.isInvalid())
539 return Owned(E);
540 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000541
John McCall0ae287a2010-12-01 04:43:34 +0000542 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000543 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000544
545 // Half FP is a bit different: it's a storage-only type, meaning that any
546 // "use" of it should be promoted to float.
547 if (Ty->isHalfType())
548 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
549
John McCall0ae287a2010-12-01 04:43:34 +0000550 // Try to perform integral promotions if the object has a theoretically
551 // promotable type.
552 if (Ty->isIntegralOrUnscopedEnumerationType()) {
553 // C99 6.3.1.1p2:
554 //
555 // The following may be used in an expression wherever an int or
556 // unsigned int may be used:
557 // - an object or expression with an integer type whose integer
558 // conversion rank is less than or equal to the rank of int
559 // and unsigned int.
560 // - A bit-field of type _Bool, int, signed int, or unsigned int.
561 //
562 // If an int can represent all values of the original type, the
563 // value is converted to an int; otherwise, it is converted to an
564 // unsigned int. These are called the integer promotions. All
565 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000566
John McCall0ae287a2010-12-01 04:43:34 +0000567 QualType PTy = Context.isPromotableBitField(E);
568 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000569 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
570 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000571 }
572 if (Ty->isPromotableIntegerType()) {
573 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
575 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000576 }
Eli Friedman04e83572009-08-20 04:21:42 +0000577 }
John Wiegley429bb272011-04-08 18:41:53 +0000578 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000579}
580
Chris Lattner05faf172008-07-25 22:25:12 +0000581/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000582/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000583/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000584ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
585 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000586 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000587
John Wiegley429bb272011-04-08 18:41:53 +0000588 ExprResult Res = UsualUnaryConversions(E);
589 if (Res.isInvalid())
590 return Owned(E);
591 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000592
Chris Lattner05faf172008-07-25 22:25:12 +0000593 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000594 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000595 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
596
John McCall96a914a2011-08-27 22:06:17 +0000597 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000598 // promotion, even on class types, but note:
599 // C++11 [conv.lval]p2:
600 // When an lvalue-to-rvalue conversion occurs in an unevaluated
601 // operand or a subexpression thereof the value contained in the
602 // referenced object is not accessed. Otherwise, if the glvalue
603 // has a class type, the conversion copy-initializes a temporary
604 // of type T from the glvalue and the result of the conversion
605 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000606 // FIXME: add some way to gate this entire thing for correctness in
607 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000608 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000609 ExprResult Temp = PerformCopyInitialization(
610 InitializedEntity::InitializeTemporary(E->getType()),
611 E->getExprLoc(),
612 Owned(E));
613 if (Temp.isInvalid())
614 return ExprError();
615 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000616 }
617
John Wiegley429bb272011-04-08 18:41:53 +0000618 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000619}
620
Richard Smith831421f2012-06-25 20:30:08 +0000621/// Determine the degree of POD-ness for an expression.
622/// Incomplete types are considered POD, since this check can be performed
623/// when we're in an unevaluated context.
624Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000625 if (Ty->isIncompleteType()) {
626 if (Ty->isObjCObjectType())
627 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000628 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000629 }
630
631 if (Ty.isCXX98PODType(Context))
632 return VAK_Valid;
633
Richard Smith831421f2012-06-25 20:30:08 +0000634 // C++0x [expr.call]p7:
635 // Passing a potentially-evaluated argument of class type (Clause 9)
636 // having a non-trivial copy constructor, a non-trivial move constructor,
637 // or a non-trivial destructor, with no corresponding parameter,
638 // is conditionally-supported with implementation-defined semantics.
Richard Smith831421f2012-06-25 20:30:08 +0000639 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
640 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
641 if (Record->hasTrivialCopyConstructor() &&
642 Record->hasTrivialMoveConstructor() &&
643 Record->hasTrivialDestructor())
644 return VAK_ValidInCXX11;
645
646 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
647 return VAK_Valid;
648 return VAK_Invalid;
649}
650
651bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
652 // Don't allow one to pass an Objective-C interface to a vararg.
653 const QualType & Ty = E->getType();
654
655 // Complain about passing non-POD types through varargs.
656 switch (isValidVarArgType(Ty)) {
657 case VAK_Valid:
658 break;
659 case VAK_ValidInCXX11:
660 DiagRuntimeBehavior(E->getLocStart(), 0,
661 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
662 << E->getType() << CT);
663 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000664 case VAK_Invalid: {
665 if (Ty->isObjCObjectType())
666 return DiagRuntimeBehavior(E->getLocStart(), 0,
667 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
668 << Ty << CT);
669
Richard Smith831421f2012-06-25 20:30:08 +0000670 return DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
672 << getLangOpts().CPlusPlus0x << Ty << CT);
673 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000674 }
Richard Smith831421f2012-06-25 20:30:08 +0000675 // c++ rules are enforced elsewhere.
676 return false;
677}
678
Chris Lattner312531a2009-04-12 08:11:20 +0000679/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000680/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000681ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000682 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000683 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000684 // Strip the unbridged-cast placeholder expression off, if applicable.
685 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
686 (CT == VariadicMethod ||
687 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
688 E = stripARCUnbridgedCast(E);
689
690 // Otherwise, do normal placeholder checking.
691 } else {
692 ExprResult ExprRes = CheckPlaceholderExpr(E);
693 if (ExprRes.isInvalid())
694 return ExprError();
695 E = ExprRes.take();
696 }
697 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000698
John McCall5acb0c92011-10-17 18:40:02 +0000699 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000700 if (ExprRes.isInvalid())
701 return ExprError();
702 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Richard Smith831421f2012-06-25 20:30:08 +0000704 // Diagnostics regarding non-POD argument types are
705 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000706 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000707 // Turn this into a trap.
708 CXXScopeSpec SS;
709 SourceLocation TemplateKWLoc;
710 UnqualifiedId Name;
711 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
712 E->getLocStart());
713 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
714 Name, true, false);
715 if (TrapFn.isInvalid())
716 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000717
Richard Smith831421f2012-06-25 20:30:08 +0000718 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
719 E->getLocStart(), MultiExprArg(),
720 E->getLocEnd());
721 if (Call.isInvalid())
722 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000723
Richard Smith831421f2012-06-25 20:30:08 +0000724 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
725 Call.get(), E);
726 if (Comma.isInvalid())
727 return ExprError();
728 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000729 }
Richard Smith831421f2012-06-25 20:30:08 +0000730
David Blaikie4e4d0842012-03-11 07:00:24 +0000731 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000732 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000733 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000734 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000735
John Wiegley429bb272011-04-08 18:41:53 +0000736 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000737}
738
Richard Trieu8289f492011-09-02 20:58:51 +0000739/// \brief Converts an integer to complex float type. Helper function of
740/// UsualArithmeticConversions()
741///
742/// \return false if the integer expression is an integer type and is
743/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000744static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
745 ExprResult &ComplexExpr,
746 QualType IntTy,
747 QualType ComplexTy,
748 bool SkipCast) {
749 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
750 if (SkipCast) return false;
751 if (IntTy->isIntegerType()) {
752 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
753 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
754 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000755 CK_FloatingRealToComplex);
756 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000757 assert(IntTy->isComplexIntegerType());
758 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000759 CK_IntegralComplexToFloatingComplex);
760 }
761 return false;
762}
763
764/// \brief Takes two complex float types and converts them to the same type.
765/// Helper function of UsualArithmeticConversions()
766static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000767handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
768 ExprResult &RHS, QualType LHSType,
769 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000770 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000771 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000772
773 if (order < 0) {
774 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000775 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000776 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
777 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000778 }
779 if (order > 0)
780 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000781 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
782 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000783}
784
785/// \brief Converts otherExpr to complex float and promotes complexExpr if
786/// necessary. Helper function of UsualArithmeticConversions()
787static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000788 ExprResult &ComplexExpr,
789 ExprResult &OtherExpr,
790 QualType ComplexTy,
791 QualType OtherTy,
792 bool ConvertComplexExpr,
793 bool ConvertOtherExpr) {
794 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000795
796 // If just the complexExpr is complex, the otherExpr needs to be converted,
797 // and the complexExpr might need to be promoted.
798 if (order > 0) { // complexExpr is wider
799 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000800 if (ConvertOtherExpr) {
801 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
802 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
803 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000804 CK_FloatingRealToComplex);
805 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000806 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000807 }
808
809 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 QualType result = (order == 0 ? ComplexTy :
811 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000812
813 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000814 if (ConvertOtherExpr)
815 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000816 CK_FloatingRealToComplex);
817
818 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000819 if (ConvertComplexExpr && order < 0)
820 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000821 CK_FloatingComplexCast);
822
823 return result;
824}
825
826/// \brief Handle arithmetic conversion with complex types. Helper function of
827/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000828static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
829 ExprResult &RHS, QualType LHSType,
830 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000831 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000832 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000833 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000834 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000835 return LHSType;
836 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000837 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000838 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000839
840 // This handles complex/complex, complex/float, or float/complex.
841 // When both operands are complex, the shorter operand is converted to the
842 // type of the longer, and that is the type of the result. This corresponds
843 // to what is done when combining two real floating-point operands.
844 // The fun begins when size promotion occur across type domains.
845 // From H&S 6.3.4: When one operand is complex and the other is a real
846 // floating-point type, the less precise type is converted, within it's
847 // real or complex domain, to the precision of the other type. For example,
848 // when combining a "long double" with a "double _Complex", the
849 // "double _Complex" is promoted to "long double _Complex".
850
Richard Trieucafd30b2011-09-06 18:25:09 +0000851 bool LHSComplexFloat = LHSType->isComplexType();
852 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000853
854 // If both are complex, just cast to the more precise type.
855 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000856 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
857 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000858 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000859
860 // If only one operand is complex, promote it if necessary and convert the
861 // other operand to complex.
862 if (LHSComplexFloat)
863 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000864 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000865 /*convertOtherExpr*/ true);
866
867 assert(RHSComplexFloat);
868 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000869 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000870 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000871}
872
873/// \brief Hande arithmetic conversion from integer to float. Helper function
874/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000875static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
876 ExprResult &IntExpr,
877 QualType FloatTy, QualType IntTy,
878 bool ConvertFloat, bool ConvertInt) {
879 if (IntTy->isIntegerType()) {
880 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000881 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000882 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000883 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000884 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000885 }
886
887 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 assert(IntTy->isComplexIntegerType());
889 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000890
891 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000892 if (ConvertInt)
893 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000894 CK_IntegralComplexToFloatingComplex);
895
896 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000897 if (ConvertFloat)
898 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000899 CK_FloatingRealToComplex);
900
901 return result;
902}
903
904/// \brief Handle arithmethic conversion with floating point types. Helper
905/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000906static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
907 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000908 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000909 bool LHSFloat = LHSType->isRealFloatingType();
910 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000911
912 // If we have two real floating types, convert the smaller operand
913 // to the bigger result.
914 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000915 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000916 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000917 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
918 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000919 }
920
921 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000922 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000923 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
924 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000925 }
926
927 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000928 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000929 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000930 /*convertInt=*/ true);
931 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000932 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000933 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000934 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000935}
936
937/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000938/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000939// FIXME: if the operands are (int, _Complex long), we currently
940// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000941static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
942 ExprResult &RHS, QualType LHSType,
943 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000944 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000945 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
946 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000947
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000948 if (LHSComplexInt && RHSComplexInt) {
949 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
950 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000951 assert(order && "inequal types with equal element ordering");
952 if (order > 0) {
953 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000954 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
955 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000956 }
957
Richard Trieuccd891a2011-09-09 01:45:06 +0000958 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000959 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
960 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000961 }
962
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000963 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000964 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000965 // FIXME: This needs to take integer ranks into account
966 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
967 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000968 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
969 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000970 }
971
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000972 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000973 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000974 // FIXME: This needs to take integer ranks into account
975 if (!IsCompAssign) {
976 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
977 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000978 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000979 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000980 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000981}
982
983/// \brief Handle integer arithmetic conversions. Helper function of
984/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000985static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
986 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000987 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000988 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000989 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
990 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
991 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
992 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000993 // Same signedness; use the higher-ranked type
994 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000995 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
996 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000997 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000998 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
999 return RHSType;
1000 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001001 // The unsigned type has greater than or equal rank to the
1002 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001003 if (RHSSigned) {
1004 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1005 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001006 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001007 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1008 return RHSType;
1009 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001010 // The two types are different widths; if we are here, that
1011 // means the signed type is larger than the unsigned type, so
1012 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001013 if (LHSSigned) {
1014 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1015 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001016 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001017 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1018 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001019 } else {
1020 // The signed type is higher-ranked than the unsigned type,
1021 // but isn't actually any bigger (like unsigned int and long
1022 // on most 32-bit systems). Use the unsigned type corresponding
1023 // to the signed type.
1024 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001025 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1026 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001027 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001028 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001029 return result;
1030 }
1031}
1032
Chris Lattnere7a2e912008-07-25 21:10:04 +00001033/// UsualArithmeticConversions - Performs various conversions that are common to
1034/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001035/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001036/// responsible for emitting appropriate error diagnostics.
1037/// FIXME: verify the conversion rules for "complex int" are consistent with
1038/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001039QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001040 bool IsCompAssign) {
1041 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001042 LHS = UsualUnaryConversions(LHS.take());
1043 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001044 return QualType();
1045 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001046
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001047 RHS = UsualUnaryConversions(RHS.take());
1048 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001049 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001050
Mike Stump1eb44332009-09-09 15:08:12 +00001051 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001052 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001053 QualType LHSType =
1054 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1055 QualType RHSType =
1056 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001057
Eli Friedman860a3192012-06-16 02:19:17 +00001058 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1059 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1060 LHSType = AtomicLHS->getValueType();
1061
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001062 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001063 if (LHSType == RHSType)
1064 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001065
1066 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1067 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001068 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001069 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001070
John McCallcf33b242010-11-13 08:17:45 +00001071 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001072 QualType LHSUnpromotedType = LHSType;
1073 if (LHSType->isPromotableIntegerType())
1074 LHSType = Context.getPromotedIntegerType(LHSType);
1075 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001076 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001077 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001078 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001079 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001080
John McCallcf33b242010-11-13 08:17:45 +00001081 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001082 if (LHSType == RHSType)
1083 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001084
1085 // At this point, we have two different arithmetic types.
1086
1087 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001088 if (LHSType->isComplexType() || RHSType->isComplexType())
1089 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001090 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001091
1092 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001093 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1094 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001095 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001096
1097 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001098 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001099 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001100 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001101
1102 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001103 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001104 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001105}
1106
Chris Lattnere7a2e912008-07-25 21:10:04 +00001107//===----------------------------------------------------------------------===//
1108// Semantic Analysis for various Expression Types
1109//===----------------------------------------------------------------------===//
1110
1111
Peter Collingbournef111d932011-04-15 00:35:48 +00001112ExprResult
1113Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1114 SourceLocation DefaultLoc,
1115 SourceLocation RParenLoc,
1116 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001117 MultiTypeArg ArgTypes,
1118 MultiExprArg ArgExprs) {
1119 unsigned NumAssocs = ArgTypes.size();
1120 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001121
Benjamin Kramer5354e772012-08-23 23:38:35 +00001122 ParsedType *ParsedTypes = ArgTypes.data();
1123 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001124
1125 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1126 for (unsigned i = 0; i < NumAssocs; ++i) {
1127 if (ParsedTypes[i])
1128 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1129 else
1130 Types[i] = 0;
1131 }
1132
1133 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1134 ControllingExpr, Types, Exprs,
1135 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001136 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001137 return ER;
1138}
1139
1140ExprResult
1141Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1142 SourceLocation DefaultLoc,
1143 SourceLocation RParenLoc,
1144 Expr *ControllingExpr,
1145 TypeSourceInfo **Types,
1146 Expr **Exprs,
1147 unsigned NumAssocs) {
1148 bool TypeErrorFound = false,
1149 IsResultDependent = ControllingExpr->isTypeDependent(),
1150 ContainsUnexpandedParameterPack
1151 = ControllingExpr->containsUnexpandedParameterPack();
1152
1153 for (unsigned i = 0; i < NumAssocs; ++i) {
1154 if (Exprs[i]->containsUnexpandedParameterPack())
1155 ContainsUnexpandedParameterPack = true;
1156
1157 if (Types[i]) {
1158 if (Types[i]->getType()->containsUnexpandedParameterPack())
1159 ContainsUnexpandedParameterPack = true;
1160
1161 if (Types[i]->getType()->isDependentType()) {
1162 IsResultDependent = true;
1163 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001164 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001165 // complete object type other than a variably modified type."
1166 unsigned D = 0;
1167 if (Types[i]->getType()->isIncompleteType())
1168 D = diag::err_assoc_type_incomplete;
1169 else if (!Types[i]->getType()->isObjectType())
1170 D = diag::err_assoc_type_nonobject;
1171 else if (Types[i]->getType()->isVariablyModifiedType())
1172 D = diag::err_assoc_type_variably_modified;
1173
1174 if (D != 0) {
1175 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1176 << Types[i]->getTypeLoc().getSourceRange()
1177 << Types[i]->getType();
1178 TypeErrorFound = true;
1179 }
1180
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001181 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001182 // selection shall specify compatible types."
1183 for (unsigned j = i+1; j < NumAssocs; ++j)
1184 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1185 Context.typesAreCompatible(Types[i]->getType(),
1186 Types[j]->getType())) {
1187 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1188 diag::err_assoc_compatible_types)
1189 << Types[j]->getTypeLoc().getSourceRange()
1190 << Types[j]->getType()
1191 << Types[i]->getType();
1192 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1193 diag::note_compat_assoc)
1194 << Types[i]->getTypeLoc().getSourceRange()
1195 << Types[i]->getType();
1196 TypeErrorFound = true;
1197 }
1198 }
1199 }
1200 }
1201 if (TypeErrorFound)
1202 return ExprError();
1203
1204 // If we determined that the generic selection is result-dependent, don't
1205 // try to compute the result expression.
1206 if (IsResultDependent)
1207 return Owned(new (Context) GenericSelectionExpr(
1208 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001209 llvm::makeArrayRef(Types, NumAssocs),
1210 llvm::makeArrayRef(Exprs, NumAssocs),
1211 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001212
Chris Lattner5f9e2722011-07-23 10:55:15 +00001213 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001214 unsigned DefaultIndex = -1U;
1215 for (unsigned i = 0; i < NumAssocs; ++i) {
1216 if (!Types[i])
1217 DefaultIndex = i;
1218 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1219 Types[i]->getType()))
1220 CompatIndices.push_back(i);
1221 }
1222
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001223 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001224 // type compatible with at most one of the types named in its generic
1225 // association list."
1226 if (CompatIndices.size() > 1) {
1227 // We strip parens here because the controlling expression is typically
1228 // parenthesized in macro definitions.
1229 ControllingExpr = ControllingExpr->IgnoreParens();
1230 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1231 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1232 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001233 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001234 E = CompatIndices.end(); I != E; ++I) {
1235 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1236 diag::note_compat_assoc)
1237 << Types[*I]->getTypeLoc().getSourceRange()
1238 << Types[*I]->getType();
1239 }
1240 return ExprError();
1241 }
1242
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001243 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001244 // its controlling expression shall have type compatible with exactly one of
1245 // the types named in its generic association list."
1246 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1247 // We strip parens here because the controlling expression is typically
1248 // parenthesized in macro definitions.
1249 ControllingExpr = ControllingExpr->IgnoreParens();
1250 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1251 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1252 return ExprError();
1253 }
1254
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001255 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001256 // type name that is compatible with the type of the controlling expression,
1257 // then the result expression of the generic selection is the expression
1258 // in that generic association. Otherwise, the result expression of the
1259 // generic selection is the expression in the default generic association."
1260 unsigned ResultIndex =
1261 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1262
1263 return Owned(new (Context) GenericSelectionExpr(
1264 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001265 llvm::makeArrayRef(Types, NumAssocs),
1266 llvm::makeArrayRef(Exprs, NumAssocs),
1267 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001268 ResultIndex));
1269}
1270
Richard Smithdd66be72012-03-08 01:34:56 +00001271/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1272/// location of the token and the offset of the ud-suffix within it.
1273static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1274 unsigned Offset) {
1275 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001276 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001277}
1278
Richard Smith36f5cfe2012-03-09 08:00:36 +00001279/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1280/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1281static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1282 IdentifierInfo *UDSuffix,
1283 SourceLocation UDSuffixLoc,
1284 ArrayRef<Expr*> Args,
1285 SourceLocation LitEndLoc) {
1286 assert(Args.size() <= 2 && "too many arguments for literal operator");
1287
1288 QualType ArgTy[2];
1289 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1290 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1291 if (ArgTy[ArgIdx]->isArrayType())
1292 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1293 }
1294
1295 DeclarationName OpName =
1296 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1297 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1298 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1299
1300 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1301 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1302 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1303 return ExprError();
1304
1305 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1306}
1307
Steve Narofff69936d2007-09-16 03:34:24 +00001308/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001309/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1310/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1311/// multiple tokens. However, the common case is that StringToks points to one
1312/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001313///
John McCall60d7b3a2010-08-24 06:29:42 +00001314ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001315Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1316 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 assert(NumStringToks && "Must have at least one string!");
1318
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001319 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001321 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001322
Chris Lattner5f9e2722011-07-23 10:55:15 +00001323 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 for (unsigned i = 0; i != NumStringToks; ++i)
1325 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001326
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001327 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001328 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001329 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001330 else if (Literal.isUTF16())
1331 StrTy = Context.Char16Ty;
1332 else if (Literal.isUTF32())
1333 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001334 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001335 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001336
Douglas Gregor5cee1192011-07-27 05:40:30 +00001337 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1338 if (Literal.isWide())
1339 Kind = StringLiteral::Wide;
1340 else if (Literal.isUTF8())
1341 Kind = StringLiteral::UTF8;
1342 else if (Literal.isUTF16())
1343 Kind = StringLiteral::UTF16;
1344 else if (Literal.isUTF32())
1345 Kind = StringLiteral::UTF32;
1346
Douglas Gregor77a52232008-09-12 00:47:35 +00001347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001348 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001349 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001350
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001351 // Get an array type for the string, according to C99 6.4.5. This includes
1352 // the nul terminator character as well as the string length for pascal
1353 // strings.
1354 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001355 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001356 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001359 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1360 Kind, Literal.Pascal, StrTy,
1361 &StringTokLocs[0],
1362 StringTokLocs.size());
1363 if (Literal.getUDSuffix().empty())
1364 return Owned(Lit);
1365
1366 // We're building a user-defined literal.
1367 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001368 SourceLocation UDSuffixLoc =
1369 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1370 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001371
Richard Smith36f5cfe2012-03-09 08:00:36 +00001372 // Make sure we're allowed user-defined literals here.
1373 if (!UDLScope)
1374 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1375
Richard Smith9fcce652012-03-07 08:35:16 +00001376 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1377 // operator "" X (str, len)
1378 QualType SizeType = Context.getSizeType();
1379 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1380 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1381 StringTokLocs[0]);
1382 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001383 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1384 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001385}
1386
John McCall60d7b3a2010-08-24 06:29:42 +00001387ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001388Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001389 SourceLocation Loc,
1390 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001391 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001392 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001393}
1394
John McCall76a40212011-02-09 01:13:10 +00001395/// BuildDeclRefExpr - Build an expression that references a
1396/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001397ExprResult
John McCall76a40212011-02-09 01:13:10 +00001398Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001399 const DeclarationNameInfo &NameInfo,
1400 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001401 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001402 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1403 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1404 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1405 CalleeTarget = IdentifyCUDATarget(Callee);
1406 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1407 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1408 << CalleeTarget << D->getIdentifier() << CallerTarget;
1409 Diag(D->getLocation(), diag::note_previous_decl)
1410 << D->getIdentifier();
1411 return ExprError();
1412 }
1413 }
1414
John McCallf4b88a42012-03-10 09:33:50 +00001415 bool refersToEnclosingScope =
1416 (CurContext != D->getDeclContext() &&
1417 D->getDeclContext()->isFunctionOrMethod());
1418
Eli Friedman5f2987c2012-02-02 03:46:19 +00001419 DeclRefExpr *E = DeclRefExpr::Create(Context,
1420 SS ? SS->getWithLocInContext(Context)
1421 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001422 SourceLocation(),
1423 D, refersToEnclosingScope,
1424 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Eli Friedman5f2987c2012-02-02 03:46:19 +00001426 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001427
Jordan Rose7a270482012-09-28 22:21:35 +00001428 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1429 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1430 DiagnosticsEngine::Level Level =
1431 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1432 E->getLocStart());
1433 if (Level != DiagnosticsEngine::Ignored)
1434 getCurFunction()->recordUseOfWeak(E);
1435 }
1436
John McCall7eb0a9e2010-11-24 05:12:34 +00001437 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001438 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1439 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001440 E->setObjectKind(OK_BitField);
1441
1442 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001443}
1444
Abramo Bagnara25777432010-08-11 22:01:17 +00001445/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001446/// possibly a list of template arguments.
1447///
1448/// If this produces template arguments, it is permitted to call
1449/// DecomposeTemplateName.
1450///
1451/// This actually loses a lot of source location information for
1452/// non-standard name kinds; we should consider preserving that in
1453/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001454void
1455Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1456 TemplateArgumentListInfo &Buffer,
1457 DeclarationNameInfo &NameInfo,
1458 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001459 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1460 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1461 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1462
Benjamin Kramer5354e772012-08-23 23:38:35 +00001463 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001464 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001465 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001466
John McCall2b5289b2010-08-23 07:28:44 +00001467 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001468 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001469 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001470 TemplateArgs = &Buffer;
1471 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001472 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001473 TemplateArgs = 0;
1474 }
1475}
1476
John McCall578b69b2009-12-16 08:11:27 +00001477/// Diagnose an empty lookup.
1478///
1479/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001480bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001481 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001482 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001483 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001484 DeclarationName Name = R.getLookupName();
1485
John McCall578b69b2009-12-16 08:11:27 +00001486 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001487 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001488 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1489 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001490 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001491 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001492 diagnostic_suggest = diag::err_undeclared_use_suggest;
1493 }
John McCall578b69b2009-12-16 08:11:27 +00001494
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001495 // If the original lookup was an unqualified lookup, fake an
1496 // unqualified lookup. This is useful when (for example) the
1497 // original lookup would not have found something because it was a
1498 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001499 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1500 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001501 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001502 if (isa<CXXRecordDecl>(DC)) {
1503 LookupQualifiedName(R, DC);
1504
1505 if (!R.empty()) {
1506 // Don't give errors about ambiguities in this lookup.
1507 R.suppressDiagnostics();
1508
Francois Pichete6226ae2011-11-17 03:44:24 +00001509 // During a default argument instantiation the CurContext points
1510 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1511 // function parameter list, hence add an explicit check.
1512 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1513 ActiveTemplateInstantiations.back().Kind ==
1514 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001515 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1516 bool isInstance = CurMethod &&
1517 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001518 DC == CurMethod->getParent() && !isDefaultArgument;
1519
John McCall578b69b2009-12-16 08:11:27 +00001520
1521 // Give a code modification hint to insert 'this->'.
1522 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1523 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001524 if (getLangOpts().MicrosoftMode)
1525 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001526 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001527 Diag(R.getNameLoc(), diagnostic) << Name
1528 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001529 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1530 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001531
1532
1533 CXXMethodDecl *DepMethod;
1534 if (CurMethod->getTemplatedKind() ==
1535 FunctionDecl::TK_FunctionTemplateSpecialization)
1536 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1537 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1538 else
1539 DepMethod = cast<CXXMethodDecl>(
1540 CurMethod->getInstantiatedFromMemberFunction());
1541 assert(DepMethod && "No template pattern found");
1542
1543 QualType DepThisType = DepMethod->getThisType(Context);
1544 CheckCXXThisCapture(R.getNameLoc());
1545 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1546 R.getNameLoc(), DepThisType, false);
1547 TemplateArgumentListInfo TList;
1548 if (ULE->hasExplicitTemplateArgs())
1549 ULE->copyTemplateArgumentsInto(TList);
1550
1551 CXXScopeSpec SS;
1552 SS.Adopt(ULE->getQualifierLoc());
1553 CXXDependentScopeMemberExpr *DepExpr =
1554 CXXDependentScopeMemberExpr::Create(
1555 Context, DepThis, DepThisType, true, SourceLocation(),
1556 SS.getWithLocInContext(Context),
1557 ULE->getTemplateKeywordLoc(), 0,
1558 R.getLookupNameInfo(),
1559 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1560 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001561 } else {
John McCall578b69b2009-12-16 08:11:27 +00001562 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001563 }
John McCall578b69b2009-12-16 08:11:27 +00001564
1565 // Do we really want to note all of these?
1566 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1567 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1568
Francois Pichete6226ae2011-11-17 03:44:24 +00001569 // Return true if we are inside a default argument instantiation
1570 // and the found name refers to an instance member function, otherwise
1571 // the function calling DiagnoseEmptyLookup will try to create an
1572 // implicit member call and this is wrong for default argument.
1573 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1574 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1575 return true;
1576 }
1577
John McCall578b69b2009-12-16 08:11:27 +00001578 // Tell the callee to try to recover.
1579 return false;
1580 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001581
1582 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001583 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001584
1585 // In Microsoft mode, if we are performing lookup from within a friend
1586 // function definition declared at class scope then we must set
1587 // DC to the lexical parent to be able to search into the parent
1588 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001589 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001590 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1591 DC->getLexicalParent()->isRecord())
1592 DC = DC->getLexicalParent();
1593 else
1594 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001595 }
1596
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001597 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001598 TypoCorrection Corrected;
1599 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001600 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001601 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1602 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001603 R.setLookupName(Corrected.getCorrection());
1604
Hans Wennborg701d1e72011-07-12 08:45:31 +00001605 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001606 if (Corrected.isOverloaded()) {
1607 OverloadCandidateSet OCS(R.getNameLoc());
1608 OverloadCandidateSet::iterator Best;
1609 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1610 CDEnd = Corrected.end();
1611 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001612 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001613 dyn_cast<FunctionTemplateDecl>(*CD))
1614 AddTemplateOverloadCandidate(
1615 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001616 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001617 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1618 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1619 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001620 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001621 }
1622 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1623 case OR_Success:
1624 ND = Best->Function;
1625 break;
1626 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001627 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001628 }
1629 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001630 R.addDecl(ND);
1631 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001632 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001633 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1634 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001635 else
1636 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001637 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001638 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001639 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1640 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001641 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001642 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001643
1644 // Tell the callee to try to recover.
1645 return false;
1646 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001647
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001648 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001649 // FIXME: If we ended up with a typo for a type name or
1650 // Objective-C class name, we're in trouble because the parser
1651 // is in the wrong place to recover. Suggest the typo
1652 // correction, but don't make it a fix-it since we're not going
1653 // to recover well anyway.
1654 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001655 Diag(R.getNameLoc(), diagnostic_suggest)
1656 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001657 else
1658 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001659 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001660 << SS.getRange();
1661
1662 // Don't try to recover; it won't work.
1663 return true;
1664 }
1665 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001666 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001667 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001668 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001669 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001670 else
Douglas Gregord203a162010-01-01 00:15:04 +00001671 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001672 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001673 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001674 return true;
1675 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001676 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001677 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001678
1679 // Emit a special diagnostic for failed member lookups.
1680 // FIXME: computing the declaration context might fail here (?)
1681 if (!SS.isEmpty()) {
1682 Diag(R.getNameLoc(), diag::err_no_member)
1683 << Name << computeDeclContext(SS, false)
1684 << SS.getRange();
1685 return true;
1686 }
1687
John McCall578b69b2009-12-16 08:11:27 +00001688 // Give up, we can't recover.
1689 Diag(R.getNameLoc(), diagnostic) << Name;
1690 return true;
1691}
1692
John McCall60d7b3a2010-08-24 06:29:42 +00001693ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001694 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001695 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001696 UnqualifiedId &Id,
1697 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001698 bool IsAddressOfOperand,
1699 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001700 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001701 "cannot be direct & operand and have a trailing lparen");
1702
1703 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001704 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001705
John McCall129e2df2009-11-30 22:42:35 +00001706 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001707
1708 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001709 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001710 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001711 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001712
Abramo Bagnara25777432010-08-11 22:01:17 +00001713 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001714 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001715 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001716
John McCallf7a1a742009-11-24 19:00:30 +00001717 // C++ [temp.dep.expr]p3:
1718 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001719 // -- an identifier that was declared with a dependent type,
1720 // (note: handled after lookup)
1721 // -- a template-id that is dependent,
1722 // (note: handled in BuildTemplateIdExpr)
1723 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001724 // -- a nested-name-specifier that contains a class-name that
1725 // names a dependent type.
1726 // Determine whether this is a member of an unknown specialization;
1727 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001728 bool DependentID = false;
1729 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1730 Name.getCXXNameType()->isDependentType()) {
1731 DependentID = true;
1732 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001733 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001734 if (RequireCompleteDeclContext(SS, DC))
1735 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001736 } else {
1737 DependentID = true;
1738 }
1739 }
1740
Chris Lattner337e5502011-02-18 01:27:55 +00001741 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001742 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1743 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001744
John McCallf7a1a742009-11-24 19:00:30 +00001745 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001746 LookupResult R(*this, NameInfo,
1747 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1748 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001749 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001750 // Lookup the template name again to correctly establish the context in
1751 // which it was found. This is really unfortunate as we already did the
1752 // lookup to determine that it was a template name in the first place. If
1753 // this becomes a performance hit, we can work harder to preserve those
1754 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001755 bool MemberOfUnknownSpecialization;
1756 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1757 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001758
1759 if (MemberOfUnknownSpecialization ||
1760 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001761 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1762 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001763 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001764 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001765 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001767 // If the result might be in a dependent base class, this is a dependent
1768 // id-expression.
1769 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001770 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1771 IsAddressOfOperand, TemplateArgs);
1772
John McCallf7a1a742009-11-24 19:00:30 +00001773 // If this reference is in an Objective-C method, then we need to do
1774 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001775 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001776 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001777 if (E.isInvalid())
1778 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Chris Lattner337e5502011-02-18 01:27:55 +00001780 if (Expr *Ex = E.takeAs<Expr>())
1781 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001782 }
Chris Lattner8a934232008-03-31 00:36:02 +00001783 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001784
John McCallf7a1a742009-11-24 19:00:30 +00001785 if (R.isAmbiguous())
1786 return ExprError();
1787
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001788 // Determine whether this name might be a candidate for
1789 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001790 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001791
John McCallf7a1a742009-11-24 19:00:30 +00001792 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001794 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001795 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001796 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1797 if (D) R.addDecl(D);
1798 }
1799
1800 // If this name wasn't predeclared and if this is not a function
1801 // call, diagnose the problem.
1802 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001803
1804 // In Microsoft mode, if we are inside a template class member function
1805 // and we can't resolve an identifier then assume the identifier is type
1806 // dependent. The goal is to postpone name lookup to instantiation time
1807 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001808 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001809 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001810 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1811 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001812
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001813 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001814 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001815 return ExprError();
1816
1817 assert(!R.empty() &&
1818 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001819
1820 // If we found an Objective-C instance variable, let
1821 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001822 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001823 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1824 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001825 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001826 // In a hopelessly buggy code, Objective-C instance variable
1827 // lookup fails and no expression will be built to reference it.
1828 if (!E.isInvalid() && !E.get())
1829 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001830 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001831 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 }
1833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
John McCallf7a1a742009-11-24 19:00:30 +00001835 // This is guaranteed from this point on.
1836 assert(!R.empty() || ADL);
1837
John McCallaa81e162009-12-01 22:10:20 +00001838 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001839 // C++ [class.mfct.non-static]p3:
1840 // When an id-expression that is not part of a class member access
1841 // syntax and not used to form a pointer to member is used in the
1842 // body of a non-static member function of class X, if name lookup
1843 // resolves the name in the id-expression to a non-static non-type
1844 // member of some class C, the id-expression is transformed into a
1845 // class member access expression using (*this) as the
1846 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001847 //
1848 // But we don't actually need to do this for '&' operands if R
1849 // resolved to a function or overloaded function set, because the
1850 // expression is ill-formed if it actually works out to be a
1851 // non-static member function:
1852 //
1853 // C++ [expr.ref]p4:
1854 // Otherwise, if E1.E2 refers to a non-static member function. . .
1855 // [t]he expression can be used only as the left-hand operand of a
1856 // member function call.
1857 //
1858 // There are other safeguards against such uses, but it's important
1859 // to get this right here so that we don't end up making a
1860 // spuriously dependent expression if we're inside a dependent
1861 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001862 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001863 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001864 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001865 MightBeImplicitMember = true;
1866 else if (!SS.isEmpty())
1867 MightBeImplicitMember = false;
1868 else if (R.isOverloadedResult())
1869 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001870 else if (R.isUnresolvableResult())
1871 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001872 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001873 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1874 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001875
1876 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001877 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1878 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001879 }
1880
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001881 if (TemplateArgs || TemplateKWLoc.isValid())
1882 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001883
John McCallf7a1a742009-11-24 19:00:30 +00001884 return BuildDeclarationNameExpr(SS, R, ADL);
1885}
1886
John McCall129e2df2009-11-30 22:42:35 +00001887/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1888/// declaration name, generally during template instantiation.
1889/// There's a large number of things which don't need to be done along
1890/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001891ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001892Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001893 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001894 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001895 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001896 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1897 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001898
John McCall77bb1aa2010-05-01 00:40:08 +00001899 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001900 return ExprError();
1901
Abramo Bagnara25777432010-08-11 22:01:17 +00001902 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001903 LookupQualifiedName(R, DC);
1904
1905 if (R.isAmbiguous())
1906 return ExprError();
1907
1908 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001909 Diag(NameInfo.getLoc(), diag::err_no_member)
1910 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001911 return ExprError();
1912 }
1913
1914 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1915}
1916
1917/// LookupInObjCMethod - The parser has read a name in, and Sema has
1918/// detected that we're currently inside an ObjC method. Perform some
1919/// additional lookup.
1920///
1921/// Ideally, most of this would be done by lookup, but there's
1922/// actually quite a lot of extra work involved.
1923///
1924/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001925ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001926Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001927 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001928 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001929 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001930
John McCallf7a1a742009-11-24 19:00:30 +00001931 // There are two cases to handle here. 1) scoped lookup could have failed,
1932 // in which case we should look for an ivar. 2) scoped lookup could have
1933 // found a decl, but that decl is outside the current instance method (i.e.
1934 // a global variable). In these two cases, we do a lookup for an ivar with
1935 // this name, if the lookup sucedes, we replace it our current decl.
1936
1937 // If we're in a class method, we don't normally want to look for
1938 // ivars. But if we don't find anything else, and there's an
1939 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001940 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001941
1942 bool LookForIvars;
1943 if (Lookup.empty())
1944 LookForIvars = true;
1945 else if (IsClassMethod)
1946 LookForIvars = false;
1947 else
1948 LookForIvars = (Lookup.isSingleResult() &&
1949 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001950 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001951 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001952 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001953 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001954 ObjCIvarDecl *IV = 0;
1955 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001956 // Diagnose using an ivar in a class method.
1957 if (IsClassMethod)
1958 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1959 << IV->getDeclName());
1960
1961 // If we're referencing an invalid decl, just return this as a silent
1962 // error node. The error diagnostic was already emitted on the decl.
1963 if (IV->isInvalidDecl())
1964 return ExprError();
1965
1966 // Check if referencing a field with __attribute__((deprecated)).
1967 if (DiagnoseUseOfDecl(IV, Loc))
1968 return ExprError();
1969
1970 // Diagnose the use of an ivar outside of the declaring class.
1971 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001972 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001973 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001974 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1975
1976 // FIXME: This should use a new expr for a direct reference, don't
1977 // turn this into Self->ivar, just return a BareIVarExpr or something.
1978 IdentifierInfo &II = Context.Idents.get("self");
1979 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001980 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001981 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001982 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001983 SourceLocation TemplateKWLoc;
1984 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001985 SelfName, false, false);
1986 if (SelfExpr.isInvalid())
1987 return ExprError();
1988
John Wiegley429bb272011-04-08 18:41:53 +00001989 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1990 if (SelfExpr.isInvalid())
1991 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001992
Eli Friedman5f2987c2012-02-02 03:46:19 +00001993 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001994
1995 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1996 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1997 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00001998
1999 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2000 Loc,
2001 SelfExpr.take(),
2002 true, true);
2003
2004 if (getLangOpts().ObjCAutoRefCount) {
2005 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2006 DiagnosticsEngine::Level Level =
2007 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2008 if (Level != DiagnosticsEngine::Ignored)
2009 getCurFunction()->recordUseOfWeak(Result);
2010 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002011 if (CurContext->isClosure())
2012 Diag(Loc, diag::warn_implicitly_retains_self)
2013 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002014 }
2015
2016 return Owned(Result);
John McCallf7a1a742009-11-24 19:00:30 +00002017 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002018 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002019 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002020 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2021 ObjCInterfaceDecl *ClassDeclared;
2022 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2023 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002024 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002025 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2026 }
John McCallf7a1a742009-11-24 19:00:30 +00002027 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002028 } else if (Lookup.isSingleResult() &&
2029 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2030 // If accessing a stand-alone ivar in a class method, this is an error.
2031 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2032 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2033 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002034 }
2035
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002036 if (Lookup.empty() && II && AllowBuiltinCreation) {
2037 // FIXME. Consolidate this with similar code in LookupName.
2038 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002039 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002040 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2041 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2042 S, Lookup.isForRedeclaration(),
2043 Lookup.getNameLoc());
2044 if (D) Lookup.addDecl(D);
2045 }
2046 }
2047 }
John McCallf7a1a742009-11-24 19:00:30 +00002048 // Sentinel value saying that we didn't do anything special.
2049 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002050}
John McCallba135432009-11-21 08:51:07 +00002051
John McCall6bb80172010-03-30 21:47:33 +00002052/// \brief Cast a base object to a member's actual type.
2053///
2054/// Logically this happens in three phases:
2055///
2056/// * First we cast from the base type to the naming class.
2057/// The naming class is the class into which we were looking
2058/// when we found the member; it's the qualifier type if a
2059/// qualifier was provided, and otherwise it's the base type.
2060///
2061/// * Next we cast from the naming class to the declaring class.
2062/// If the member we found was brought into a class's scope by
2063/// a using declaration, this is that class; otherwise it's
2064/// the class declaring the member.
2065///
2066/// * Finally we cast from the declaring class to the "true"
2067/// declaring class of the member. This conversion does not
2068/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002069ExprResult
2070Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002071 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002072 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002073 NamedDecl *Member) {
2074 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2075 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002076 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002077
Douglas Gregor5fccd362010-03-03 23:55:11 +00002078 QualType DestRecordType;
2079 QualType DestType;
2080 QualType FromRecordType;
2081 QualType FromType = From->getType();
2082 bool PointerConversions = false;
2083 if (isa<FieldDecl>(Member)) {
2084 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002085
Douglas Gregor5fccd362010-03-03 23:55:11 +00002086 if (FromType->getAs<PointerType>()) {
2087 DestType = Context.getPointerType(DestRecordType);
2088 FromRecordType = FromType->getPointeeType();
2089 PointerConversions = true;
2090 } else {
2091 DestType = DestRecordType;
2092 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002093 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002094 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2095 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002096 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002097
Douglas Gregor5fccd362010-03-03 23:55:11 +00002098 DestType = Method->getThisType(Context);
2099 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002100
Douglas Gregor5fccd362010-03-03 23:55:11 +00002101 if (FromType->getAs<PointerType>()) {
2102 FromRecordType = FromType->getPointeeType();
2103 PointerConversions = true;
2104 } else {
2105 FromRecordType = FromType;
2106 DestType = DestRecordType;
2107 }
2108 } else {
2109 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002110 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002111 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002112
Douglas Gregor5fccd362010-03-03 23:55:11 +00002113 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002114 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002115
Douglas Gregor5fccd362010-03-03 23:55:11 +00002116 // If the unqualified types are the same, no conversion is necessary.
2117 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002118 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002119
John McCall6bb80172010-03-30 21:47:33 +00002120 SourceRange FromRange = From->getSourceRange();
2121 SourceLocation FromLoc = FromRange.getBegin();
2122
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002123 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002124
Douglas Gregor5fccd362010-03-03 23:55:11 +00002125 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002126 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002127 // class name.
2128 //
2129 // If the member was a qualified name and the qualified referred to a
2130 // specific base subobject type, we'll cast to that intermediate type
2131 // first and then to the object in which the member is declared. That allows
2132 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2133 //
2134 // class Base { public: int x; };
2135 // class Derived1 : public Base { };
2136 // class Derived2 : public Base { };
2137 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2138 //
2139 // void VeryDerived::f() {
2140 // x = 17; // error: ambiguous base subobjects
2141 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2142 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002143 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002144 QualType QType = QualType(Qualifier->getAsType(), 0);
2145 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2146 assert(QType->isRecordType() && "lookup done with non-record type");
2147
2148 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2149
2150 // In C++98, the qualifier type doesn't actually have to be a base
2151 // type of the object type, in which case we just ignore it.
2152 // Otherwise build the appropriate casts.
2153 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002154 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002155 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002156 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002157 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002158
Douglas Gregor5fccd362010-03-03 23:55:11 +00002159 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002160 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002161 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2162 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002163
2164 FromType = QType;
2165 FromRecordType = QRecordType;
2166
2167 // If the qualifier type was the same as the destination type,
2168 // we're done.
2169 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002170 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002171 }
2172 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002173
John McCall6bb80172010-03-30 21:47:33 +00002174 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002175
John McCall6bb80172010-03-30 21:47:33 +00002176 // If we actually found the member through a using declaration, cast
2177 // down to the using declaration's type.
2178 //
2179 // Pointer equality is fine here because only one declaration of a
2180 // class ever has member declarations.
2181 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2182 assert(isa<UsingShadowDecl>(FoundDecl));
2183 QualType URecordType = Context.getTypeDeclType(
2184 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2185
2186 // We only need to do this if the naming-class to declaring-class
2187 // conversion is non-trivial.
2188 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2189 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002190 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002191 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002192 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002193 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002194
John McCall6bb80172010-03-30 21:47:33 +00002195 QualType UType = URecordType;
2196 if (PointerConversions)
2197 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002198 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2199 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002200 FromType = UType;
2201 FromRecordType = URecordType;
2202 }
2203
2204 // We don't do access control for the conversion from the
2205 // declaring class to the true declaring class.
2206 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002207 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002208
John McCallf871d0c2010-08-07 06:22:56 +00002209 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002210 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2211 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002212 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002213 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002214
John Wiegley429bb272011-04-08 18:41:53 +00002215 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2216 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002217}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002218
John McCallf7a1a742009-11-24 19:00:30 +00002219bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002220 const LookupResult &R,
2221 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002222 // Only when used directly as the postfix-expression of a call.
2223 if (!HasTrailingLParen)
2224 return false;
2225
2226 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002227 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002228 return false;
2229
2230 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002231 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002232 return false;
2233
2234 // Turn off ADL when we find certain kinds of declarations during
2235 // normal lookup:
2236 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2237 NamedDecl *D = *I;
2238
2239 // C++0x [basic.lookup.argdep]p3:
2240 // -- a declaration of a class member
2241 // Since using decls preserve this property, we check this on the
2242 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002243 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002244 return false;
2245
2246 // C++0x [basic.lookup.argdep]p3:
2247 // -- a block-scope function declaration that is not a
2248 // using-declaration
2249 // NOTE: we also trigger this for function templates (in fact, we
2250 // don't check the decl type at all, since all other decl types
2251 // turn off ADL anyway).
2252 if (isa<UsingShadowDecl>(D))
2253 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2254 else if (D->getDeclContext()->isFunctionOrMethod())
2255 return false;
2256
2257 // C++0x [basic.lookup.argdep]p3:
2258 // -- a declaration that is neither a function or a function
2259 // template
2260 // And also for builtin functions.
2261 if (isa<FunctionDecl>(D)) {
2262 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2263
2264 // But also builtin functions.
2265 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2266 return false;
2267 } else if (!isa<FunctionTemplateDecl>(D))
2268 return false;
2269 }
2270
2271 return true;
2272}
2273
2274
John McCallba135432009-11-21 08:51:07 +00002275/// Diagnoses obvious problems with the use of the given declaration
2276/// as an expression. This is only actually called for lookups that
2277/// were not overloaded, and it doesn't promise that the declaration
2278/// will in fact be used.
2279static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002280 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002281 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2282 return true;
2283 }
2284
2285 if (isa<ObjCInterfaceDecl>(D)) {
2286 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2287 return true;
2288 }
2289
2290 if (isa<NamespaceDecl>(D)) {
2291 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2292 return true;
2293 }
2294
2295 return false;
2296}
2297
John McCall60d7b3a2010-08-24 06:29:42 +00002298ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002299Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002300 LookupResult &R,
2301 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002302 // If this is a single, fully-resolved result and we don't need ADL,
2303 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002304 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002305 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2306 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002307
2308 // We only need to check the declaration if there's exactly one
2309 // result, because in the overloaded case the results can only be
2310 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002311 if (R.isSingleResult() &&
2312 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002313 return ExprError();
2314
John McCallc373d482010-01-27 01:50:18 +00002315 // Otherwise, just build an unresolved lookup expression. Suppress
2316 // any lookup-related diagnostics; we'll hash these out later, when
2317 // we've picked a target.
2318 R.suppressDiagnostics();
2319
John McCallba135432009-11-21 08:51:07 +00002320 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002321 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002322 SS.getWithLocInContext(Context),
2323 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002324 NeedsADL, R.isOverloadedResult(),
2325 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002326
2327 return Owned(ULE);
2328}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002329
John McCallba135432009-11-21 08:51:07 +00002330/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002331ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002332Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002333 const DeclarationNameInfo &NameInfo,
2334 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002335 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002336 assert(!isa<FunctionTemplateDecl>(D) &&
2337 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002338
Abramo Bagnara25777432010-08-11 22:01:17 +00002339 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002340 if (CheckDeclInExpr(*this, Loc, D))
2341 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002342
Douglas Gregor9af2f522009-12-01 16:58:18 +00002343 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2344 // Specifically diagnose references to class templates that are missing
2345 // a template argument list.
2346 Diag(Loc, diag::err_template_decl_ref)
2347 << Template << SS.getRange();
2348 Diag(Template->getLocation(), diag::note_template_decl_here);
2349 return ExprError();
2350 }
2351
2352 // Make sure that we're referring to a value.
2353 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2354 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002355 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002356 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002357 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002358 return ExprError();
2359 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002360
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002361 // Check whether this declaration can be used. Note that we suppress
2362 // this check when we're going to perform argument-dependent lookup
2363 // on this function name, because this might not be the function
2364 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002365 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002366 return ExprError();
2367
Steve Naroffdd972f22008-09-05 22:11:13 +00002368 // Only create DeclRefExpr's for valid Decl's.
2369 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002370 return ExprError();
2371
John McCall5808ce42011-02-03 08:15:49 +00002372 // Handle members of anonymous structs and unions. If we got here,
2373 // and the reference is to a class member indirect field, then this
2374 // must be the subject of a pointer-to-member expression.
2375 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2376 if (!indirectField->isCXXClassMember())
2377 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2378 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002379
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002380 {
John McCall76a40212011-02-09 01:13:10 +00002381 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002382 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002383
2384 switch (D->getKind()) {
2385 // Ignore all the non-ValueDecl kinds.
2386#define ABSTRACT_DECL(kind)
2387#define VALUE(type, base)
2388#define DECL(type, base) \
2389 case Decl::type:
2390#include "clang/AST/DeclNodes.inc"
2391 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002392
2393 // These shouldn't make it here.
2394 case Decl::ObjCAtDefsField:
2395 case Decl::ObjCIvar:
2396 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002397
2398 // Enum constants are always r-values and never references.
2399 // Unresolved using declarations are dependent.
2400 case Decl::EnumConstant:
2401 case Decl::UnresolvedUsingValue:
2402 valueKind = VK_RValue;
2403 break;
2404
2405 // Fields and indirect fields that got here must be for
2406 // pointer-to-member expressions; we just call them l-values for
2407 // internal consistency, because this subexpression doesn't really
2408 // exist in the high-level semantics.
2409 case Decl::Field:
2410 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002411 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002412 "building reference to field in C?");
2413
2414 // These can't have reference type in well-formed programs, but
2415 // for internal consistency we do this anyway.
2416 type = type.getNonReferenceType();
2417 valueKind = VK_LValue;
2418 break;
2419
2420 // Non-type template parameters are either l-values or r-values
2421 // depending on the type.
2422 case Decl::NonTypeTemplateParm: {
2423 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2424 type = reftype->getPointeeType();
2425 valueKind = VK_LValue; // even if the parameter is an r-value reference
2426 break;
2427 }
2428
2429 // For non-references, we need to strip qualifiers just in case
2430 // the template parameter was declared as 'const int' or whatever.
2431 valueKind = VK_RValue;
2432 type = type.getUnqualifiedType();
2433 break;
2434 }
2435
2436 case Decl::Var:
2437 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002438 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002439 !type.hasQualifiers() &&
2440 type->isVoidType()) {
2441 valueKind = VK_RValue;
2442 break;
2443 }
2444 // fallthrough
2445
2446 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002447 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002448 // These are always l-values.
2449 valueKind = VK_LValue;
2450 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002451
Douglas Gregor68932842012-02-18 05:51:20 +00002452 // FIXME: Does the addition of const really only apply in
2453 // potentially-evaluated contexts? Since the variable isn't actually
2454 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002455 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002456 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2457 if (!CapturedType.isNull())
2458 type = CapturedType;
2459 }
2460
John McCall76a40212011-02-09 01:13:10 +00002461 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002462 }
2463
John McCall76a40212011-02-09 01:13:10 +00002464 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002465 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2466 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2467 type = Context.BuiltinFnTy;
2468 valueKind = VK_RValue;
2469 break;
2470 }
2471 }
2472
John McCall755d8492011-04-12 00:42:48 +00002473 const FunctionType *fty = type->castAs<FunctionType>();
2474
2475 // If we're referring to a function with an __unknown_anytype
2476 // result type, make the entire expression __unknown_anytype.
2477 if (fty->getResultType() == Context.UnknownAnyTy) {
2478 type = Context.UnknownAnyTy;
2479 valueKind = VK_RValue;
2480 break;
2481 }
2482
John McCall76a40212011-02-09 01:13:10 +00002483 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002484 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002485 valueKind = VK_LValue;
2486 break;
2487 }
2488
2489 // C99 DR 316 says that, if a function type comes from a
2490 // function definition (without a prototype), that type is only
2491 // used for checking compatibility. Therefore, when referencing
2492 // the function, we pretend that we don't have the full function
2493 // type.
John McCall755d8492011-04-12 00:42:48 +00002494 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2495 isa<FunctionProtoType>(fty))
2496 type = Context.getFunctionNoProtoType(fty->getResultType(),
2497 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002498
2499 // Functions are r-values in C.
2500 valueKind = VK_RValue;
2501 break;
2502 }
2503
2504 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002505 // If we're referring to a method with an __unknown_anytype
2506 // result type, make the entire expression __unknown_anytype.
2507 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002508 if (const FunctionProtoType *proto
2509 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002510 if (proto->getResultType() == Context.UnknownAnyTy) {
2511 type = Context.UnknownAnyTy;
2512 valueKind = VK_RValue;
2513 break;
2514 }
2515
John McCall76a40212011-02-09 01:13:10 +00002516 // C++ methods are l-values if static, r-values if non-static.
2517 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2518 valueKind = VK_LValue;
2519 break;
2520 }
2521 // fallthrough
2522
2523 case Decl::CXXConversion:
2524 case Decl::CXXDestructor:
2525 case Decl::CXXConstructor:
2526 valueKind = VK_RValue;
2527 break;
2528 }
2529
2530 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2531 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002532}
2533
John McCall755d8492011-04-12 00:42:48 +00002534ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002535 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002536
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002538 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002539 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2540 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002541 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002542 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002543 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002544
Chris Lattnerfa28b302008-01-12 08:14:25 +00002545 // Pre-defined identifiers are of type char[x], where x is the length of the
2546 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002547
Anders Carlsson3a082d82009-09-08 18:24:21 +00002548 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002549 if (!currentDecl && getCurBlock())
2550 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002551 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002552 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002553 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002554 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002555
Anders Carlsson773f3972009-09-11 01:22:35 +00002556 QualType ResTy;
2557 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2558 ResTy = Context.DependentTy;
2559 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002560 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002561
Anders Carlsson773f3972009-09-11 01:22:35 +00002562 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002563 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002564 ResTy = Context.WCharTy.withConst();
2565 else
2566 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002567 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2568 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002569 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002570}
2571
Richard Smith36f5cfe2012-03-09 08:00:36 +00002572ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002573 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002574 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002575 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002576 if (Invalid)
2577 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002578
Benjamin Kramerddeea562010-02-27 13:44:12 +00002579 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002580 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002581 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002582 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002583
Chris Lattnere8337df2009-12-30 21:19:39 +00002584 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002585 if (Literal.isWide())
2586 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002587 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002588 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002589 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002590 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002591 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002592 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002593 else
2594 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002595
Douglas Gregor5cee1192011-07-27 05:40:30 +00002596 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2597 if (Literal.isWide())
2598 Kind = CharacterLiteral::Wide;
2599 else if (Literal.isUTF16())
2600 Kind = CharacterLiteral::UTF16;
2601 else if (Literal.isUTF32())
2602 Kind = CharacterLiteral::UTF32;
2603
Richard Smithdd66be72012-03-08 01:34:56 +00002604 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2605 Tok.getLocation());
2606
2607 if (Literal.getUDSuffix().empty())
2608 return Owned(Lit);
2609
2610 // We're building a user-defined literal.
2611 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2612 SourceLocation UDSuffixLoc =
2613 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2614
Richard Smith36f5cfe2012-03-09 08:00:36 +00002615 // Make sure we're allowed user-defined literals here.
2616 if (!UDLScope)
2617 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2618
Richard Smithdd66be72012-03-08 01:34:56 +00002619 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2620 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002621 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2622 llvm::makeArrayRef(&Lit, 1),
2623 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002624}
2625
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002626ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2627 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2628 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2629 Context.IntTy, Loc));
2630}
2631
Richard Smithb453ad32012-03-08 08:45:32 +00002632static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2633 QualType Ty, SourceLocation Loc) {
2634 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2635
2636 using llvm::APFloat;
2637 APFloat Val(Format);
2638
2639 APFloat::opStatus result = Literal.GetFloatValue(Val);
2640
2641 // Overflow is always an error, but underflow is only an error if
2642 // we underflowed to zero (APFloat reports denormals as underflow).
2643 if ((result & APFloat::opOverflow) ||
2644 ((result & APFloat::opUnderflow) && Val.isZero())) {
2645 unsigned diagnostic;
2646 SmallString<20> buffer;
2647 if (result & APFloat::opOverflow) {
2648 diagnostic = diag::warn_float_overflow;
2649 APFloat::getLargest(Format).toString(buffer);
2650 } else {
2651 diagnostic = diag::warn_float_underflow;
2652 APFloat::getSmallest(Format).toString(buffer);
2653 }
2654
2655 S.Diag(Loc, diagnostic)
2656 << Ty
2657 << StringRef(buffer.data(), buffer.size());
2658 }
2659
2660 bool isExact = (result == APFloat::opOK);
2661 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2662}
2663
Richard Smith36f5cfe2012-03-09 08:00:36 +00002664ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002665 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002666 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002668 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002669 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 }
Ted Kremenek28396602009-01-13 23:19:12 +00002671
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002672 SmallString<128> SpellingBuffer;
2673 // NumericLiteralParser wants to overread by one character. Add padding to
2674 // the buffer in case the token is copied to the buffer. If getSpelling()
2675 // returns a StringRef to the memory buffer, it should have a null char at
2676 // the EOF, so it is also safe.
2677 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002678
Reid Spencer5f016e22007-07-11 17:01:13 +00002679 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002680 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002681 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002682 if (Invalid)
2683 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002684
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002685 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002687 return ExprError();
2688
Richard Smithb453ad32012-03-08 08:45:32 +00002689 if (Literal.hasUDSuffix()) {
2690 // We're building a user-defined literal.
2691 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2692 SourceLocation UDSuffixLoc =
2693 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2694
Richard Smith36f5cfe2012-03-09 08:00:36 +00002695 // Make sure we're allowed user-defined literals here.
2696 if (!UDLScope)
2697 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002698
Richard Smith36f5cfe2012-03-09 08:00:36 +00002699 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002700 if (Literal.isFloatingLiteral()) {
2701 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2702 // long double, the literal is treated as a call of the form
2703 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002704 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002705 } else {
2706 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2707 // unsigned long long, the literal is treated as a call of the form
2708 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002709 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002710 }
2711
Richard Smith36f5cfe2012-03-09 08:00:36 +00002712 DeclarationName OpName =
2713 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2714 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2715 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2716
2717 // Perform literal operator lookup to determine if we're building a raw
2718 // literal or a cooked one.
2719 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2720 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2721 /*AllowRawAndTemplate*/true)) {
2722 case LOLR_Error:
2723 return ExprError();
2724
2725 case LOLR_Cooked: {
2726 Expr *Lit;
2727 if (Literal.isFloatingLiteral()) {
2728 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2729 } else {
2730 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2731 if (Literal.GetIntegerValue(ResultVal))
2732 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2733 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2734 Tok.getLocation());
2735 }
2736 return BuildLiteralOperatorCall(R, OpNameInfo,
2737 llvm::makeArrayRef(&Lit, 1),
2738 Tok.getLocation());
2739 }
2740
2741 case LOLR_Raw: {
2742 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2743 // literal is treated as a call of the form
2744 // operator "" X ("n")
2745 SourceLocation TokLoc = Tok.getLocation();
2746 unsigned Length = Literal.getUDSuffixOffset();
2747 QualType StrTy = Context.getConstantArrayType(
2748 Context.CharTy, llvm::APInt(32, Length + 1),
2749 ArrayType::Normal, 0);
2750 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002751 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002752 /*Pascal*/false, StrTy, &TokLoc, 1);
2753 return BuildLiteralOperatorCall(R, OpNameInfo,
2754 llvm::makeArrayRef(&Lit, 1), TokLoc);
2755 }
2756
2757 case LOLR_Template:
2758 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2759 // template), L is treated as a call fo the form
2760 // operator "" X <'c1', 'c2', ... 'ck'>()
2761 // where n is the source character sequence c1 c2 ... ck.
2762 TemplateArgumentListInfo ExplicitArgs;
2763 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2764 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2765 llvm::APSInt Value(CharBits, CharIsUnsigned);
2766 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002767 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002768 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002769 TemplateArgumentLocInfo ArgInfo;
2770 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2771 }
2772 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2773 Tok.getLocation(), &ExplicitArgs);
2774 }
2775
2776 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002777 }
2778
Chris Lattner5d661452007-08-26 03:42:43 +00002779 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002780
Chris Lattner5d661452007-08-26 03:42:43 +00002781 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002782 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002783 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002784 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002785 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002786 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002787 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002788 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002789
Richard Smithb453ad32012-03-08 08:45:32 +00002790 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002791
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002792 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002793 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002794 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002795 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002796 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002797 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002798 }
2799 }
Chris Lattner5d661452007-08-26 03:42:43 +00002800 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002801 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002802 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002803 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002804
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002805 // 'long long' is a C99 or C++11 feature.
2806 if (!getLangOpts().C99 && Literal.isLongLong) {
2807 if (getLangOpts().CPlusPlus)
2808 Diag(Tok.getLocation(),
2809 getLangOpts().CPlusPlus0x ?
2810 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2811 else
2812 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2813 }
Neil Boothb9449512007-08-29 22:00:19 +00002814
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002816 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2817 // The microsoft literal suffix extensions support 128-bit literals, which
2818 // may be wider than [u]intmax_t.
2819 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2820 MaxWidth = 128;
2821 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002822
Reid Spencer5f016e22007-07-11 17:01:13 +00002823 if (Literal.GetIntegerValue(ResultVal)) {
2824 // If this value didn't fit into uintmax_t, warn and force to ull.
2825 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002826 Ty = Context.UnsignedLongLongTy;
2827 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002828 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 } else {
2830 // If this value fits into a ULL, try to figure out what else it fits into
2831 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002832
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2834 // be an unsigned int.
2835 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2836
2837 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002838 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002839 if (!Literal.isLong && !Literal.isLongLong) {
2840 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002841 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002842
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 // Does it fit in a unsigned int?
2844 if (ResultVal.isIntN(IntSize)) {
2845 // Does it fit in a signed int?
2846 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002847 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002849 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002850 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002851 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002852 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002853
Reid Spencer5f016e22007-07-11 17:01:13 +00002854 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002855 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002856 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002857
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 // Does it fit in a unsigned long?
2859 if (ResultVal.isIntN(LongSize)) {
2860 // Does it fit in a signed long?
2861 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002862 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002864 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002865 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002866 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002867 }
2868
Stephen Canonb9e05f12012-05-03 22:49:43 +00002869 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002870 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002871 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002872
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 // Does it fit in a unsigned long long?
2874 if (ResultVal.isIntN(LongLongSize)) {
2875 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002876 // To be compatible with MSVC, hex integer literals ending with the
2877 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002878 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002879 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002880 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002882 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002883 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002884 }
2885 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002886
2887 // If it doesn't fit in unsigned long long, and we're using Microsoft
2888 // extensions, then its a 128-bit integer literal.
2889 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2890 if (Literal.isUnsigned)
2891 Ty = Context.UnsignedInt128Ty;
2892 else
2893 Ty = Context.Int128Ty;
2894 Width = 128;
2895 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002896
Reid Spencer5f016e22007-07-11 17:01:13 +00002897 // If we still couldn't decide a type, we probably have something that
2898 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002899 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002901 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002902 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002903 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002904
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002905 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002906 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002907 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002908 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002910
Chris Lattner5d661452007-08-26 03:42:43 +00002911 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2912 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002913 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002914 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002915
2916 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002917}
2918
Richard Trieuccd891a2011-09-09 01:45:06 +00002919ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002920 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002921 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002922}
2923
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002924static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2925 SourceLocation Loc,
2926 SourceRange ArgRange) {
2927 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2928 // scalar or vector data type argument..."
2929 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2930 // type (C99 6.2.5p18) or void.
2931 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2932 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2933 << T << ArgRange;
2934 return true;
2935 }
2936
2937 assert((T->isVoidType() || !T->isIncompleteType()) &&
2938 "Scalar types should always be complete");
2939 return false;
2940}
2941
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002942static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2943 SourceLocation Loc,
2944 SourceRange ArgRange,
2945 UnaryExprOrTypeTrait TraitKind) {
2946 // C99 6.5.3.4p1:
2947 if (T->isFunctionType()) {
2948 // alignof(function) is allowed as an extension.
2949 if (TraitKind == UETT_SizeOf)
2950 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2951 return false;
2952 }
2953
2954 // Allow sizeof(void)/alignof(void) as an extension.
2955 if (T->isVoidType()) {
2956 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2957 return false;
2958 }
2959
2960 return true;
2961}
2962
2963static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2964 SourceLocation Loc,
2965 SourceRange ArgRange,
2966 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002967 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2968 // runtime doesn't allow it.
2969 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002970 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2971 << T << (TraitKind == UETT_SizeOf)
2972 << ArgRange;
2973 return true;
2974 }
2975
2976 return false;
2977}
2978
Chandler Carruth9d342d02011-05-26 08:53:10 +00002979/// \brief Check the constrains on expression operands to unary type expression
2980/// and type traits.
2981///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002982/// Completes any types necessary and validates the constraints on the operand
2983/// expression. The logic mostly mirrors the type-based overload, but may modify
2984/// the expression as it completes the type for that expression through template
2985/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002986bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002987 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002988 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002989
2990 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2991 // the result is the size of the referenced type."
2992 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2993 // result shall be the alignment of the referenced type."
2994 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2995 ExprTy = Ref->getPointeeType();
2996
2997 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002998 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2999 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003000
3001 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003002 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3003 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003004 return false;
3005
Richard Trieuccd891a2011-09-09 01:45:06 +00003006 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00003007 diag::err_sizeof_alignof_incomplete_type,
3008 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003009 return true;
3010
3011 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003012 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003013 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3014 ExprTy = Ref->getPointeeType();
3015
Richard Trieuccd891a2011-09-09 01:45:06 +00003016 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3017 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003018 return true;
3019
Nico Webercf739922011-06-15 02:47:03 +00003020 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003021 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003022 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3023 QualType OType = PVD->getOriginalType();
3024 QualType Type = PVD->getType();
3025 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003026 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003027 << Type << OType;
3028 Diag(PVD->getLocation(), diag::note_declared_at);
3029 }
3030 }
3031 }
3032 }
3033
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003034 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003035}
3036
3037/// \brief Check the constraints on operands to unary expression and type
3038/// traits.
3039///
3040/// This will complete any types necessary, and validate the various constraints
3041/// on those operands.
3042///
Reid Spencer5f016e22007-07-11 17:01:13 +00003043/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003044/// C99 6.3.2.1p[2-4] all state:
3045/// Except when it is the operand of the sizeof operator ...
3046///
3047/// C++ [expr.sizeof]p4
3048/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3049/// standard conversions are not applied to the operand of sizeof.
3050///
3051/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003052bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003053 SourceLocation OpLoc,
3054 SourceRange ExprRange,
3055 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003056 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003057 return false;
3058
Sebastian Redl5d484e82009-11-23 17:18:46 +00003059 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3060 // the result is the size of the referenced type."
3061 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3062 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003063 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3064 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003065
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003066 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003067 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003068
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003069 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003070 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003071 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003072 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Richard Trieuccd891a2011-09-09 01:45:06 +00003074 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003075 diag::err_sizeof_alignof_incomplete_type,
3076 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003077 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Richard Trieuccd891a2011-09-09 01:45:06 +00003079 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003080 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003081 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Chris Lattner1efaa952009-04-24 00:30:45 +00003083 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003084}
3085
Chandler Carruth9d342d02011-05-26 08:53:10 +00003086static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003087 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003088
Mike Stump1eb44332009-09-09 15:08:12 +00003089 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003090 if (isa<DeclRefExpr>(E))
3091 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003092
3093 // Cannot know anything else if the expression is dependent.
3094 if (E->isTypeDependent())
3095 return false;
3096
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003097 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003098 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3099 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003100 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003101 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003102
3103 // Alignment of a field access is always okay, so long as it isn't a
3104 // bit-field.
3105 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003106 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003107 return false;
3108
Chandler Carruth9d342d02011-05-26 08:53:10 +00003109 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003110}
3111
Chandler Carruth9d342d02011-05-26 08:53:10 +00003112bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003113 E = E->IgnoreParens();
3114
3115 // Cannot know anything else if the expression is dependent.
3116 if (E->isTypeDependent())
3117 return false;
3118
Chandler Carruth9d342d02011-05-26 08:53:10 +00003119 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003120}
3121
Douglas Gregorba498172009-03-13 21:01:28 +00003122/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003123ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003124Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3125 SourceLocation OpLoc,
3126 UnaryExprOrTypeTrait ExprKind,
3127 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003128 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003129 return ExprError();
3130
John McCalla93c9342009-12-07 02:54:59 +00003131 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003132
Douglas Gregorba498172009-03-13 21:01:28 +00003133 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003134 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003135 return ExprError();
3136
3137 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003138 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3139 Context.getSizeType(),
3140 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003141}
3142
3143/// \brief Build a sizeof or alignof expression given an expression
3144/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003145ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003146Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3147 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003148 ExprResult PE = CheckPlaceholderExpr(E);
3149 if (PE.isInvalid())
3150 return ExprError();
3151
3152 E = PE.get();
3153
Douglas Gregorba498172009-03-13 21:01:28 +00003154 // Verify that the operand is valid.
3155 bool isInvalid = false;
3156 if (E->isTypeDependent()) {
3157 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003158 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003159 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003160 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003161 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003162 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003163 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003164 isInvalid = true;
3165 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003166 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003167 }
3168
3169 if (isInvalid)
3170 return ExprError();
3171
Eli Friedman71b8fb52012-01-21 01:01:51 +00003172 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3173 PE = TranformToPotentiallyEvaluated(E);
3174 if (PE.isInvalid()) return ExprError();
3175 E = PE.take();
3176 }
3177
Douglas Gregorba498172009-03-13 21:01:28 +00003178 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003179 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003180 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003181 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003182}
3183
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003184/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3185/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003186/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003187ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003188Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003189 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003190 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003191 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003192 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003193
Richard Trieuccd891a2011-09-09 01:45:06 +00003194 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003195 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003196 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003197 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003198 }
Sebastian Redl05189992008-11-11 17:56:53 +00003199
Douglas Gregorba498172009-03-13 21:01:28 +00003200 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003201 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003202 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003203}
3204
John Wiegley429bb272011-04-08 18:41:53 +00003205static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003206 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003207 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003208 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003209
John McCallf6a16482010-12-04 03:47:34 +00003210 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003211 if (V.get()->getObjectKind() != OK_Ordinary) {
3212 V = S.DefaultLvalueConversion(V.take());
3213 if (V.isInvalid())
3214 return QualType();
3215 }
John McCallf6a16482010-12-04 03:47:34 +00003216
Chris Lattnercc26ed72007-08-26 05:39:26 +00003217 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003218 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003219 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003220
Chris Lattnercc26ed72007-08-26 05:39:26 +00003221 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003222 if (V.get()->getType()->isArithmeticType())
3223 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003224
John McCall2cd11fe2010-10-12 02:09:17 +00003225 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003226 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003227 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003228 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003229 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003230 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003231 }
3232
Chris Lattnercc26ed72007-08-26 05:39:26 +00003233 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003234 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003235 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003236 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003237}
3238
3239
Reid Spencer5f016e22007-07-11 17:01:13 +00003240
John McCall60d7b3a2010-08-24 06:29:42 +00003241ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003242Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003243 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003244 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003245 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003246 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003247 case tok::plusplus: Opc = UO_PostInc; break;
3248 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003249 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003250
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003251 // Since this might is a postfix expression, get rid of ParenListExprs.
3252 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3253 if (Result.isInvalid()) return ExprError();
3254 Input = Result.take();
3255
John McCall9ae2f072010-08-23 23:25:46 +00003256 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003257}
3258
John McCall1503f0d2012-07-31 05:14:30 +00003259/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3260///
3261/// \return true on error
3262static bool checkArithmeticOnObjCPointer(Sema &S,
3263 SourceLocation opLoc,
3264 Expr *op) {
3265 assert(op->getType()->isObjCObjectPointerType());
3266 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3267 return false;
3268
3269 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3270 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3271 << op->getSourceRange();
3272 return true;
3273}
3274
John McCall60d7b3a2010-08-24 06:29:42 +00003275ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003276Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3277 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003278 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003279 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003280 if (Result.isInvalid()) return ExprError();
3281 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003282
John McCall9ae2f072010-08-23 23:25:46 +00003283 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003284
David Blaikie4e4d0842012-03-11 07:00:24 +00003285 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003286 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003287 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003288 Context.DependentTy,
3289 VK_LValue, OK_Ordinary,
3290 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003291 }
3292
David Blaikie4e4d0842012-03-11 07:00:24 +00003293 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003294 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003295 LHSExp->getType()->isEnumeralType() ||
3296 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003297 RHSExp->getType()->isEnumeralType()) &&
3298 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003299 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003300 }
3301
John McCall9ae2f072010-08-23 23:25:46 +00003302 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003303}
3304
John McCall60d7b3a2010-08-24 06:29:42 +00003305ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003306Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003307 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003308 Expr *LHSExp = Base;
3309 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003310
Chris Lattner12d9ff62007-07-16 00:14:47 +00003311 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003312 if (!LHSExp->getType()->getAs<VectorType>()) {
3313 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3314 if (Result.isInvalid())
3315 return ExprError();
3316 LHSExp = Result.take();
3317 }
3318 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3319 if (Result.isInvalid())
3320 return ExprError();
3321 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003322
Chris Lattner12d9ff62007-07-16 00:14:47 +00003323 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003324 ExprValueKind VK = VK_LValue;
3325 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003326
Reid Spencer5f016e22007-07-11 17:01:13 +00003327 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003328 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003329 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003330 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003331 Expr *BaseExpr, *IndexExpr;
3332 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003333 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3334 BaseExpr = LHSExp;
3335 IndexExpr = RHSExp;
3336 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003337 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003338 BaseExpr = LHSExp;
3339 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003340 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003341 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003342 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003343 BaseExpr = LHSExp;
3344 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003345
3346 // Use custom logic if this should be the pseudo-object subscript
3347 // expression.
3348 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3349 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3350
Steve Naroff14108da2009-07-10 23:34:53 +00003351 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003352 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3353 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3354 << ResultType << BaseExpr->getSourceRange();
3355 return ExprError();
3356 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003357 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3358 // Handle the uncommon case of "123[Ptr]".
3359 BaseExpr = RHSExp;
3360 IndexExpr = LHSExp;
3361 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003362 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003363 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003364 // Handle the uncommon case of "123[Ptr]".
3365 BaseExpr = RHSExp;
3366 IndexExpr = LHSExp;
3367 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003368 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3369 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3370 << ResultType << BaseExpr->getSourceRange();
3371 return ExprError();
3372 }
John McCall183700f2009-09-21 23:43:11 +00003373 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003374 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003375 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003376 VK = LHSExp->getValueKind();
3377 if (VK != VK_RValue)
3378 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003379
Chris Lattner12d9ff62007-07-16 00:14:47 +00003380 // FIXME: need to deal with const...
3381 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003382 } else if (LHSTy->isArrayType()) {
3383 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003384 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003385 // wasn't promoted because of the C90 rule that doesn't
3386 // allow promoting non-lvalue arrays. Warn, then
3387 // force the promotion here.
3388 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3389 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003390 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3391 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003392 LHSTy = LHSExp->getType();
3393
3394 BaseExpr = LHSExp;
3395 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003396 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003397 } else if (RHSTy->isArrayType()) {
3398 // Same as previous, except for 123[f().a] case
3399 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3400 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003401 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3402 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003403 RHSTy = RHSExp->getType();
3404
3405 BaseExpr = RHSExp;
3406 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003407 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003408 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003409 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3410 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003411 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003412 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003413 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003414 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3415 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003416
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003417 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003418 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3419 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003420 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3421
Douglas Gregore7450f52009-03-24 19:52:54 +00003422 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003423 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3424 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003425 // incomplete types are not object types.
3426 if (ResultType->isFunctionType()) {
3427 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3428 << ResultType << BaseExpr->getSourceRange();
3429 return ExprError();
3430 }
Mike Stump1eb44332009-09-09 15:08:12 +00003431
David Blaikie4e4d0842012-03-11 07:00:24 +00003432 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003433 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003434 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3435 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003436
3437 // C forbids expressions of unqualified void type from being l-values.
3438 // See IsCForbiddenLValueType.
3439 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003440 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003441 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003442 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003443 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003444
John McCall09431682010-11-18 19:01:18 +00003445 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003446 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003447
Mike Stumpeed9cac2009-02-19 03:04:26 +00003448 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003449 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003450}
3451
John McCall60d7b3a2010-08-24 06:29:42 +00003452ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003453 FunctionDecl *FD,
3454 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003455 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003456 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003457 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003458 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003459 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003460 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003461 return ExprError();
3462 }
3463
3464 if (Param->hasUninstantiatedDefaultArg()) {
3465 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003466
Richard Smithadb1d4c2012-07-22 23:45:10 +00003467 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3468 Param);
3469
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003470 // Instantiate the expression.
3471 MultiLevelTemplateArgumentList ArgList
3472 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003473
Nico Weber08e41a62010-11-29 18:19:25 +00003474 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003475 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003476 InstantiatingTemplate Inst(*this, CallLoc, Param,
3477 ArrayRef<TemplateArgument>(Innermost.first,
3478 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003479 if (Inst)
3480 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003481
Nico Weber08e41a62010-11-29 18:19:25 +00003482 ExprResult Result;
3483 {
3484 // C++ [dcl.fct.default]p5:
3485 // The names in the [default argument] expression are bound, and
3486 // the semantic constraints are checked, at the point where the
3487 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003488 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003489 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003490 Result = SubstExpr(UninstExpr, ArgList);
3491 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003492 if (Result.isInvalid())
3493 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003494
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003495 // Check the expression as an initializer for the parameter.
3496 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003497 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003498 InitializationKind Kind
3499 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003500 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003501 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003502
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003503 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003504 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003505 if (Result.isInvalid())
3506 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003507
David Blaikiec1c07252012-04-30 18:21:31 +00003508 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003509 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003510 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003511 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003512 }
3513
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003514 // If the default expression creates temporaries, we need to
3515 // push them to the current stack of expression temporaries so they'll
3516 // be properly destroyed.
3517 // FIXME: We should really be rebuilding the default argument with new
3518 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003519 // We don't need to do that with block decls, though, because
3520 // blocks in default argument expression can never capture anything.
3521 if (isa<ExprWithCleanups>(Param->getInit())) {
3522 // Set the "needs cleanups" bit regardless of whether there are
3523 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003524 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003525
3526 // Append all the objects to the cleanup list. Right now, this
3527 // should always be a no-op, because blocks in default argument
3528 // expressions should never be able to capture anything.
3529 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3530 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003531 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003532
3533 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003534 // Just mark all of the declarations in this potentially-evaluated expression
3535 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003536 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3537 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003538 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003539}
3540
Richard Smith831421f2012-06-25 20:30:08 +00003541
3542Sema::VariadicCallType
3543Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3544 Expr *Fn) {
3545 if (Proto && Proto->isVariadic()) {
3546 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3547 return VariadicConstructor;
3548 else if (Fn && Fn->getType()->isBlockPointerType())
3549 return VariadicBlock;
3550 else if (FDecl) {
3551 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3552 if (Method->isInstance())
3553 return VariadicMethod;
3554 }
3555 return VariadicFunction;
3556 }
3557 return VariadicDoesNotApply;
3558}
3559
Douglas Gregor88a35142008-12-22 05:46:06 +00003560/// ConvertArgumentsForCall - Converts the arguments specified in
3561/// Args/NumArgs to the parameter types of the function FDecl with
3562/// function prototype Proto. Call is the call expression itself, and
3563/// Fn is the function expression. For a C++ member function, this
3564/// routine does not attempt to convert the object argument. Returns
3565/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003566bool
3567Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003568 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003569 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003570 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003571 SourceLocation RParenLoc,
3572 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003573 // Bail out early if calling a builtin with custom typechecking.
3574 // We don't need to do this in the
3575 if (FDecl)
3576 if (unsigned ID = FDecl->getBuiltinID())
3577 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3578 return false;
3579
Mike Stumpeed9cac2009-02-19 03:04:26 +00003580 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003581 // assignment, to the types of the corresponding parameter, ...
3582 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003583 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003584 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003585 unsigned FnKind = Fn->getType()->isBlockPointerType()
3586 ? 1 /* block */
3587 : (IsExecConfig ? 3 /* kernel function (exec config) */
3588 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003589
Douglas Gregor88a35142008-12-22 05:46:06 +00003590 // If too few arguments are available (and we don't have default
3591 // arguments for the remaining parameters), don't make the call.
3592 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003593 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003594 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3595 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3596 ? diag::err_typecheck_call_too_few_args_one
3597 : diag::err_typecheck_call_too_few_args_at_least_one)
3598 << FnKind
3599 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3600 else
3601 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3602 ? diag::err_typecheck_call_too_few_args
3603 : diag::err_typecheck_call_too_few_args_at_least)
3604 << FnKind
3605 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003606
3607 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003608 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003609 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3610 << FDecl;
3611
3612 return true;
3613 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003614 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003615 }
3616
3617 // If too many are passed and not variadic, error on the extras and drop
3618 // them.
3619 if (NumArgs > NumArgsInProto) {
3620 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003621 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3622 Diag(Args[NumArgsInProto]->getLocStart(),
3623 MinArgs == NumArgsInProto
3624 ? diag::err_typecheck_call_too_many_args_one
3625 : diag::err_typecheck_call_too_many_args_at_most_one)
3626 << FnKind
3627 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3628 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3629 Args[NumArgs-1]->getLocEnd());
3630 else
3631 Diag(Args[NumArgsInProto]->getLocStart(),
3632 MinArgs == NumArgsInProto
3633 ? diag::err_typecheck_call_too_many_args
3634 : diag::err_typecheck_call_too_many_args_at_most)
3635 << FnKind
3636 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3637 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3638 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003639
3640 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003641 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003642 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3643 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003644
Douglas Gregor88a35142008-12-22 05:46:06 +00003645 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003646 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003647 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003648 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003649 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003650 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003651 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3652
Daniel Dunbar96a00142012-03-09 18:35:03 +00003653 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003654 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003655 if (Invalid)
3656 return true;
3657 unsigned TotalNumArgs = AllArgs.size();
3658 for (unsigned i = 0; i < TotalNumArgs; ++i)
3659 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003660
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003661 return false;
3662}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003663
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003664bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3665 FunctionDecl *FDecl,
3666 const FunctionProtoType *Proto,
3667 unsigned FirstProtoArg,
3668 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003669 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003670 VariadicCallType CallType,
3671 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003672 unsigned NumArgsInProto = Proto->getNumArgs();
3673 unsigned NumArgsToCheck = NumArgs;
3674 bool Invalid = false;
3675 if (NumArgs != NumArgsInProto)
3676 // Use default arguments for missing arguments
3677 NumArgsToCheck = NumArgsInProto;
3678 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003679 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003680 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003681 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003682
Douglas Gregor88a35142008-12-22 05:46:06 +00003683 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003684 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003685 if (ArgIx < NumArgs) {
3686 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003687
Daniel Dunbar96a00142012-03-09 18:35:03 +00003688 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003689 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003690 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003691 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003692
Douglas Gregora188ff22009-12-22 16:09:06 +00003693 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003694 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003695 if (FDecl && i < FDecl->getNumParams())
3696 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003697
John McCall5acb0c92011-10-17 18:40:02 +00003698 // Strip the unbridged-cast placeholder expression off, if applicable.
3699 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3700 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3701 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3702 Arg = stripARCUnbridgedCast(Arg);
3703
Douglas Gregora188ff22009-12-22 16:09:06 +00003704 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003705 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003706 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3707 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003708 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003709 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003710 Owned(Arg),
3711 /*TopLevelOfInitList=*/false,
3712 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003713 if (ArgE.isInvalid())
3714 return true;
3715
3716 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003717 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003718 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003719
John McCall60d7b3a2010-08-24 06:29:42 +00003720 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003721 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003722 if (ArgExpr.isInvalid())
3723 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003724
Anders Carlsson56c5e332009-08-25 03:49:14 +00003725 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003726 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003727
3728 // Check for array bounds violations for each argument to the call. This
3729 // check only triggers warnings when the argument isn't a more complex Expr
3730 // with its own checking, such as a BinaryOperator.
3731 CheckArrayAccess(Arg);
3732
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003733 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3734 CheckStaticArrayArgument(CallLoc, Param, Arg);
3735
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003736 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003737 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003738
Douglas Gregor88a35142008-12-22 05:46:06 +00003739 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003740 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003741 // Assume that extern "C" functions with variadic arguments that
3742 // return __unknown_anytype aren't *really* variadic.
3743 if (Proto->getResultType() == Context.UnknownAnyTy &&
3744 FDecl && FDecl->isExternC()) {
3745 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3746 ExprResult arg;
3747 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3748 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3749 else
3750 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3751 Invalid |= arg.isInvalid();
3752 AllArgs.push_back(arg.take());
3753 }
3754
3755 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3756 } else {
3757 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003758 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3759 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003760 Invalid |= Arg.isInvalid();
3761 AllArgs.push_back(Arg.take());
3762 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003763 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003764
3765 // Check for array bounds violations.
3766 for (unsigned i = ArgIx; i != NumArgs; ++i)
3767 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003768 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003769 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003770}
3771
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003772static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3773 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3774 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3775 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3776 << ATL->getLocalSourceRange();
3777}
3778
3779/// CheckStaticArrayArgument - If the given argument corresponds to a static
3780/// array parameter, check that it is non-null, and that if it is formed by
3781/// array-to-pointer decay, the underlying array is sufficiently large.
3782///
3783/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3784/// array type derivation, then for each call to the function, the value of the
3785/// corresponding actual argument shall provide access to the first element of
3786/// an array with at least as many elements as specified by the size expression.
3787void
3788Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3789 ParmVarDecl *Param,
3790 const Expr *ArgExpr) {
3791 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003792 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003793 return;
3794
3795 QualType OrigTy = Param->getOriginalType();
3796
3797 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3798 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3799 return;
3800
3801 if (ArgExpr->isNullPointerConstant(Context,
3802 Expr::NPC_NeverValueDependent)) {
3803 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3804 DiagnoseCalleeStaticArrayParam(*this, Param);
3805 return;
3806 }
3807
3808 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3809 if (!CAT)
3810 return;
3811
3812 const ConstantArrayType *ArgCAT =
3813 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3814 if (!ArgCAT)
3815 return;
3816
3817 if (ArgCAT->getSize().ult(CAT->getSize())) {
3818 Diag(CallLoc, diag::warn_static_array_too_small)
3819 << ArgExpr->getSourceRange()
3820 << (unsigned) ArgCAT->getSize().getZExtValue()
3821 << (unsigned) CAT->getSize().getZExtValue();
3822 DiagnoseCalleeStaticArrayParam(*this, Param);
3823 }
3824}
3825
John McCall755d8492011-04-12 00:42:48 +00003826/// Given a function expression of unknown-any type, try to rebuild it
3827/// to have a function type.
3828static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3829
Steve Narofff69936d2007-09-16 03:34:24 +00003830/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003831/// This provides the location of the left/right parens and a list of comma
3832/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003833ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003834Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003835 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003836 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003837 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003838 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003839 if (Result.isInvalid()) return ExprError();
3840 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003841
David Blaikie4e4d0842012-03-11 07:00:24 +00003842 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003843 // If this is a pseudo-destructor expression, build the call immediately.
3844 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003845 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003846 // Pseudo-destructor calls should not have any arguments.
3847 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003848 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003849 SourceRange(ArgExprs[0]->getLocStart(),
3850 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003851 }
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003853 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3854 Context.VoidTy, VK_RValue,
3855 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Douglas Gregor17330012009-02-04 15:01:18 +00003858 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003859 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003860 // FIXME: Will need to cache the results of name lookup (including ADL) in
3861 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003862 bool Dependent = false;
3863 if (Fn->isTypeDependent())
3864 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003865 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003866 Dependent = true;
3867
Peter Collingbournee08ce652011-02-09 21:07:24 +00003868 if (Dependent) {
3869 if (ExecConfig) {
3870 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003871 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003872 Context.DependentTy, VK_RValue, RParenLoc));
3873 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003874 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003875 Context.DependentTy, VK_RValue,
3876 RParenLoc));
3877 }
3878 }
Douglas Gregor17330012009-02-04 15:01:18 +00003879
3880 // Determine whether this is a call to an object (C++ [over.call.object]).
3881 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003882 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3883 ArgExprs.data(),
3884 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003885
John McCall755d8492011-04-12 00:42:48 +00003886 if (Fn->getType() == Context.UnknownAnyTy) {
3887 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3888 if (result.isInvalid()) return ExprError();
3889 Fn = result.take();
3890 }
3891
John McCall864c0412011-04-26 20:42:42 +00003892 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003893 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3894 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003895 }
John McCall864c0412011-04-26 20:42:42 +00003896 }
John McCall129e2df2009-11-30 22:42:35 +00003897
John McCall864c0412011-04-26 20:42:42 +00003898 // Check for overloaded calls. This can happen even in C due to extensions.
3899 if (Fn->getType() == Context.OverloadTy) {
3900 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3901
Douglas Gregoree697e62011-10-13 18:10:35 +00003902 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003903 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003904 OverloadExpr *ovl = find.Expression;
3905 if (isa<UnresolvedLookupExpr>(ovl)) {
3906 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003907 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3908 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003909 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003910 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3911 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003912 }
3913 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003914 }
3915
Douglas Gregorfa047642009-02-04 00:32:51 +00003916 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003917 if (Fn->getType() == Context.UnknownAnyTy) {
3918 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3919 if (result.isInvalid()) return ExprError();
3920 Fn = result.take();
3921 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003922
Eli Friedmanefa42f72009-12-26 03:35:45 +00003923 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003924
John McCall3b4294e2009-12-16 12:17:52 +00003925 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003926 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3927 if (UnOp->getOpcode() == UO_AddrOf)
3928 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3929
John McCall3b4294e2009-12-16 12:17:52 +00003930 if (isa<DeclRefExpr>(NakedFn))
3931 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003932 else if (isa<MemberExpr>(NakedFn))
3933 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003934
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003935 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3936 ArgExprs.size(), RParenLoc, ExecConfig,
3937 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003938}
3939
3940ExprResult
3941Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003942 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003943 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3944 if (!ConfigDecl)
3945 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3946 << "cudaConfigureCall");
3947 QualType ConfigQTy = ConfigDecl->getType();
3948
3949 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003950 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003951 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003952
Peter Collingbourne1f240762011-10-02 23:49:29 +00003953 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3954 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003955}
3956
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003957/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3958///
3959/// __builtin_astype( value, dst type )
3960///
Richard Trieuccd891a2011-09-09 01:45:06 +00003961ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003962 SourceLocation BuiltinLoc,
3963 SourceLocation RParenLoc) {
3964 ExprValueKind VK = VK_RValue;
3965 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003966 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3967 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003968 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3969 return ExprError(Diag(BuiltinLoc,
3970 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003971 << DstTy
3972 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003973 << E->getSourceRange());
3974 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003975 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003976}
3977
John McCall3b4294e2009-12-16 12:17:52 +00003978/// BuildResolvedCallExpr - Build a call to a resolved expression,
3979/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003980/// unary-convert to an expression of function-pointer or
3981/// block-pointer type.
3982///
3983/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003984ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003985Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3986 SourceLocation LParenLoc,
3987 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003988 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003989 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003990 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003991 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00003992
Chris Lattner04421082008-04-08 04:40:51 +00003993 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00003994 // We special-case function promotion here because we only allow promoting
3995 // builtin functions to function pointers in the callee of a call.
3996 ExprResult Result;
3997 if (BuiltinID &&
3998 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3999 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4000 CK_BuiltinFnToFnPtr).take();
4001 } else {
4002 Result = UsualUnaryConversions(Fn);
4003 }
John Wiegley429bb272011-04-08 18:41:53 +00004004 if (Result.isInvalid())
4005 return ExprError();
4006 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004007
Chris Lattner925e60d2007-12-28 05:29:59 +00004008 // Make the call expr early, before semantic checks. This guarantees cleanup
4009 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004010 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004011 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004012 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4013 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004014 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004015 Context.BoolTy,
4016 VK_RValue,
4017 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004018 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00004019 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004020 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004021 Context.BoolTy,
4022 VK_RValue,
4023 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004024
John McCall8e10f3b2011-02-26 05:39:39 +00004025 // Bail out early if calling a builtin with custom typechecking.
4026 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4027 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4028
John McCall1de4d4e2011-04-07 08:22:57 +00004029 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004030 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004031 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004032 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4033 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004034 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004035 if (FuncT == 0)
4036 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4037 << Fn->getType() << Fn->getSourceRange());
4038 } else if (const BlockPointerType *BPT =
4039 Fn->getType()->getAs<BlockPointerType>()) {
4040 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4041 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004042 // Handle calls to expressions of unknown-any type.
4043 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004044 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004045 if (rewrite.isInvalid()) return ExprError();
4046 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004047 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004048 goto retry;
4049 }
4050
Sebastian Redl0eb23302009-01-19 00:08:26 +00004051 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4052 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004053 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004054
David Blaikie4e4d0842012-03-11 07:00:24 +00004055 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004056 if (Config) {
4057 // CUDA: Kernel calls must be to global functions
4058 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4059 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4060 << FDecl->getName() << Fn->getSourceRange());
4061
4062 // CUDA: Kernel function must have 'void' return type
4063 if (!FuncT->getResultType()->isVoidType())
4064 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4065 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004066 } else {
4067 // CUDA: Calls to global functions must be configured
4068 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4069 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4070 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004071 }
4072 }
4073
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004074 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004075 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004076 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004077 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004078 return ExprError();
4079
Chris Lattner925e60d2007-12-28 05:29:59 +00004080 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004081 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004082 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004083
Richard Smith831421f2012-06-25 20:30:08 +00004084 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4085 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004086 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004087 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004088 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004089 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004090 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004091
Douglas Gregor74734d52009-04-02 15:37:10 +00004092 if (FDecl) {
4093 // Check if we have too few/too many template arguments, based
4094 // on our knowledge of the function definition.
4095 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004096 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004097 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004098 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004099 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4100 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004101 }
Douglas Gregor46542412010-10-25 20:39:23 +00004102
4103 // If the function we're calling isn't a function prototype, but we have
4104 // a function prototype from a prior declaratiom, use that prototype.
4105 if (!FDecl->hasPrototype())
4106 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004107 }
4108
Steve Naroffb291ab62007-08-28 23:30:39 +00004109 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004110 for (unsigned i = 0; i != NumArgs; i++) {
4111 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004112
4113 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004114 InitializedEntity Entity
4115 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004116 Proto->getArgType(i),
4117 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004118 ExprResult ArgE = PerformCopyInitialization(Entity,
4119 SourceLocation(),
4120 Owned(Arg));
4121 if (ArgE.isInvalid())
4122 return true;
4123
4124 Arg = ArgE.takeAs<Expr>();
4125
4126 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004127 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4128
4129 if (ArgE.isInvalid())
4130 return true;
4131
4132 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004133 }
4134
Daniel Dunbar96a00142012-03-09 18:35:03 +00004135 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004136 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004137 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004138 return ExprError();
4139
Chris Lattner925e60d2007-12-28 05:29:59 +00004140 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004141 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004142 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004143
Douglas Gregor88a35142008-12-22 05:46:06 +00004144 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4145 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004146 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4147 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004148
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004149 // Check for sentinels
4150 if (NDecl)
4151 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004152
Chris Lattner59907c42007-08-10 20:18:51 +00004153 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004154 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004155 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004156 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004157
John McCall8e10f3b2011-02-26 05:39:39 +00004158 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004159 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004160 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004161 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004162 return ExprError();
4163 }
Chris Lattner59907c42007-08-10 20:18:51 +00004164
John McCall9ae2f072010-08-23 23:25:46 +00004165 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004166}
4167
John McCall60d7b3a2010-08-24 06:29:42 +00004168ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004169Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004170 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004171 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004172 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004173 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004174
4175 TypeSourceInfo *TInfo;
4176 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4177 if (!TInfo)
4178 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4179
John McCall9ae2f072010-08-23 23:25:46 +00004180 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004181}
4182
John McCall60d7b3a2010-08-24 06:29:42 +00004183ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004184Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004185 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004186 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004187
Eli Friedman6223c222008-05-20 05:22:08 +00004188 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004189 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004190 diag::err_illegal_decl_array_incomplete_type,
4191 SourceRange(LParenLoc,
4192 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004193 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004194 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004195 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004196 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004197 } else if (!literalType->isDependentType() &&
4198 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004199 diag::err_typecheck_decl_incomplete_type,
4200 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004201 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004202
Douglas Gregor99a2e602009-12-16 01:38:02 +00004203 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004204 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004205 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004206 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004207 SourceRange(LParenLoc, RParenLoc),
4208 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004209 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004210 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4211 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004212 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004213 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004214 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004215
Chris Lattner371f2582008-12-04 23:50:19 +00004216 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004217 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004218 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004219 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004220 }
Eli Friedman08544622009-12-22 02:35:53 +00004221
John McCallf89e55a2010-11-18 06:31:45 +00004222 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004223 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004224
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004225 return MaybeBindToTemporary(
4226 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004227 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004228}
4229
John McCall60d7b3a2010-08-24 06:29:42 +00004230ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004231Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004232 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004233 // Immediately handle non-overload placeholders. Overloads can be
4234 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004235 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4236 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4237 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004238
4239 // Ignore failures; dropping the entire initializer list because
4240 // of one failure would be terrible for indexing/etc.
4241 if (result.isInvalid()) continue;
4242
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004243 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004244 }
4245 }
4246
Steve Naroff08d92e42007-09-15 18:49:24 +00004247 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004248 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004249
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004250 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4251 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004252 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004253 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004254}
4255
John McCalldc05b112011-09-10 01:16:55 +00004256/// Do an explicit extend of the given block pointer if we're in ARC.
4257static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4258 assert(E.get()->getType()->isBlockPointerType());
4259 assert(E.get()->isRValue());
4260
4261 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004262 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004263
4264 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004265 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004266 /*base path*/ 0, VK_RValue);
4267 S.ExprNeedsCleanups = true;
4268}
4269
4270/// Prepare a conversion of the given expression to an ObjC object
4271/// pointer type.
4272CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4273 QualType type = E.get()->getType();
4274 if (type->isObjCObjectPointerType()) {
4275 return CK_BitCast;
4276 } else if (type->isBlockPointerType()) {
4277 maybeExtendBlockObject(*this, E);
4278 return CK_BlockPointerToObjCPointerCast;
4279 } else {
4280 assert(type->isPointerType());
4281 return CK_CPointerToObjCPointerCast;
4282 }
4283}
4284
John McCallf3ea8cf2010-11-14 08:17:51 +00004285/// Prepares for a scalar cast, performing all the necessary stages
4286/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004287CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004288 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4289 // Also, callers should have filtered out the invalid cases with
4290 // pointers. Everything else should be possible.
4291
John Wiegley429bb272011-04-08 18:41:53 +00004292 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004293 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004294 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004295
John McCall1d9b3b22011-09-09 05:25:32 +00004296 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004297 case Type::STK_MemberPointer:
4298 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004299
John McCall1d9b3b22011-09-09 05:25:32 +00004300 case Type::STK_CPointer:
4301 case Type::STK_BlockPointer:
4302 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004303 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004304 case Type::STK_CPointer:
4305 return CK_BitCast;
4306 case Type::STK_BlockPointer:
4307 return (SrcKind == Type::STK_BlockPointer
4308 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4309 case Type::STK_ObjCObjectPointer:
4310 if (SrcKind == Type::STK_ObjCObjectPointer)
4311 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004312 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004313 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004314 maybeExtendBlockObject(*this, Src);
4315 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004316 case Type::STK_Bool:
4317 return CK_PointerToBoolean;
4318 case Type::STK_Integral:
4319 return CK_PointerToIntegral;
4320 case Type::STK_Floating:
4321 case Type::STK_FloatingComplex:
4322 case Type::STK_IntegralComplex:
4323 case Type::STK_MemberPointer:
4324 llvm_unreachable("illegal cast from pointer");
4325 }
David Blaikie7530c032012-01-17 06:56:22 +00004326 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004327
John McCalldaa8e4e2010-11-15 09:13:47 +00004328 case Type::STK_Bool: // casting from bool is like casting from an integer
4329 case Type::STK_Integral:
4330 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004331 case Type::STK_CPointer:
4332 case Type::STK_ObjCObjectPointer:
4333 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004334 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004335 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004336 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004337 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004338 case Type::STK_Bool:
4339 return CK_IntegralToBoolean;
4340 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004341 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004342 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004343 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004344 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004345 Src = ImpCastExprToType(Src.take(),
4346 DestTy->castAs<ComplexType>()->getElementType(),
4347 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004348 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004349 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004350 Src = ImpCastExprToType(Src.take(),
4351 DestTy->castAs<ComplexType>()->getElementType(),
4352 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004353 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004354 case Type::STK_MemberPointer:
4355 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004356 }
David Blaikie7530c032012-01-17 06:56:22 +00004357 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004358
John McCalldaa8e4e2010-11-15 09:13:47 +00004359 case Type::STK_Floating:
4360 switch (DestTy->getScalarTypeKind()) {
4361 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004362 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004363 case Type::STK_Bool:
4364 return CK_FloatingToBoolean;
4365 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004366 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004367 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004368 Src = ImpCastExprToType(Src.take(),
4369 DestTy->castAs<ComplexType>()->getElementType(),
4370 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004371 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004372 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004373 Src = ImpCastExprToType(Src.take(),
4374 DestTy->castAs<ComplexType>()->getElementType(),
4375 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004376 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004377 case Type::STK_CPointer:
4378 case Type::STK_ObjCObjectPointer:
4379 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004380 llvm_unreachable("valid float->pointer cast?");
4381 case Type::STK_MemberPointer:
4382 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004383 }
David Blaikie7530c032012-01-17 06:56:22 +00004384 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004385
John McCalldaa8e4e2010-11-15 09:13:47 +00004386 case Type::STK_FloatingComplex:
4387 switch (DestTy->getScalarTypeKind()) {
4388 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004389 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004390 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004391 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004392 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004393 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4394 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004395 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004396 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004397 return CK_FloatingCast;
4398 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004399 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004400 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004401 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004402 Src = ImpCastExprToType(Src.take(),
4403 SrcTy->castAs<ComplexType>()->getElementType(),
4404 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004405 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004406 case Type::STK_CPointer:
4407 case Type::STK_ObjCObjectPointer:
4408 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004409 llvm_unreachable("valid complex float->pointer cast?");
4410 case Type::STK_MemberPointer:
4411 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004412 }
David Blaikie7530c032012-01-17 06:56:22 +00004413 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004414
John McCalldaa8e4e2010-11-15 09:13:47 +00004415 case Type::STK_IntegralComplex:
4416 switch (DestTy->getScalarTypeKind()) {
4417 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004418 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004419 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004420 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004421 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004422 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4423 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004424 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004425 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004426 return CK_IntegralCast;
4427 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004428 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004429 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004430 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004431 Src = ImpCastExprToType(Src.take(),
4432 SrcTy->castAs<ComplexType>()->getElementType(),
4433 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004434 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004435 case Type::STK_CPointer:
4436 case Type::STK_ObjCObjectPointer:
4437 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004438 llvm_unreachable("valid complex int->pointer cast?");
4439 case Type::STK_MemberPointer:
4440 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004441 }
David Blaikie7530c032012-01-17 06:56:22 +00004442 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004443 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004444
John McCallf3ea8cf2010-11-14 08:17:51 +00004445 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004446}
4447
Anders Carlssonc3516322009-10-16 02:48:28 +00004448bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004449 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004450 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004451
Anders Carlssona64db8f2007-11-27 05:51:55 +00004452 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004453 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004454 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004455 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004456 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004457 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004458 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004459 } else
4460 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004461 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004462 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004463
John McCall2de56d12010-08-25 11:45:40 +00004464 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004465 return false;
4466}
4467
John Wiegley429bb272011-04-08 18:41:53 +00004468ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4469 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004470 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004471
Anders Carlsson16a89042009-10-16 05:23:41 +00004472 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004473
Nate Begeman9b10da62009-06-27 22:05:55 +00004474 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4475 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004476 // In OpenCL, casts between vectors of different types are not allowed.
4477 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004478 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004479 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004480 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004481 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004482 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004483 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004484 return ExprError();
4485 }
John McCall2de56d12010-08-25 11:45:40 +00004486 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004487 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004488 }
4489
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004490 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004491 // conversion will take place first from scalar to elt type, and then
4492 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004493 if (SrcTy->isPointerType())
4494 return Diag(R.getBegin(),
4495 diag::err_invalid_conversion_between_vector_and_scalar)
4496 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004497
4498 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004499 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004500 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004501 if (CastExprRes.isInvalid())
4502 return ExprError();
4503 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004504
John McCall2de56d12010-08-25 11:45:40 +00004505 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004506 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004507}
4508
John McCall60d7b3a2010-08-24 06:29:42 +00004509ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004510Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4511 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004512 SourceLocation RParenLoc, Expr *CastExpr) {
4513 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004514 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004515
Richard Trieuccd891a2011-09-09 01:45:06 +00004516 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004517 if (D.isInvalidType())
4518 return ExprError();
4519
David Blaikie4e4d0842012-03-11 07:00:24 +00004520 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004521 // Check that there are no default arguments (C++ only).
4522 CheckExtraCXXDefaultArguments(D);
4523 }
4524
John McCalle82247a2011-10-01 05:17:03 +00004525 checkUnusedDeclAttributes(D);
4526
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004527 QualType castType = castTInfo->getType();
4528 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004529
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004530 bool isVectorLiteral = false;
4531
4532 // Check for an altivec or OpenCL literal,
4533 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004534 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4535 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004536 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004537 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004538 if (PLE && PLE->getNumExprs() == 0) {
4539 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4540 return ExprError();
4541 }
4542 if (PE || PLE->getNumExprs() == 1) {
4543 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4544 if (!E->getType()->isVectorType())
4545 isVectorLiteral = true;
4546 }
4547 else
4548 isVectorLiteral = true;
4549 }
4550
4551 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4552 // then handle it as such.
4553 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004554 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004555
Nate Begeman2ef13e52009-08-10 23:49:36 +00004556 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004557 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4558 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004559 if (isa<ParenListExpr>(CastExpr)) {
4560 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004561 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004562 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004563 }
John McCallb042fdf2010-01-15 18:56:44 +00004564
Richard Trieuccd891a2011-09-09 01:45:06 +00004565 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004566}
4567
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004568ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4569 SourceLocation RParenLoc, Expr *E,
4570 TypeSourceInfo *TInfo) {
4571 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4572 "Expected paren or paren list expression");
4573
4574 Expr **exprs;
4575 unsigned numExprs;
4576 Expr *subExpr;
4577 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4578 exprs = PE->getExprs();
4579 numExprs = PE->getNumExprs();
4580 } else {
4581 subExpr = cast<ParenExpr>(E)->getSubExpr();
4582 exprs = &subExpr;
4583 numExprs = 1;
4584 }
4585
4586 QualType Ty = TInfo->getType();
4587 assert(Ty->isVectorType() && "Expected vector type");
4588
Chris Lattner5f9e2722011-07-23 10:55:15 +00004589 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004590 const VectorType *VTy = Ty->getAs<VectorType>();
4591 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4592
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004593 // '(...)' form of vector initialization in AltiVec: the number of
4594 // initializers must be one or must match the size of the vector.
4595 // If a single value is specified in the initializer then it will be
4596 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004597 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004598 // The number of initializers must be one or must match the size of the
4599 // vector. If a single value is specified in the initializer then it will
4600 // be replicated to all the components of the vector
4601 if (numExprs == 1) {
4602 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004603 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4604 if (Literal.isInvalid())
4605 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004606 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004607 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004608 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4609 }
4610 else if (numExprs < numElems) {
4611 Diag(E->getExprLoc(),
4612 diag::err_incorrect_number_of_vector_initializers);
4613 return ExprError();
4614 }
4615 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004616 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004617 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004618 else {
4619 // For OpenCL, when the number of initializers is a single value,
4620 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004621 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004622 VTy->getVectorKind() == VectorType::GenericVector &&
4623 numExprs == 1) {
4624 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004625 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4626 if (Literal.isInvalid())
4627 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004628 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004629 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004630 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4631 }
4632
Benjamin Kramer14c59822012-02-14 12:06:21 +00004633 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004634 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004635 // FIXME: This means that pretty-printing the final AST will produce curly
4636 // braces instead of the original commas.
4637 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004638 initExprs, RParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004639 initE->setType(Ty);
4640 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4641}
4642
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004643/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4644/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004645ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004646Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4647 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004648 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004649 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004650
John McCall60d7b3a2010-08-24 06:29:42 +00004651 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004652
Nate Begeman2ef13e52009-08-10 23:49:36 +00004653 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004654 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4655 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004656
John McCall9ae2f072010-08-23 23:25:46 +00004657 if (Result.isInvalid()) return ExprError();
4658
4659 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004660}
4661
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004662ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4663 SourceLocation R,
4664 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004665 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4666 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004667 return Owned(expr);
4668}
4669
Chandler Carruth82214a82011-02-18 23:54:50 +00004670/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004671/// constant and the other is not a pointer. Returns true if a diagnostic is
4672/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004673bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004674 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004675 Expr *NullExpr = LHSExpr;
4676 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004677 Expr::NullPointerConstantKind NullKind =
4678 NullExpr->isNullPointerConstant(Context,
4679 Expr::NPC_ValueDependentIsNotNull);
4680
4681 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004682 NullExpr = RHSExpr;
4683 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004684 NullKind =
4685 NullExpr->isNullPointerConstant(Context,
4686 Expr::NPC_ValueDependentIsNotNull);
4687 }
4688
4689 if (NullKind == Expr::NPCK_NotNull)
4690 return false;
4691
David Blaikie50800fc2012-08-08 17:33:31 +00004692 if (NullKind == Expr::NPCK_ZeroExpression)
4693 return false;
4694
4695 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004696 // In this case, check to make sure that we got here from a "NULL"
4697 // string in the source code.
4698 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004699 SourceLocation loc = NullExpr->getExprLoc();
4700 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004701 return false;
4702 }
4703
4704 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4705 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4706 << NonPointerExpr->getType() << DiagType
4707 << NonPointerExpr->getSourceRange();
4708 return true;
4709}
4710
Richard Trieu26f96072011-09-02 01:51:02 +00004711/// \brief Return false if the condition expression is valid, true otherwise.
4712static bool checkCondition(Sema &S, Expr *Cond) {
4713 QualType CondTy = Cond->getType();
4714
4715 // C99 6.5.15p2
4716 if (CondTy->isScalarType()) return false;
4717
4718 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004719 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004720 return false;
4721
4722 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004723 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004724 diag::err_typecheck_cond_expect_scalar :
4725 diag::err_typecheck_cond_expect_scalar_or_vector)
4726 << CondTy;
4727 return true;
4728}
4729
4730/// \brief Return false if the two expressions can be converted to a vector,
4731/// true otherwise
4732static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4733 ExprResult &RHS,
4734 QualType CondTy) {
4735 // Both operands should be of scalar type.
4736 if (!LHS.get()->getType()->isScalarType()) {
4737 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4738 << CondTy;
4739 return true;
4740 }
4741 if (!RHS.get()->getType()->isScalarType()) {
4742 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4743 << CondTy;
4744 return true;
4745 }
4746
4747 // Implicity convert these scalars to the type of the condition.
4748 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4749 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4750 return false;
4751}
4752
4753/// \brief Handle when one or both operands are void type.
4754static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4755 ExprResult &RHS) {
4756 Expr *LHSExpr = LHS.get();
4757 Expr *RHSExpr = RHS.get();
4758
4759 if (!LHSExpr->getType()->isVoidType())
4760 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4761 << RHSExpr->getSourceRange();
4762 if (!RHSExpr->getType()->isVoidType())
4763 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4764 << LHSExpr->getSourceRange();
4765 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4766 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4767 return S.Context.VoidTy;
4768}
4769
4770/// \brief Return false if the NullExpr can be promoted to PointerTy,
4771/// true otherwise.
4772static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4773 QualType PointerTy) {
4774 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4775 !NullExpr.get()->isNullPointerConstant(S.Context,
4776 Expr::NPC_ValueDependentIsNull))
4777 return true;
4778
4779 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4780 return false;
4781}
4782
4783/// \brief Checks compatibility between two pointers and return the resulting
4784/// type.
4785static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4786 ExprResult &RHS,
4787 SourceLocation Loc) {
4788 QualType LHSTy = LHS.get()->getType();
4789 QualType RHSTy = RHS.get()->getType();
4790
4791 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4792 // Two identical pointers types are always compatible.
4793 return LHSTy;
4794 }
4795
4796 QualType lhptee, rhptee;
4797
4798 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004799 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4800 lhptee = LHSBTy->getPointeeType();
4801 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004802 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004803 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4804 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004805 }
4806
Eli Friedmanae916a12012-04-05 22:30:04 +00004807 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4808 // differently qualified versions of compatible types, the result type is
4809 // a pointer to an appropriately qualified version of the composite
4810 // type.
4811
4812 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4813 // clause doesn't make sense for our extensions. E.g. address space 2 should
4814 // be incompatible with address space 3: they may live on different devices or
4815 // anything.
4816 Qualifiers lhQual = lhptee.getQualifiers();
4817 Qualifiers rhQual = rhptee.getQualifiers();
4818
4819 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4820 lhQual.removeCVRQualifiers();
4821 rhQual.removeCVRQualifiers();
4822
4823 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4824 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4825
4826 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4827
4828 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004829 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4830 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4831 << RHS.get()->getSourceRange();
4832 // In this situation, we assume void* type. No especially good
4833 // reason, but this is what gcc does, and we do have to pick
4834 // to get a consistent AST.
4835 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4836 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4837 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4838 return incompatTy;
4839 }
4840
4841 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004842 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4843 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004844
Eli Friedmanae916a12012-04-05 22:30:04 +00004845 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4846 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4847 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004848}
4849
4850/// \brief Return the resulting type when the operands are both block pointers.
4851static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4852 ExprResult &LHS,
4853 ExprResult &RHS,
4854 SourceLocation Loc) {
4855 QualType LHSTy = LHS.get()->getType();
4856 QualType RHSTy = RHS.get()->getType();
4857
4858 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4859 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4860 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4861 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4862 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4863 return destType;
4864 }
4865 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4866 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4867 << RHS.get()->getSourceRange();
4868 return QualType();
4869 }
4870
4871 // We have 2 block pointer types.
4872 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4873}
4874
4875/// \brief Return the resulting type when the operands are both pointers.
4876static QualType
4877checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4878 ExprResult &RHS,
4879 SourceLocation Loc) {
4880 // get the pointer types
4881 QualType LHSTy = LHS.get()->getType();
4882 QualType RHSTy = RHS.get()->getType();
4883
4884 // get the "pointed to" types
4885 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4886 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4887
4888 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4889 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4890 // Figure out necessary qualifiers (C99 6.5.15p6)
4891 QualType destPointee
4892 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4893 QualType destType = S.Context.getPointerType(destPointee);
4894 // Add qualifiers if necessary.
4895 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4896 // Promote to void*.
4897 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4898 return destType;
4899 }
4900 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4901 QualType destPointee
4902 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4903 QualType destType = S.Context.getPointerType(destPointee);
4904 // Add qualifiers if necessary.
4905 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4906 // Promote to void*.
4907 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4908 return destType;
4909 }
4910
4911 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4912}
4913
4914/// \brief Return false if the first expression is not an integer and the second
4915/// expression is not a pointer, true otherwise.
4916static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4917 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004918 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004919 if (!PointerExpr->getType()->isPointerType() ||
4920 !Int.get()->getType()->isIntegerType())
4921 return false;
4922
Richard Trieuccd891a2011-09-09 01:45:06 +00004923 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4924 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004925
4926 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4927 << Expr1->getType() << Expr2->getType()
4928 << Expr1->getSourceRange() << Expr2->getSourceRange();
4929 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4930 CK_IntegralToPointer);
4931 return true;
4932}
4933
Richard Trieu33fc7572011-09-06 20:06:39 +00004934/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4935/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004936/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004937QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4938 ExprResult &RHS, ExprValueKind &VK,
4939 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004940 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004941
Richard Trieu33fc7572011-09-06 20:06:39 +00004942 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4943 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004944 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004945
Richard Trieu33fc7572011-09-06 20:06:39 +00004946 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4947 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004948 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004949
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004950 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004951 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004952 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004953
4954 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004955 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004956
John Wiegley429bb272011-04-08 18:41:53 +00004957 Cond = UsualUnaryConversions(Cond.take());
4958 if (Cond.isInvalid())
4959 return QualType();
4960 LHS = UsualUnaryConversions(LHS.take());
4961 if (LHS.isInvalid())
4962 return QualType();
4963 RHS = UsualUnaryConversions(RHS.take());
4964 if (RHS.isInvalid())
4965 return QualType();
4966
4967 QualType CondTy = Cond.get()->getType();
4968 QualType LHSTy = LHS.get()->getType();
4969 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004970
Reid Spencer5f016e22007-07-11 17:01:13 +00004971 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004972 if (checkCondition(*this, Cond.get()))
4973 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004974
Chris Lattner70d67a92008-01-06 22:42:25 +00004975 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004976 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004977 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004978
Nate Begeman6155d732010-09-20 22:41:17 +00004979 // OpenCL: If the condition is a vector, and both operands are scalar,
4980 // attempt to implicity convert them to the vector type to act like the
4981 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004982 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004983 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004984 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004985
Chris Lattner70d67a92008-01-06 22:42:25 +00004986 // If both operands have arithmetic type, do the usual arithmetic conversions
4987 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004988 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4989 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004990 if (LHS.isInvalid() || RHS.isInvalid())
4991 return QualType();
4992 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004993 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004994
Chris Lattner70d67a92008-01-06 22:42:25 +00004995 // If both operands are the same structure or union type, the result is that
4996 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004997 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4998 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004999 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005000 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005001 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005002 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005003 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005004 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005005
Chris Lattner70d67a92008-01-06 22:42:25 +00005006 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005007 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005008 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005009 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00005010 }
Richard Trieu26f96072011-09-02 01:51:02 +00005011
Steve Naroffb6d54e52008-01-08 01:11:38 +00005012 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5013 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00005014 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5015 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005016
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005017 // All objective-c pointer type analysis is done here.
5018 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5019 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005020 if (LHS.isInvalid() || RHS.isInvalid())
5021 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005022 if (!compositeType.isNull())
5023 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005024
5025
Steve Naroff7154a772009-07-01 14:36:47 +00005026 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00005027 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5028 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5029 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005030
Steve Naroff7154a772009-07-01 14:36:47 +00005031 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00005032 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5033 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5034 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005035
John McCall404cd162010-11-13 01:35:44 +00005036 // GCC compatibility: soften pointer/integer mismatch. Note that
5037 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00005038 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5039 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00005040 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005041 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5042 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00005043 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005044
Chandler Carruth82214a82011-02-18 23:54:50 +00005045 // Emit a better diagnostic if one of the expressions is a null pointer
5046 // constant and the other is not a pointer type. In this case, the user most
5047 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005048 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005049 return QualType();
5050
Chris Lattner70d67a92008-01-06 22:42:25 +00005051 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005052 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005053 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5054 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005055 return QualType();
5056}
5057
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005058/// FindCompositeObjCPointerType - Helper method to find composite type of
5059/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005060QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005061 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005062 QualType LHSTy = LHS.get()->getType();
5063 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005064
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005065 // Handle things like Class and struct objc_class*. Here we case the result
5066 // to the pseudo-builtin, because that will be implicitly cast back to the
5067 // redefinition type if an attempt is made to access its fields.
5068 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005069 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005070 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005071 return LHSTy;
5072 }
5073 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005074 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005075 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005076 return RHSTy;
5077 }
5078 // And the same for struct objc_object* / id
5079 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005080 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005081 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005082 return LHSTy;
5083 }
5084 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005085 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005086 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005087 return RHSTy;
5088 }
5089 // And the same for struct objc_selector* / SEL
5090 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005091 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005092 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005093 return LHSTy;
5094 }
5095 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005096 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005097 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005098 return RHSTy;
5099 }
5100 // Check constraints for Objective-C object pointers types.
5101 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005102
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005103 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5104 // Two identical object pointer types are always compatible.
5105 return LHSTy;
5106 }
John McCall1d9b3b22011-09-09 05:25:32 +00005107 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5108 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005109 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005110
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005111 // If both operands are interfaces and either operand can be
5112 // assigned to the other, use that type as the composite
5113 // type. This allows
5114 // xxx ? (A*) a : (B*) b
5115 // where B is a subclass of A.
5116 //
5117 // Additionally, as for assignment, if either type is 'id'
5118 // allow silent coercion. Finally, if the types are
5119 // incompatible then make sure to use 'id' as the composite
5120 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005121
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005122 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5123 // It could return the composite type.
5124 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5125 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5126 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5127 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5128 } else if ((LHSTy->isObjCQualifiedIdType() ||
5129 RHSTy->isObjCQualifiedIdType()) &&
5130 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5131 // Need to handle "id<xx>" explicitly.
5132 // GCC allows qualified id and any Objective-C type to devolve to
5133 // id. Currently localizing to here until clear this should be
5134 // part of ObjCQualifiedIdTypesAreCompatible.
5135 compositeType = Context.getObjCIdType();
5136 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5137 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005138 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005139 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5140 ;
5141 else {
5142 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5143 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005144 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005145 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005146 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5147 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005148 return incompatTy;
5149 }
5150 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005151 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5152 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005153 return compositeType;
5154 }
5155 // Check Objective-C object pointer types and 'void *'
5156 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005157 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005158 // ARC forbids the implicit conversion of object pointers to 'void *',
5159 // so these types are not compatible.
5160 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5161 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5162 LHS = RHS = true;
5163 return QualType();
5164 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005165 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5166 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5167 QualType destPointee
5168 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5169 QualType destType = Context.getPointerType(destPointee);
5170 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005171 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005172 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005173 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005174 return destType;
5175 }
5176 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005177 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005178 // ARC forbids the implicit conversion of object pointers to 'void *',
5179 // so these types are not compatible.
5180 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5181 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5182 LHS = RHS = true;
5183 return QualType();
5184 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005185 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5186 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5187 QualType destPointee
5188 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5189 QualType destType = Context.getPointerType(destPointee);
5190 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005191 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005192 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005193 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005194 return destType;
5195 }
5196 return QualType();
5197}
5198
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005199/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005200/// ParenRange in parentheses.
5201static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005202 const PartialDiagnostic &Note,
5203 SourceRange ParenRange) {
5204 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5205 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5206 EndLoc.isValid()) {
5207 Self.Diag(Loc, Note)
5208 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5209 << FixItHint::CreateInsertion(EndLoc, ")");
5210 } else {
5211 // We can't display the parentheses, so just show the bare note.
5212 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005213 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005214}
5215
5216static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5217 return Opc >= BO_Mul && Opc <= BO_Shr;
5218}
5219
Hans Wennborg2f072b42011-06-09 17:06:51 +00005220/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5221/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005222/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5223/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005224static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005225 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005226 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5227 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005228 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005229 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005230
5231 // Built-in binary operator.
5232 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5233 if (IsArithmeticOp(OP->getOpcode())) {
5234 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005235 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005236 return true;
5237 }
5238 }
5239
5240 // Overloaded operator.
5241 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5242 if (Call->getNumArgs() != 2)
5243 return false;
5244
5245 // Make sure this is really a binary operator that is safe to pass into
5246 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5247 OverloadedOperatorKind OO = Call->getOperator();
5248 if (OO < OO_Plus || OO > OO_Arrow)
5249 return false;
5250
5251 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5252 if (IsArithmeticOp(OpKind)) {
5253 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005254 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005255 return true;
5256 }
5257 }
5258
5259 return false;
5260}
5261
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005262static bool IsLogicOp(BinaryOperatorKind Opc) {
5263 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5264}
5265
Hans Wennborg2f072b42011-06-09 17:06:51 +00005266/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5267/// or is a logical expression such as (x==y) which has int type, but is
5268/// commonly interpreted as boolean.
5269static bool ExprLooksBoolean(Expr *E) {
5270 E = E->IgnoreParenImpCasts();
5271
5272 if (E->getType()->isBooleanType())
5273 return true;
5274 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5275 return IsLogicOp(OP->getOpcode());
5276 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5277 return OP->getOpcode() == UO_LNot;
5278
5279 return false;
5280}
5281
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005282/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5283/// and binary operator are mixed in a way that suggests the programmer assumed
5284/// the conditional operator has higher precedence, for example:
5285/// "int x = a + someBinaryCondition ? 1 : 2".
5286static void DiagnoseConditionalPrecedence(Sema &Self,
5287 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005288 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005289 Expr *LHSExpr,
5290 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005291 BinaryOperatorKind CondOpcode;
5292 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005293
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005294 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005295 return;
5296 if (!ExprLooksBoolean(CondRHS))
5297 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005298
Hans Wennborg2f072b42011-06-09 17:06:51 +00005299 // The condition is an arithmetic binary expression, with a right-
5300 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005301
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005302 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005303 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005304 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005305
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005306 SuggestParentheses(Self, OpLoc,
5307 Self.PDiag(diag::note_precedence_conditional_silence)
5308 << BinaryOperator::getOpcodeStr(CondOpcode),
5309 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005310
5311 SuggestParentheses(Self, OpLoc,
5312 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005313 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005314}
5315
Steve Narofff69936d2007-09-16 03:34:24 +00005316/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005317/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005318ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005319 SourceLocation ColonLoc,
5320 Expr *CondExpr, Expr *LHSExpr,
5321 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005322 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5323 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005324 OpaqueValueExpr *opaqueValue = 0;
5325 Expr *commonExpr = 0;
5326 if (LHSExpr == 0) {
5327 commonExpr = CondExpr;
5328
5329 // We usually want to apply unary conversions *before* saving, except
5330 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005331 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005332 && !commonExpr->isTypeDependent()
5333 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5334 && commonExpr->isGLValue()
5335 && commonExpr->isOrdinaryOrBitFieldObject()
5336 && RHSExpr->isOrdinaryOrBitFieldObject()
5337 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005338 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5339 if (commonRes.isInvalid())
5340 return ExprError();
5341 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005342 }
5343
5344 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5345 commonExpr->getType(),
5346 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005347 commonExpr->getObjectKind(),
5348 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005349 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005350 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005351
John McCallf89e55a2010-11-18 06:31:45 +00005352 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005353 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005354 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5355 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005356 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005357 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5358 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005359 return ExprError();
5360
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005361 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5362 RHS.get());
5363
John McCall56ca35d2011-02-17 10:25:35 +00005364 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005365 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5366 LHS.take(), ColonLoc,
5367 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005368
5369 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005370 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005371 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5372 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005373}
5374
John McCalle4be87e2011-01-31 23:13:11 +00005375// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005376// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005377// routine is it effectively iqnores the qualifiers on the top level pointee.
5378// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5379// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005380static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005381checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5382 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5383 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005384
Reid Spencer5f016e22007-07-11 17:01:13 +00005385 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005386 const Type *lhptee, *rhptee;
5387 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005388 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5389 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005390
John McCalle4be87e2011-01-31 23:13:11 +00005391 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005392
5393 // C99 6.5.16.1p1: This following citation is common to constraints
5394 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5395 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005396 Qualifiers lq;
5397
John McCallf85e1932011-06-15 23:02:42 +00005398 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5399 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5400 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5401 // Ignore lifetime for further calculation.
5402 lhq.removeObjCLifetime();
5403 rhq.removeObjCLifetime();
5404 }
5405
John McCall86c05f32011-02-01 00:10:29 +00005406 if (!lhq.compatiblyIncludes(rhq)) {
5407 // Treat address-space mismatches as fatal. TODO: address subspaces
5408 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5409 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5410
John McCallf85e1932011-06-15 23:02:42 +00005411 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005412 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005413 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005414 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005415 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005416 && (lhptee->isVoidType() || rhptee->isVoidType()))
5417 ; // keep old
5418
John McCallf85e1932011-06-15 23:02:42 +00005419 // Treat lifetime mismatches as fatal.
5420 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5421 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5422
John McCall86c05f32011-02-01 00:10:29 +00005423 // For GCC compatibility, other qualifier mismatches are treated
5424 // as still compatible in C.
5425 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005427
Mike Stumpeed9cac2009-02-19 03:04:26 +00005428 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5429 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005430 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005431 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005432 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005433 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005434
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005435 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005436 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005437 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005438 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005439
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005440 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005441 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005442 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005443
5444 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005445 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005446 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005447 }
John McCall86c05f32011-02-01 00:10:29 +00005448
Mike Stumpeed9cac2009-02-19 03:04:26 +00005449 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005450 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005451 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5452 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005453 // Check if the pointee types are compatible ignoring the sign.
5454 // We explicitly check for char so that we catch "char" vs
5455 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005456 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005457 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005458 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005459 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005460
Chris Lattner6a2b9262009-10-17 20:33:28 +00005461 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005462 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005463 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005464 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005465
John McCall86c05f32011-02-01 00:10:29 +00005466 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005467 // Types are compatible ignoring the sign. Qualifier incompatibility
5468 // takes priority over sign incompatibility because the sign
5469 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005470 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005471 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005472
John McCalle4be87e2011-01-31 23:13:11 +00005473 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005474 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005475
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005476 // If we are a multi-level pointer, it's possible that our issue is simply
5477 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5478 // the eventual target type is the same and the pointers have the same
5479 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005480 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005481 do {
John McCall86c05f32011-02-01 00:10:29 +00005482 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5483 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005484 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005485
John McCall86c05f32011-02-01 00:10:29 +00005486 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005487 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005488 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005489
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005490 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005491 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005492 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005493 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005494 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5495 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005496 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005497}
5498
John McCalle4be87e2011-01-31 23:13:11 +00005499/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005500/// block pointer types are compatible or whether a block and normal pointer
5501/// are compatible. It is more restrict than comparing two function pointer
5502// types.
John McCalle4be87e2011-01-31 23:13:11 +00005503static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005504checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5505 QualType RHSType) {
5506 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5507 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005508
Steve Naroff1c7d0672008-09-04 15:10:53 +00005509 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005510
Steve Naroff1c7d0672008-09-04 15:10:53 +00005511 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005512 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5513 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005514
John McCalle4be87e2011-01-31 23:13:11 +00005515 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005516 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005517 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005518
John McCalle4be87e2011-01-31 23:13:11 +00005519 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005520
Steve Naroff1c7d0672008-09-04 15:10:53 +00005521 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005522 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5523 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005524
Richard Trieu1da27a12011-09-06 20:21:22 +00005525 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005526 return Sema::IncompatibleBlockPointer;
5527
Steve Naroff1c7d0672008-09-04 15:10:53 +00005528 return ConvTy;
5529}
5530
John McCalle4be87e2011-01-31 23:13:11 +00005531/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005532/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005533static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005534checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5535 QualType RHSType) {
5536 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5537 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005538
Richard Trieu1da27a12011-09-06 20:21:22 +00005539 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005540 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005541 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5542 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005543 return Sema::IncompatiblePointer;
5544 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005545 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005546 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005547 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5548 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005549 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005550 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005551 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005552 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5553 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005554
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005555 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5556 // make an exception for id<P>
5557 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005558 return Sema::CompatiblePointerDiscardsQualifiers;
5559
Richard Trieu1da27a12011-09-06 20:21:22 +00005560 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005561 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005562 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005563 return Sema::IncompatibleObjCQualifiedId;
5564 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005565}
5566
John McCall1c23e912010-11-16 02:32:08 +00005567Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005568Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005569 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005570 // Fake up an opaque expression. We don't actually care about what
5571 // cast operations are required, so if CheckAssignmentConstraints
5572 // adds casts to this they'll be wasted, but fortunately that doesn't
5573 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005574 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5575 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005576 CastKind K = CK_Invalid;
5577
Richard Trieu1da27a12011-09-06 20:21:22 +00005578 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005579}
5580
Mike Stumpeed9cac2009-02-19 03:04:26 +00005581/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5582/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005583/// pointers. Here are some objectionable examples that GCC considers warnings:
5584///
5585/// int a, *pint;
5586/// short *pshort;
5587/// struct foo *pfoo;
5588///
5589/// pint = pshort; // warning: assignment from incompatible pointer type
5590/// a = pint; // warning: assignment makes integer from pointer without a cast
5591/// pint = a; // warning: assignment makes pointer from integer without a cast
5592/// pint = pfoo; // warning: assignment from incompatible pointer type
5593///
5594/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005595/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005596///
John McCalldaa8e4e2010-11-15 09:13:47 +00005597/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005598Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005599Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005600 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005601 QualType RHSType = RHS.get()->getType();
5602 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005603
Chris Lattnerfc144e22008-01-04 23:18:45 +00005604 // Get canonical types. We're not formatting these types, just comparing
5605 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005606 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5607 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005608
Eli Friedmanb001de72011-10-06 23:00:33 +00005609
John McCallb6cfa242011-01-31 22:28:28 +00005610 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005611 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005612 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005613 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005614 }
5615
Eli Friedman860a3192012-06-16 02:19:17 +00005616 // If we have an atomic type, try a non-atomic assignment, then just add an
5617 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005618 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005619 Sema::AssignConvertType result =
5620 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5621 if (result != Compatible)
5622 return result;
5623 if (Kind != CK_NoOp)
5624 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5625 Kind = CK_NonAtomicToAtomic;
5626 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005627 }
5628
Douglas Gregor9d293df2008-10-28 00:22:11 +00005629 // If the left-hand side is a reference type, then we are in a
5630 // (rare!) case where we've allowed the use of references in C,
5631 // e.g., as a parameter type in a built-in function. In this case,
5632 // just make sure that the type referenced is compatible with the
5633 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005634 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005635 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005636 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5637 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005638 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005639 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005640 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005641 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005642 }
John McCallb6cfa242011-01-31 22:28:28 +00005643
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005644 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5645 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005646 if (LHSType->isExtVectorType()) {
5647 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005648 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005649 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005650 // CK_VectorSplat does T -> vector T, so first cast to the
5651 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005652 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5653 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005654 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005655 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005656 }
5657 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005658 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005659 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005660 }
Mike Stump1eb44332009-09-09 15:08:12 +00005661
John McCallb6cfa242011-01-31 22:28:28 +00005662 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005663 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5664 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005665 // Allow assignments of an AltiVec vector type to an equivalent GCC
5666 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005667 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005668 Kind = CK_BitCast;
5669 return Compatible;
5670 }
5671
Douglas Gregor255210e2010-08-06 10:14:59 +00005672 // If we are allowing lax vector conversions, and LHS and RHS are both
5673 // vectors, the total size only needs to be the same. This is a bitcast;
5674 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005675 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005676 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005677 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005678 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005679 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005680 }
5681 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005682 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005683
John McCallb6cfa242011-01-31 22:28:28 +00005684 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005685 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005686 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005687 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005688 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005689 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005690
John McCallb6cfa242011-01-31 22:28:28 +00005691 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005692 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005693 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005694 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005695 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005696 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005697 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005698
John McCallb6cfa242011-01-31 22:28:28 +00005699 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005700 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005701 Kind = CK_IntegralToPointer; // FIXME: null?
5702 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005703 }
John McCallb6cfa242011-01-31 22:28:28 +00005704
5705 // C pointers are not compatible with ObjC object pointers,
5706 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005707 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005708 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005709 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005710 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005711 return Compatible;
5712 }
5713
5714 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005715 if (RHSType->isObjCClassType() &&
5716 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005717 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005718 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005719 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005720 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005721
John McCallb6cfa242011-01-31 22:28:28 +00005722 Kind = CK_BitCast;
5723 return IncompatiblePointer;
5724 }
5725
5726 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005727 if (RHSType->getAs<BlockPointerType>()) {
5728 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005729 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005730 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005731 }
Steve Naroffb4406862008-09-29 18:10:17 +00005732 }
John McCallb6cfa242011-01-31 22:28:28 +00005733
Steve Naroff1c7d0672008-09-04 15:10:53 +00005734 return Incompatible;
5735 }
5736
John McCallb6cfa242011-01-31 22:28:28 +00005737 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005738 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005739 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005740 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005741 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005742 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005743 }
5744
5745 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005746 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005747 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005748 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005749 }
5750
John McCallb6cfa242011-01-31 22:28:28 +00005751 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005752 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005753 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005754 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005755 }
Steve Naroffb4406862008-09-29 18:10:17 +00005756
John McCallb6cfa242011-01-31 22:28:28 +00005757 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005758 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005759 if (RHSPT->getPointeeType()->isVoidType()) {
5760 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005761 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005762 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005763
Chris Lattnerfc144e22008-01-04 23:18:45 +00005764 return Incompatible;
5765 }
5766
John McCallb6cfa242011-01-31 22:28:28 +00005767 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005768 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005769 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005770 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005771 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005772 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005773 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005774 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005775 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005776 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005777 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005778 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005779 }
5780
5781 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005782 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005783 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005784 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005785 }
5786
John McCallb6cfa242011-01-31 22:28:28 +00005787 // In general, C pointers are not compatible with ObjC object pointers,
5788 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005789 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005790 Kind = CK_CPointerToObjCPointerCast;
5791
John McCallb6cfa242011-01-31 22:28:28 +00005792 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005793 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005794 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005795 }
5796
5797 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005798 if (LHSType->isObjCClassType() &&
5799 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005800 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005801 return Compatible;
5802 }
5803
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005804 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005805 }
John McCallb6cfa242011-01-31 22:28:28 +00005806
5807 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005808 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005809 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005810 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005811 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005812 }
5813
Steve Naroff14108da2009-07-10 23:34:53 +00005814 return Incompatible;
5815 }
John McCallb6cfa242011-01-31 22:28:28 +00005816
5817 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005818 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005819 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005820 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005821 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005822 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005823 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005824
John McCallb6cfa242011-01-31 22:28:28 +00005825 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005826 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005827 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005828 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005829 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005830
Chris Lattnerfc144e22008-01-04 23:18:45 +00005831 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005832 }
John McCallb6cfa242011-01-31 22:28:28 +00005833
5834 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005835 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005836 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005837 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005838 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005839 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005840 }
Steve Naroff14108da2009-07-10 23:34:53 +00005841
John McCallb6cfa242011-01-31 22:28:28 +00005842 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005843 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005844 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005845 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005846 }
5847
Steve Naroff14108da2009-07-10 23:34:53 +00005848 return Incompatible;
5849 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005850
John McCallb6cfa242011-01-31 22:28:28 +00005851 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005852 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5853 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005854 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005855 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005856 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005857 }
John McCallb6cfa242011-01-31 22:28:28 +00005858
Reid Spencer5f016e22007-07-11 17:01:13 +00005859 return Incompatible;
5860}
5861
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005862/// \brief Constructs a transparent union from an expression that is
5863/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005864static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5865 ExprResult &EResult, QualType UnionType,
5866 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005867 // Build an initializer list that designates the appropriate member
5868 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005869 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005870 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005871 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005872 Initializer->setType(UnionType);
5873 Initializer->setInitializedFieldInUnion(Field);
5874
5875 // Build a compound literal constructing a value of the transparent
5876 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005877 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005878 EResult = S.Owned(
5879 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5880 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005881}
5882
5883Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005884Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005885 ExprResult &RHS) {
5886 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005887
Mike Stump1eb44332009-09-09 15:08:12 +00005888 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005889 // transparent_union GCC extension.
5890 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005891 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005892 return Incompatible;
5893
5894 // The field to initialize within the transparent union.
5895 RecordDecl *UD = UT->getDecl();
5896 FieldDecl *InitField = 0;
5897 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005898 for (RecordDecl::field_iterator it = UD->field_begin(),
5899 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005900 it != itend; ++it) {
5901 if (it->getType()->isPointerType()) {
5902 // If the transparent union contains a pointer type, we allow:
5903 // 1) void pointer
5904 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005905 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005906 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005907 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005908 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005909 break;
5910 }
Mike Stump1eb44332009-09-09 15:08:12 +00005911
Richard Trieuf7720da2011-09-06 20:40:12 +00005912 if (RHS.get()->isNullPointerConstant(Context,
5913 Expr::NPC_ValueDependentIsNull)) {
5914 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5915 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005916 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005917 break;
5918 }
5919 }
5920
John McCalldaa8e4e2010-11-15 09:13:47 +00005921 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005922 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005923 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005924 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005925 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005926 break;
5927 }
5928 }
5929
5930 if (!InitField)
5931 return Incompatible;
5932
Richard Trieuf7720da2011-09-06 20:40:12 +00005933 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005934 return Compatible;
5935}
5936
Chris Lattner5cf216b2008-01-04 18:04:52 +00005937Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005938Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5939 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005940 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005941 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005942 // C++ 5.17p3: If the left operand is not of class type, the
5943 // expression is implicitly converted (C++ 4) to the
5944 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005945 ExprResult Res;
5946 if (Diagnose) {
5947 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5948 AA_Assigning);
5949 } else {
5950 ImplicitConversionSequence ICS =
5951 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5952 /*SuppressUserConversions=*/false,
5953 /*AllowExplicit=*/false,
5954 /*InOverloadResolution=*/false,
5955 /*CStyle=*/false,
5956 /*AllowObjCWritebackConversion=*/false);
5957 if (ICS.isFailure())
5958 return Incompatible;
5959 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5960 ICS, AA_Assigning);
5961 }
John Wiegley429bb272011-04-08 18:41:53 +00005962 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005963 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005964 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005965 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005966 !CheckObjCARCUnavailableWeakConversion(LHSType,
5967 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005968 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005969 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005970 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005971 }
5972
5973 // FIXME: Currently, we fall through and treat C++ classes like C
5974 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005975 // FIXME: We also fall through for atomics; not sure what should
5976 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005977 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005978
Steve Naroff529a4ad2007-11-27 17:58:44 +00005979 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5980 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005981 if ((LHSType->isPointerType() ||
5982 LHSType->isObjCObjectPointerType() ||
5983 LHSType->isBlockPointerType())
5984 && RHS.get()->isNullPointerConstant(Context,
5985 Expr::NPC_ValueDependentIsNull)) {
5986 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005987 return Compatible;
5988 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005989
Chris Lattner943140e2007-10-16 02:55:40 +00005990 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005991 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005992 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005993 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005994 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005995 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005996 if (!LHSType->isReferenceType()) {
5997 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5998 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005999 return Incompatible;
6000 }
Steve Narofff1120de2007-08-24 22:33:52 +00006001
John McCalldaa8e4e2010-11-15 09:13:47 +00006002 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006003 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00006004 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006005
Steve Narofff1120de2007-08-24 22:33:52 +00006006 // C99 6.5.16.1p2: The value of the right operand is converted to the
6007 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006008 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6009 // so that we can use references in built-in functions even in C.
6010 // The getNonReferenceType() call makes sure that the resulting expression
6011 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00006012 if (result != Incompatible && RHS.get()->getType() != LHSType)
6013 RHS = ImpCastExprToType(RHS.take(),
6014 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006015 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006016}
6017
Richard Trieuf7720da2011-09-06 20:40:12 +00006018QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6019 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006020 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00006021 << LHS.get()->getType() << RHS.get()->getType()
6022 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006023 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006024}
6025
Richard Trieu08062aa2011-09-06 21:01:04 +00006026QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006027 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00006028 if (!IsCompAssign) {
6029 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6030 if (LHS.isInvalid())
6031 return QualType();
6032 }
6033 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6034 if (RHS.isInvalid())
6035 return QualType();
6036
Mike Stumpeed9cac2009-02-19 03:04:26 +00006037 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006038 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00006039 QualType LHSType =
6040 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6041 QualType RHSType =
6042 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006043
Nate Begemanbe2341d2008-07-14 18:02:46 +00006044 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006045 if (LHSType == RHSType)
6046 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006047
Douglas Gregor255210e2010-08-06 10:14:59 +00006048 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006049 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6050 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6051 if (LHSType->isExtVectorType()) {
6052 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6053 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006054 }
6055
Richard Trieuccd891a2011-09-09 01:45:06 +00006056 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006057 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6058 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006059 }
6060
David Blaikie4e4d0842012-03-11 07:00:24 +00006061 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006062 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006063 // If we are allowing lax vector conversions, and LHS and RHS are both
6064 // vectors, the total size only needs to be the same. This is a
6065 // bitcast; no bits are changed but the result type is different.
6066 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006067 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6068 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006069 }
6070
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006071 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6072 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6073 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006074 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006075 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006076 std::swap(RHS, LHS);
6077 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006078 }
Mike Stump1eb44332009-09-09 15:08:12 +00006079
Nate Begemandde25982009-06-28 19:12:57 +00006080 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006081 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006082 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006083 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6084 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006085 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006086 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006087 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006088 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6089 if (swapped) std::swap(RHS, LHS);
6090 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006091 }
6092 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006093 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6094 RHSType->isRealFloatingType()) {
6095 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006096 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006097 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006098 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006099 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6100 if (swapped) std::swap(RHS, LHS);
6101 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006102 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006103 }
6104 }
Mike Stump1eb44332009-09-09 15:08:12 +00006105
Nate Begemandde25982009-06-28 19:12:57 +00006106 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006107 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006108 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006109 << LHS.get()->getType() << RHS.get()->getType()
6110 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006111 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006112}
6113
Richard Trieu481037f2011-09-16 00:53:10 +00006114// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6115// expression. These are mainly cases where the null pointer is used as an
6116// integer instead of a pointer.
6117static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6118 SourceLocation Loc, bool IsCompare) {
6119 // The canonical way to check for a GNU null is with isNullPointerConstant,
6120 // but we use a bit of a hack here for speed; this is a relatively
6121 // hot path, and isNullPointerConstant is slow.
6122 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6123 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6124
6125 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6126
6127 // Avoid analyzing cases where the result will either be invalid (and
6128 // diagnosed as such) or entirely valid and not something to warn about.
6129 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6130 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6131 return;
6132
6133 // Comparison operations would not make sense with a null pointer no matter
6134 // what the other expression is.
6135 if (!IsCompare) {
6136 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6137 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6138 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6139 return;
6140 }
6141
6142 // The rest of the operations only make sense with a null pointer
6143 // if the other expression is a pointer.
6144 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6145 NonNullType->canDecayToPointerType())
6146 return;
6147
6148 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6149 << LHSNull /* LHS is NULL */ << NonNullType
6150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6151}
6152
Richard Trieu08062aa2011-09-06 21:01:04 +00006153QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006154 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006155 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006156 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6157
Richard Trieu08062aa2011-09-06 21:01:04 +00006158 if (LHS.get()->getType()->isVectorType() ||
6159 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006160 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006161
Richard Trieuccd891a2011-09-09 01:45:06 +00006162 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006163 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006164 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006165
David Chisnall7a7ee302012-01-16 17:27:18 +00006166
Eli Friedman860a3192012-06-16 02:19:17 +00006167 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006168 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006169
Chris Lattner7ef655a2010-01-12 21:23:57 +00006170 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006171 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006172 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006173 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006174 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6175 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006176
Chris Lattner7ef655a2010-01-12 21:23:57 +00006177 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006178}
6179
Chris Lattner7ef655a2010-01-12 21:23:57 +00006180QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006181 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006182 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6183
Richard Trieu08062aa2011-09-06 21:01:04 +00006184 if (LHS.get()->getType()->isVectorType() ||
6185 RHS.get()->getType()->isVectorType()) {
6186 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6187 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006188 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006189 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006190 }
Steve Naroff90045e82007-07-13 23:32:42 +00006191
Richard Trieuccd891a2011-09-09 01:45:06 +00006192 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006193 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006194 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006195
Eli Friedman860a3192012-06-16 02:19:17 +00006196 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006197 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006198
Chris Lattner7ef655a2010-01-12 21:23:57 +00006199 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006200 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006201 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006202 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6203 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006204
Chris Lattner7ef655a2010-01-12 21:23:57 +00006205 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006206}
6207
Chandler Carruth13b21be2011-06-27 08:02:19 +00006208/// \brief Diagnose invalid arithmetic on two void pointers.
6209static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006210 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006211 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006212 ? diag::err_typecheck_pointer_arith_void_type
6213 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006214 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6215 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006216}
6217
6218/// \brief Diagnose invalid arithmetic on a void pointer.
6219static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6220 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006221 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006222 ? diag::err_typecheck_pointer_arith_void_type
6223 : diag::ext_gnu_void_ptr)
6224 << 0 /* one pointer */ << Pointer->getSourceRange();
6225}
6226
6227/// \brief Diagnose invalid arithmetic on two function pointers.
6228static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6229 Expr *LHS, Expr *RHS) {
6230 assert(LHS->getType()->isAnyPointerType());
6231 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006232 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006233 ? diag::err_typecheck_pointer_arith_function_type
6234 : diag::ext_gnu_ptr_func_arith)
6235 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6236 // We only show the second type if it differs from the first.
6237 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6238 RHS->getType())
6239 << RHS->getType()->getPointeeType()
6240 << LHS->getSourceRange() << RHS->getSourceRange();
6241}
6242
6243/// \brief Diagnose invalid arithmetic on a function pointer.
6244static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6245 Expr *Pointer) {
6246 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006247 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006248 ? diag::err_typecheck_pointer_arith_function_type
6249 : diag::ext_gnu_ptr_func_arith)
6250 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6251 << 0 /* one pointer, so only one type */
6252 << Pointer->getSourceRange();
6253}
6254
Richard Trieud9f19342011-09-12 18:08:02 +00006255/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006256///
6257/// \returns True if pointer has incomplete type
6258static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6259 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006260 assert(Operand->getType()->isAnyPointerType() &&
6261 !Operand->getType()->isDependentType());
6262 QualType PointeeTy = Operand->getType()->getPointeeType();
6263 return S.RequireCompleteType(Loc, PointeeTy,
6264 diag::err_typecheck_arithmetic_incomplete_type,
6265 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006266}
6267
Chandler Carruth13b21be2011-06-27 08:02:19 +00006268/// \brief Check the validity of an arithmetic pointer operand.
6269///
6270/// If the operand has pointer type, this code will check for pointer types
6271/// which are invalid in arithmetic operations. These will be diagnosed
6272/// appropriately, including whether or not the use is supported as an
6273/// extension.
6274///
6275/// \returns True when the operand is valid to use (even if as an extension).
6276static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6277 Expr *Operand) {
6278 if (!Operand->getType()->isAnyPointerType()) return true;
6279
6280 QualType PointeeTy = Operand->getType()->getPointeeType();
6281 if (PointeeTy->isVoidType()) {
6282 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006283 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006284 }
6285 if (PointeeTy->isFunctionType()) {
6286 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006287 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006288 }
6289
Richard Trieu097ecd22011-09-02 02:15:37 +00006290 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006291
6292 return true;
6293}
6294
6295/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6296/// operands.
6297///
6298/// This routine will diagnose any invalid arithmetic on pointer operands much
6299/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6300/// for emitting a single diagnostic even for operations where both LHS and RHS
6301/// are (potentially problematic) pointers.
6302///
6303/// \returns True when the operand is valid to use (even if as an extension).
6304static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006305 Expr *LHSExpr, Expr *RHSExpr) {
6306 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6307 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006308 if (!isLHSPointer && !isRHSPointer) return true;
6309
6310 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006311 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6312 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006313
6314 // Check for arithmetic on pointers to incomplete types.
6315 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6316 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6317 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006318 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6319 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6320 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006321
David Blaikie4e4d0842012-03-11 07:00:24 +00006322 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006323 }
6324
6325 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6326 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6327 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006328 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6329 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6330 RHSExpr);
6331 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006332
David Blaikie4e4d0842012-03-11 07:00:24 +00006333 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006334 }
6335
John McCall1503f0d2012-07-31 05:14:30 +00006336 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6337 return false;
6338 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6339 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006340
Chandler Carruth13b21be2011-06-27 08:02:19 +00006341 return true;
6342}
6343
Nico Weber1cb2d742012-03-02 22:01:22 +00006344/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6345/// literal.
6346static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6347 Expr *LHSExpr, Expr *RHSExpr) {
6348 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6349 Expr* IndexExpr = RHSExpr;
6350 if (!StrExpr) {
6351 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6352 IndexExpr = LHSExpr;
6353 }
6354
6355 bool IsStringPlusInt = StrExpr &&
6356 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6357 if (!IsStringPlusInt)
6358 return;
6359
6360 llvm::APSInt index;
6361 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6362 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6363 if (index.isNonNegative() &&
6364 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6365 index.isUnsigned()))
6366 return;
6367 }
6368
6369 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6370 Self.Diag(OpLoc, diag::warn_string_plus_int)
6371 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6372
6373 // Only print a fixit for "str" + int, not for int + "str".
6374 if (IndexExpr == RHSExpr) {
6375 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6376 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6377 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6378 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6379 << FixItHint::CreateInsertion(EndLoc, "]");
6380 } else
6381 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6382}
6383
Richard Trieud9f19342011-09-12 18:08:02 +00006384/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006385static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006386 Expr *LHSExpr, Expr *RHSExpr) {
6387 assert(LHSExpr->getType()->isAnyPointerType());
6388 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006389 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006390 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6391 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006392}
6393
Chris Lattner7ef655a2010-01-12 21:23:57 +00006394QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006395 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6396 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006397 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6398
Richard Trieudef75842011-09-06 21:13:51 +00006399 if (LHS.get()->getType()->isVectorType() ||
6400 RHS.get()->getType()->isVectorType()) {
6401 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006402 if (CompLHSTy) *CompLHSTy = compType;
6403 return compType;
6404 }
Steve Naroff49b45262007-07-13 16:58:59 +00006405
Richard Trieudef75842011-09-06 21:13:51 +00006406 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6407 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006408 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006409
Nico Weber1cb2d742012-03-02 22:01:22 +00006410 // Diagnose "string literal" '+' int.
6411 if (Opc == BO_Add)
6412 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6413
Reid Spencer5f016e22007-07-11 17:01:13 +00006414 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006415 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006416 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006417 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006418 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006419
John McCall1503f0d2012-07-31 05:14:30 +00006420 // Type-checking. Ultimately the pointer's going to be in PExp;
6421 // note that we bias towards the LHS being the pointer.
6422 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006423
John McCall1503f0d2012-07-31 05:14:30 +00006424 bool isObjCPointer;
6425 if (PExp->getType()->isPointerType()) {
6426 isObjCPointer = false;
6427 } else if (PExp->getType()->isObjCObjectPointerType()) {
6428 isObjCPointer = true;
6429 } else {
6430 std::swap(PExp, IExp);
6431 if (PExp->getType()->isPointerType()) {
6432 isObjCPointer = false;
6433 } else if (PExp->getType()->isObjCObjectPointerType()) {
6434 isObjCPointer = true;
6435 } else {
6436 return InvalidOperands(Loc, LHS, RHS);
6437 }
6438 }
6439 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006440
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006441 if (!IExp->getType()->isIntegerType())
6442 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006443
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006444 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6445 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006446
John McCall1503f0d2012-07-31 05:14:30 +00006447 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006448 return QualType();
6449
6450 // Check array bounds for pointer arithemtic
6451 CheckArrayAccess(PExp, IExp);
6452
6453 if (CompLHSTy) {
6454 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6455 if (LHSTy.isNull()) {
6456 LHSTy = LHS.get()->getType();
6457 if (LHSTy->isPromotableIntegerType())
6458 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006459 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006460 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006461 }
6462
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006463 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006464}
6465
Chris Lattnereca7be62008-04-07 05:30:13 +00006466// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006467QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006468 SourceLocation Loc,
6469 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006470 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6471
Richard Trieudef75842011-09-06 21:13:51 +00006472 if (LHS.get()->getType()->isVectorType() ||
6473 RHS.get()->getType()->isVectorType()) {
6474 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006475 if (CompLHSTy) *CompLHSTy = compType;
6476 return compType;
6477 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006478
Richard Trieudef75842011-09-06 21:13:51 +00006479 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6480 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006481 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006482
Chris Lattner6e4ab612007-12-09 21:53:25 +00006483 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006484
Chris Lattner6e4ab612007-12-09 21:53:25 +00006485 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006486 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006487 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006488 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006489 }
Mike Stump1eb44332009-09-09 15:08:12 +00006490
Chris Lattner6e4ab612007-12-09 21:53:25 +00006491 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006492 if (LHS.get()->getType()->isAnyPointerType()) {
6493 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006494
Chris Lattnerb5f15622009-04-24 23:50:08 +00006495 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006496 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6497 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006498 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006499
Chris Lattner6e4ab612007-12-09 21:53:25 +00006500 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006501 if (RHS.get()->getType()->isIntegerType()) {
6502 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006503 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006504
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006505 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006506 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6507 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006508
Richard Trieudef75842011-09-06 21:13:51 +00006509 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6510 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006511 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006512
Chris Lattner6e4ab612007-12-09 21:53:25 +00006513 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006514 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006515 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006516 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006517
David Blaikie4e4d0842012-03-11 07:00:24 +00006518 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006519 // Pointee types must be the same: C++ [expr.add]
6520 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006521 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006522 }
6523 } else {
6524 // Pointee types must be compatible C99 6.5.6p3
6525 if (!Context.typesAreCompatible(
6526 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6527 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006528 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006529 return QualType();
6530 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006531 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006532
Chandler Carruth13b21be2011-06-27 08:02:19 +00006533 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006534 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006535 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006536
Richard Trieudef75842011-09-06 21:13:51 +00006537 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006538 return Context.getPointerDiffType();
6539 }
6540 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006541
Richard Trieudef75842011-09-06 21:13:51 +00006542 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006543}
6544
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006545static bool isScopedEnumerationType(QualType T) {
6546 if (const EnumType *ET = dyn_cast<EnumType>(T))
6547 return ET->getDecl()->isScoped();
6548 return false;
6549}
6550
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006551static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006552 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006553 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006554 llvm::APSInt Right;
6555 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006556 if (RHS.get()->isValueDependent() ||
6557 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006558 return;
6559
6560 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006561 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006562 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006563 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006564 return;
6565 }
6566 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006567 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006568 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006569 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006570 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006571 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006572 return;
6573 }
6574 if (Opc != BO_Shl)
6575 return;
6576
6577 // When left shifting an ICE which is signed, we can check for overflow which
6578 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6579 // integers have defined behavior modulo one more than the maximum value
6580 // representable in the result type, so never warn for those.
6581 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006582 if (LHS.get()->isValueDependent() ||
6583 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6584 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006585 return;
6586 llvm::APInt ResultBits =
6587 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6588 if (LeftBits.uge(ResultBits))
6589 return;
6590 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6591 Result = Result.shl(Right);
6592
Ted Kremenekfa821382011-06-15 00:54:52 +00006593 // Print the bit representation of the signed integer as an unsigned
6594 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006595 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006596 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6597
Chandler Carruth21206d52011-02-23 23:34:11 +00006598 // If we are only missing a sign bit, this is less likely to result in actual
6599 // bugs -- if the result is cast back to an unsigned type, it will have the
6600 // expected value. Thus we place this behind a different warning that can be
6601 // turned off separately if needed.
6602 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006603 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006604 << HexResult.str() << LHSType
6605 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006606 return;
6607 }
6608
6609 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006610 << HexResult.str() << Result.getMinSignedBits() << LHSType
6611 << Left.getBitWidth() << LHS.get()->getSourceRange()
6612 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006613}
6614
Chris Lattnereca7be62008-04-07 05:30:13 +00006615// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006616QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006617 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006618 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006619 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6620
Chris Lattnerca5eede2007-12-12 05:47:28 +00006621 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006622 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6623 !RHS.get()->getType()->hasIntegerRepresentation())
6624 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006625
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006626 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6627 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006628 if (isScopedEnumerationType(LHS.get()->getType()) ||
6629 isScopedEnumerationType(RHS.get()->getType())) {
6630 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006631 }
6632
Nate Begeman2207d792009-10-25 02:26:48 +00006633 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006634 if (LHS.get()->getType()->isVectorType() ||
6635 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006636 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006637
Chris Lattnerca5eede2007-12-12 05:47:28 +00006638 // Shifts don't perform usual arithmetic conversions, they just do integer
6639 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006640
John McCall1bc80af2010-12-16 19:28:59 +00006641 // For the LHS, do usual unary conversions, but then reset them away
6642 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006643 ExprResult OldLHS = LHS;
6644 LHS = UsualUnaryConversions(LHS.take());
6645 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006646 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006647 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006648 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006649
6650 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006651 RHS = UsualUnaryConversions(RHS.take());
6652 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006653 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006654
Ryan Flynnd0439682009-08-07 16:20:20 +00006655 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006656 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006657
Chris Lattnerca5eede2007-12-12 05:47:28 +00006658 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006659 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006660}
6661
Chandler Carruth99919472010-07-10 12:30:03 +00006662static bool IsWithinTemplateSpecialization(Decl *D) {
6663 if (DeclContext *DC = D->getDeclContext()) {
6664 if (isa<ClassTemplateSpecializationDecl>(DC))
6665 return true;
6666 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6667 return FD->isFunctionTemplateSpecialization();
6668 }
6669 return false;
6670}
6671
Richard Trieue648ac32011-09-02 03:48:46 +00006672/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006673static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6674 ExprResult &RHS) {
6675 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6676 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006677
6678 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6679 if (!LHSEnumType)
6680 return;
6681 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6682 if (!RHSEnumType)
6683 return;
6684
6685 // Ignore anonymous enums.
6686 if (!LHSEnumType->getDecl()->getIdentifier())
6687 return;
6688 if (!RHSEnumType->getDecl()->getIdentifier())
6689 return;
6690
6691 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6692 return;
6693
6694 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6695 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006696 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006697}
6698
Richard Trieu7be1be02011-09-02 02:55:45 +00006699/// \brief Diagnose bad pointer comparisons.
6700static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006701 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006702 bool IsError) {
6703 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006704 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006705 << LHS.get()->getType() << RHS.get()->getType()
6706 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006707}
6708
6709/// \brief Returns false if the pointers are converted to a composite type,
6710/// true otherwise.
6711static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006712 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006713 // C++ [expr.rel]p2:
6714 // [...] Pointer conversions (4.10) and qualification
6715 // conversions (4.4) are performed on pointer operands (or on
6716 // a pointer operand and a null pointer constant) to bring
6717 // them to their composite pointer type. [...]
6718 //
6719 // C++ [expr.eq]p1 uses the same notion for (in)equality
6720 // comparisons of pointers.
6721
6722 // C++ [expr.eq]p2:
6723 // In addition, pointers to members can be compared, or a pointer to
6724 // member and a null pointer constant. Pointer to member conversions
6725 // (4.11) and qualification conversions (4.4) are performed to bring
6726 // them to a common type. If one operand is a null pointer constant,
6727 // the common type is the type of the other operand. Otherwise, the
6728 // common type is a pointer to member type similar (4.4) to the type
6729 // of one of the operands, with a cv-qualification signature (4.4)
6730 // that is the union of the cv-qualification signatures of the operand
6731 // types.
6732
Richard Trieuba261492011-09-06 21:27:33 +00006733 QualType LHSType = LHS.get()->getType();
6734 QualType RHSType = RHS.get()->getType();
6735 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6736 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006737
6738 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006739 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006740 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006741 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006742 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006743 return true;
6744 }
6745
6746 if (NonStandardCompositeType)
6747 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006748 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6749 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006750
Richard Trieuba261492011-09-06 21:27:33 +00006751 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6752 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006753 return false;
6754}
6755
6756static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006757 ExprResult &LHS,
6758 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006759 bool IsError) {
6760 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6761 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006762 << LHS.get()->getType() << RHS.get()->getType()
6763 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006764}
6765
Jordan Rose9f63a452012-06-08 21:14:25 +00006766static bool isObjCObjectLiteral(ExprResult &E) {
6767 switch (E.get()->getStmtClass()) {
6768 case Stmt::ObjCArrayLiteralClass:
6769 case Stmt::ObjCDictionaryLiteralClass:
6770 case Stmt::ObjCStringLiteralClass:
6771 case Stmt::ObjCBoxedExprClass:
6772 return true;
6773 default:
6774 // Note that ObjCBoolLiteral is NOT an object literal!
6775 return false;
6776 }
6777}
6778
Jordan Rose8d872ca2012-07-17 17:46:40 +00006779static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6780 // Get the LHS object's interface type.
6781 QualType Type = LHS->getType();
6782 QualType InterfaceType;
6783 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6784 InterfaceType = PTy->getPointeeType();
6785 if (const ObjCObjectType *iQFaceTy =
6786 InterfaceType->getAsObjCQualifiedInterfaceType())
6787 InterfaceType = iQFaceTy->getBaseType();
6788 } else {
6789 // If this is not actually an Objective-C object, bail out.
6790 return false;
6791 }
6792
6793 // If the RHS isn't an Objective-C object, bail out.
6794 if (!RHS->getType()->isObjCObjectPointerType())
6795 return false;
6796
6797 // Try to find the -isEqual: method.
6798 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6799 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6800 InterfaceType,
6801 /*instance=*/true);
6802 if (!Method) {
6803 if (Type->isObjCIdType()) {
6804 // For 'id', just check the global pool.
6805 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6806 /*receiverId=*/true,
6807 /*warn=*/false);
6808 } else {
6809 // Check protocols.
6810 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6811 cast<ObjCObjectPointerType>(Type),
6812 /*instance=*/true);
6813 }
6814 }
6815
6816 if (!Method)
6817 return false;
6818
6819 QualType T = Method->param_begin()[0]->getType();
6820 if (!T->isObjCObjectPointerType())
6821 return false;
6822
6823 QualType R = Method->getResultType();
6824 if (!R->isScalarType())
6825 return false;
6826
6827 return true;
6828}
6829
6830static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6831 ExprResult &LHS, ExprResult &RHS,
6832 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006833 Expr *Literal;
6834 Expr *Other;
6835 if (isObjCObjectLiteral(LHS)) {
6836 Literal = LHS.get();
6837 Other = RHS.get();
6838 } else {
6839 Literal = RHS.get();
6840 Other = LHS.get();
6841 }
6842
6843 // Don't warn on comparisons against nil.
6844 Other = Other->IgnoreParenCasts();
6845 if (Other->isNullPointerConstant(S.getASTContext(),
6846 Expr::NPC_ValueDependentIsNotNull))
6847 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006848
Jordan Roseeec207f2012-07-17 17:46:44 +00006849 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006850 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006851 enum {
6852 LK_Array,
6853 LK_Dictionary,
6854 LK_Numeric,
6855 LK_Boxed,
6856 LK_String
6857 } LiteralKind;
6858
Jordan Rose9f63a452012-06-08 21:14:25 +00006859 switch (Literal->getStmtClass()) {
6860 case Stmt::ObjCStringLiteralClass:
6861 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006862 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006863 break;
6864 case Stmt::ObjCArrayLiteralClass:
6865 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006866 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006867 break;
6868 case Stmt::ObjCDictionaryLiteralClass:
6869 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006870 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006871 break;
6872 case Stmt::ObjCBoxedExprClass: {
6873 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6874 switch (Inner->getStmtClass()) {
6875 case Stmt::IntegerLiteralClass:
6876 case Stmt::FloatingLiteralClass:
6877 case Stmt::CharacterLiteralClass:
6878 case Stmt::ObjCBoolLiteralExprClass:
6879 case Stmt::CXXBoolLiteralExprClass:
6880 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006881 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006882 break;
6883 case Stmt::ImplicitCastExprClass: {
6884 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6885 // Boolean literals can be represented by implicit casts.
6886 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006887 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006888 break;
6889 }
6890 // FALLTHROUGH
6891 }
6892 default:
6893 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006894 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006895 break;
6896 }
6897 break;
6898 }
6899 default:
6900 llvm_unreachable("Unknown Objective-C object literal kind");
6901 }
6902
Jordan Roseeec207f2012-07-17 17:46:44 +00006903 if (LiteralKind == LK_String)
6904 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6905 << Literal->getSourceRange();
6906 else
6907 S.Diag(Loc, diag::warn_objc_literal_comparison)
6908 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006909
Jordan Rose8d872ca2012-07-17 17:46:40 +00006910 if (BinaryOperator::isEqualityOp(Opc) &&
6911 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6912 SourceLocation Start = LHS.get()->getLocStart();
6913 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6914 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006915
Jordan Rose8d872ca2012-07-17 17:46:40 +00006916 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6917 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6918 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6919 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006920 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006921}
6922
Douglas Gregor0c6db942009-05-04 06:07:12 +00006923// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006924QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006925 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006926 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006927 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6928
John McCall2de56d12010-08-25 11:45:40 +00006929 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006930
Chris Lattner02dd4b12009-12-05 05:40:13 +00006931 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006932 if (LHS.get()->getType()->isVectorType() ||
6933 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006934 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006935
Richard Trieuf1775fb2011-09-06 21:43:51 +00006936 QualType LHSType = LHS.get()->getType();
6937 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006938
Richard Trieuf1775fb2011-09-06 21:43:51 +00006939 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6940 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006941
Richard Trieuf1775fb2011-09-06 21:43:51 +00006942 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006943
Richard Trieuf1775fb2011-09-06 21:43:51 +00006944 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006945 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006946 !LHS.get()->getLocStart().isMacroID() &&
6947 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006948 // For non-floating point types, check for self-comparisons of the form
6949 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6950 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006951 //
6952 // NOTE: Don't warn about comparison expressions resulting from macro
6953 // expansion. Also don't warn about comparisons which are only self
6954 // comparisons within a template specialization. The warnings should catch
6955 // obvious cases in the definition of the template anyways. The idea is to
6956 // warn when the typed comparison operator will always evaluate to the same
6957 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006958 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006959 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006960 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006961 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006962 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006963 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006964 << (Opc == BO_EQ
6965 || Opc == BO_LE
6966 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006967 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006968 !DRL->getDecl()->getType()->isReferenceType() &&
6969 !DRR->getDecl()->getType()->isReferenceType()) {
6970 // what is it always going to eval to?
6971 char always_evals_to;
6972 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006973 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006974 always_evals_to = 0; // false
6975 break;
John McCall2de56d12010-08-25 11:45:40 +00006976 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006977 always_evals_to = 1; // true
6978 break;
6979 default:
6980 // best we can say is 'a constant'
6981 always_evals_to = 2; // e.g. array1 <= array2
6982 break;
6983 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006984 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006985 << 1 // array
6986 << always_evals_to);
6987 }
6988 }
Chandler Carruth99919472010-07-10 12:30:03 +00006989 }
Mike Stump1eb44332009-09-09 15:08:12 +00006990
Chris Lattner55660a72009-03-08 19:39:53 +00006991 if (isa<CastExpr>(LHSStripped))
6992 LHSStripped = LHSStripped->IgnoreParenCasts();
6993 if (isa<CastExpr>(RHSStripped))
6994 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006995
Chris Lattner55660a72009-03-08 19:39:53 +00006996 // Warn about comparisons against a string constant (unless the other
6997 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006998 Expr *literalString = 0;
6999 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007000 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007001 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007002 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007003 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007004 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007005 } else if ((isa<StringLiteral>(RHSStripped) ||
7006 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007007 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007008 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007009 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007010 literalStringStripped = RHSStripped;
7011 }
7012
7013 if (literalString) {
7014 std::string resultComparison;
7015 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007016 case BO_LT: resultComparison = ") < 0"; break;
7017 case BO_GT: resultComparison = ") > 0"; break;
7018 case BO_LE: resultComparison = ") <= 0"; break;
7019 case BO_GE: resultComparison = ") >= 0"; break;
7020 case BO_EQ: resultComparison = ") == 0"; break;
7021 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00007022 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00007023 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007024
Ted Kremenek351ba912011-02-23 01:52:04 +00007025 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007026 PDiag(diag::warn_stringcompare)
7027 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007028 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007029 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007030 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007031
Douglas Gregord64fdd02010-06-08 19:50:34 +00007032 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00007033 if (LHS.get()->getType()->isArithmeticType() &&
7034 RHS.get()->getType()->isArithmeticType()) {
7035 UsualArithmeticConversions(LHS, RHS);
7036 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007037 return QualType();
7038 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007039 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007040 LHS = UsualUnaryConversions(LHS.take());
7041 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007042 return QualType();
7043
Richard Trieuf1775fb2011-09-06 21:43:51 +00007044 RHS = UsualUnaryConversions(RHS.take());
7045 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007046 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007047 }
7048
Richard Trieuf1775fb2011-09-06 21:43:51 +00007049 LHSType = LHS.get()->getType();
7050 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007051
Douglas Gregor447b69e2008-11-19 03:25:36 +00007052 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007053 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007054
Richard Trieuccd891a2011-09-09 01:45:06 +00007055 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007056 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007057 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007058 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007059 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007060 if (LHSType->hasFloatingRepresentation())
7061 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007062
Richard Trieuf1775fb2011-09-06 21:43:51 +00007063 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007064 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007065 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007066
Richard Trieuf1775fb2011-09-06 21:43:51 +00007067 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007068 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007069 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007070 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007071
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007072 // All of the following pointer-related warnings are GCC extensions, except
7073 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007074 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007075 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007076 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007077 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007078 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007079
David Blaikie4e4d0842012-03-11 07:00:24 +00007080 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007081 if (LCanPointeeTy == RCanPointeeTy)
7082 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007083 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007084 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7085 // Valid unless comparison between non-null pointer and function pointer
7086 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007087 // In a SFINAE context, we treat this as a hard error to maintain
7088 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007089 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7090 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007091 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007092 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007093
7094 if (isSFINAEContext())
7095 return QualType();
7096
Richard Trieuf1775fb2011-09-06 21:43:51 +00007097 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007098 return ResultTy;
7099 }
7100 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007101
Richard Trieuf1775fb2011-09-06 21:43:51 +00007102 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007103 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007104 else
7105 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007106 }
Eli Friedman3075e762009-08-23 00:27:47 +00007107 // C99 6.5.9p2 and C99 6.5.8p2
7108 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7109 RCanPointeeTy.getUnqualifiedType())) {
7110 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007111 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007112 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007113 << LHSType << RHSType << LHS.get()->getSourceRange()
7114 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007115 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007116 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007117 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7118 // Valid unless comparison between non-null pointer and function pointer
7119 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007120 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007121 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007122 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007123 } else {
7124 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007125 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007126 }
John McCall34d6f932011-03-11 04:25:25 +00007127 if (LCanPointeeTy != RCanPointeeTy) {
7128 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007129 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007130 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007131 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007132 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007133 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007134 }
Mike Stump1eb44332009-09-09 15:08:12 +00007135
David Blaikie4e4d0842012-03-11 07:00:24 +00007136 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007137 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007138 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007139 return ResultTy;
7140
Mike Stump1eb44332009-09-09 15:08:12 +00007141 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007142 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007143 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007144 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007145 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007146 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7147 RHS = ImpCastExprToType(RHS.take(), LHSType,
7148 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007149 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007150 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007151 return ResultTy;
7152 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007153 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007154 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007155 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007156 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7157 LHS = ImpCastExprToType(LHS.take(), RHSType,
7158 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007159 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007160 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007161 return ResultTy;
7162 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007163
7164 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007165 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007166 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7167 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007168 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007169 else
7170 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007171 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007172
7173 // Handle scoped enumeration types specifically, since they don't promote
7174 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007175 if (LHS.get()->getType()->isEnumeralType() &&
7176 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7177 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007178 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007179 }
Mike Stump1eb44332009-09-09 15:08:12 +00007180
Steve Naroff1c7d0672008-09-04 15:10:53 +00007181 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007182 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007183 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007184 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7185 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007186
Steve Naroff1c7d0672008-09-04 15:10:53 +00007187 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007188 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007189 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007190 << LHSType << RHSType << LHS.get()->getSourceRange()
7191 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007192 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007193 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007194 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007195 }
John Wiegley429bb272011-04-08 18:41:53 +00007196
Steve Naroff59f53942008-09-28 01:11:11 +00007197 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007198 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007199 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7200 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007201 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007202 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007203 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007204 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007205 ->getPointeeType()->isVoidType())))
7206 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007207 << LHSType << RHSType << LHS.get()->getSourceRange()
7208 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007209 }
John McCall34d6f932011-03-11 04:25:25 +00007210 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007211 LHS = ImpCastExprToType(LHS.take(), RHSType,
7212 RHSType->isPointerType() ? CK_BitCast
7213 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007214 else
John McCall1d9b3b22011-09-09 05:25:32 +00007215 RHS = ImpCastExprToType(RHS.take(), LHSType,
7216 LHSType->isPointerType() ? CK_BitCast
7217 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007218 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007219 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007220
Richard Trieuf1775fb2011-09-06 21:43:51 +00007221 if (LHSType->isObjCObjectPointerType() ||
7222 RHSType->isObjCObjectPointerType()) {
7223 const PointerType *LPT = LHSType->getAs<PointerType>();
7224 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007225 if (LPT || RPT) {
7226 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7227 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007228
Steve Naroffa8069f12008-11-17 19:49:16 +00007229 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007230 !Context.typesAreCompatible(LHSType, RHSType)) {
7231 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007232 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007233 }
John McCall34d6f932011-03-11 04:25:25 +00007234 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007235 LHS = ImpCastExprToType(LHS.take(), RHSType,
7236 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007237 else
John McCall1d9b3b22011-09-09 05:25:32 +00007238 RHS = ImpCastExprToType(RHS.take(), LHSType,
7239 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007240 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007241 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007242 if (LHSType->isObjCObjectPointerType() &&
7243 RHSType->isObjCObjectPointerType()) {
7244 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7245 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007246 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007247 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007248 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007249
John McCall34d6f932011-03-11 04:25:25 +00007250 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007251 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007252 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007253 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007254 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007255 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007256 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007257 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7258 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007259 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007260 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007261 if (LangOpts.DebuggerSupport) {
7262 // Under a debugger, allow the comparison of pointers to integers,
7263 // since users tend to want to compare addresses.
7264 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007265 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007266 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007267 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007268 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007269 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007270 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007271 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7272 isError = true;
7273 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007274 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007275
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007276 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007277 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007278 << LHSType << RHSType << LHS.get()->getSourceRange()
7279 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007280 if (isError)
7281 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007282 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007283
Richard Trieuf1775fb2011-09-06 21:43:51 +00007284 if (LHSType->isIntegerType())
7285 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007286 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007287 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007288 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007289 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007290 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007291 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007292
Steve Naroff39218df2008-09-04 16:56:14 +00007293 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007294 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007295 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7296 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007297 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007298 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007299 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007300 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7301 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007302 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007303 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007304
Richard Trieuf1775fb2011-09-06 21:43:51 +00007305 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007306}
7307
Tanya Lattner4f692c22012-01-16 21:02:28 +00007308
7309// Return a signed type that is of identical size and number of elements.
7310// For floating point vectors, return an integer type of identical size
7311// and number of elements.
7312QualType Sema::GetSignedVectorType(QualType V) {
7313 const VectorType *VTy = V->getAs<VectorType>();
7314 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7315 if (TypeSize == Context.getTypeSize(Context.CharTy))
7316 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7317 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7318 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7319 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7320 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7321 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7322 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7323 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7324 "Unhandled vector element size in vector compare");
7325 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7326}
7327
Nate Begemanbe2341d2008-07-14 18:02:46 +00007328/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007329/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007330/// like a scalar comparison, a vector comparison produces a vector of integer
7331/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007332QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007333 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007334 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007335 // Check to make sure we're operating on vectors of the same type and width,
7336 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007337 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007338 if (vType.isNull())
7339 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007340
Richard Trieu9f60dee2011-09-07 01:19:57 +00007341 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007342
Anton Yartsev7870b132011-03-27 15:36:07 +00007343 // If AltiVec, the comparison results in a numeric type, i.e.
7344 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007345 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007346 return Context.getLogicalOperationType();
7347
Nate Begemanbe2341d2008-07-14 18:02:46 +00007348 // For non-floating point types, check for self-comparisons of the form
7349 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7350 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007351 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007352 if (DeclRefExpr* DRL
7353 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7354 if (DeclRefExpr* DRR
7355 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007356 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007357 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007358 PDiag(diag::warn_comparison_always)
7359 << 0 // self-
7360 << 2 // "a constant"
7361 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007362 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007363
Nate Begemanbe2341d2008-07-14 18:02:46 +00007364 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007365 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007366 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007367 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007368 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007369
7370 // Return a signed type for the vector.
7371 return GetSignedVectorType(LHSType);
7372}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007373
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007374QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7375 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007376 // Ensure that either both operands are of the same vector type, or
7377 // one operand is of a vector type and the other is of its element type.
7378 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7379 if (vType.isNull() || vType->isFloatingType())
7380 return InvalidOperands(Loc, LHS, RHS);
7381
7382 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007383}
7384
Reid Spencer5f016e22007-07-11 17:01:13 +00007385inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007386 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007387 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7388
Richard Trieu9f60dee2011-09-07 01:19:57 +00007389 if (LHS.get()->getType()->isVectorType() ||
7390 RHS.get()->getType()->isVectorType()) {
7391 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7392 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007393 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007394
Richard Trieu9f60dee2011-09-07 01:19:57 +00007395 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007396 }
Steve Naroff90045e82007-07-13 23:32:42 +00007397
Richard Trieu9f60dee2011-09-07 01:19:57 +00007398 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7399 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007400 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007401 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007402 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007403 LHS = LHSResult.take();
7404 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007405
Eli Friedman860a3192012-06-16 02:19:17 +00007406 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007407 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007408 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007409}
7410
7411inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007412 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007413
Tanya Lattner4f692c22012-01-16 21:02:28 +00007414 // Check vector operands differently.
7415 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7416 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7417
Chris Lattner90a8f272010-07-13 19:41:32 +00007418 // Diagnose cases where the user write a logical and/or but probably meant a
7419 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7420 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007421 if (LHS.get()->getType()->isIntegerType() &&
7422 !LHS.get()->getType()->isBooleanType() &&
7423 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007424 // Don't warn in macros or template instantiations.
7425 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007426 // If the RHS can be constant folded, and if it constant folds to something
7427 // that isn't 0 or 1 (which indicate a potential logical operation that
7428 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007429 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007430 llvm::APSInt Result;
7431 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007432 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007433 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007434 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007435 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007436 << (Opc == BO_LAnd ? "&&" : "||");
7437 // Suggest replacing the logical operator with the bitwise version
7438 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7439 << (Opc == BO_LAnd ? "&" : "|")
7440 << FixItHint::CreateReplacement(SourceRange(
7441 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007442 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007443 Opc == BO_LAnd ? "&" : "|");
7444 if (Opc == BO_LAnd)
7445 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7446 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7447 << FixItHint::CreateRemoval(
7448 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007449 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007450 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007451 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007452 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007453 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007454 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007455
David Blaikie4e4d0842012-03-11 07:00:24 +00007456 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007457 LHS = UsualUnaryConversions(LHS.take());
7458 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007459 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007460
Richard Trieu9f60dee2011-09-07 01:19:57 +00007461 RHS = UsualUnaryConversions(RHS.take());
7462 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007463 return QualType();
7464
Richard Trieu9f60dee2011-09-07 01:19:57 +00007465 if (!LHS.get()->getType()->isScalarType() ||
7466 !RHS.get()->getType()->isScalarType())
7467 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007468
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007469 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007470 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007471
John McCall75f7c0f2010-06-04 00:29:51 +00007472 // The following is safe because we only use this method for
7473 // non-overloadable operands.
7474
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007475 // C++ [expr.log.and]p1
7476 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007477 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007478 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7479 if (LHSRes.isInvalid())
7480 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007481 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007482
Richard Trieu9f60dee2011-09-07 01:19:57 +00007483 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7484 if (RHSRes.isInvalid())
7485 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007486 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007487
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007488 // C++ [expr.log.and]p2
7489 // C++ [expr.log.or]p2
7490 // The result is a bool.
7491 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007492}
7493
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007494/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7495/// is a read-only property; return true if so. A readonly property expression
7496/// depends on various declarations and thus must be treated specially.
7497///
Mike Stump1eb44332009-09-09 15:08:12 +00007498static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007499 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7500 if (!PropExpr) return false;
7501 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007502
John McCall3c3b7f92011-10-25 17:37:35 +00007503 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7504 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007505 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007506 PropExpr->getBase()->getType();
7507
John McCall3c3b7f92011-10-25 17:37:35 +00007508 if (const ObjCObjectPointerType *OPT =
7509 BaseType->getAsObjCInterfacePointerType())
7510 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7511 if (S.isPropertyReadonly(PDecl, IFace))
7512 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007513 return false;
7514}
7515
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007516static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007517 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7518 if (!ME) return false;
7519 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7520 ObjCMessageExpr *Base =
7521 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7522 if (!Base) return false;
7523 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007524}
7525
John McCall78dae242012-03-13 00:37:01 +00007526/// Is the given expression (which must be 'const') a reference to a
7527/// variable which was originally non-const, but which has become
7528/// 'const' due to being captured within a block?
7529enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7530static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7531 assert(E->isLValue() && E->getType().isConstQualified());
7532 E = E->IgnoreParens();
7533
7534 // Must be a reference to a declaration from an enclosing scope.
7535 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7536 if (!DRE) return NCCK_None;
7537 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7538
7539 // The declaration must be a variable which is not declared 'const'.
7540 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7541 if (!var) return NCCK_None;
7542 if (var->getType().isConstQualified()) return NCCK_None;
7543 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7544
7545 // Decide whether the first capture was for a block or a lambda.
7546 DeclContext *DC = S.CurContext;
7547 while (DC->getParent() != var->getDeclContext())
7548 DC = DC->getParent();
7549 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7550}
7551
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007552/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7553/// emit an error and return true. If so, return false.
7554static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007555 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007556 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007557 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007558 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007559 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7560 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007561 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7562 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007563 if (IsLV == Expr::MLV_Valid)
7564 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007565
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007566 unsigned Diag = 0;
7567 bool NeedType = false;
7568 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007569 case Expr::MLV_ConstQualified:
7570 Diag = diag::err_typecheck_assign_const;
7571
John McCall78dae242012-03-13 00:37:01 +00007572 // Use a specialized diagnostic when we're assigning to an object
7573 // from an enclosing function or block.
7574 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7575 if (NCCK == NCCK_Block)
7576 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7577 else
7578 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7579 break;
7580 }
7581
John McCall7acddac2011-06-17 06:42:21 +00007582 // In ARC, use some specialized diagnostics for occasions where we
7583 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007584 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007585 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7586 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7587 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7588
John McCall7acddac2011-06-17 06:42:21 +00007589 // Use the normal diagnostic if it's pseudo-__strong but the
7590 // user actually wrote 'const'.
7591 if (var->isARCPseudoStrong() &&
7592 (!var->getTypeSourceInfo() ||
7593 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7594 // There are two pseudo-strong cases:
7595 // - self
John McCallf85e1932011-06-15 23:02:42 +00007596 ObjCMethodDecl *method = S.getCurMethodDecl();
7597 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007598 Diag = method->isClassMethod()
7599 ? diag::err_typecheck_arc_assign_self_class_method
7600 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007601
7602 // - fast enumeration variables
7603 else
John McCallf85e1932011-06-15 23:02:42 +00007604 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007605
John McCallf85e1932011-06-15 23:02:42 +00007606 SourceRange Assign;
7607 if (Loc != OrigLoc)
7608 Assign = SourceRange(OrigLoc, OrigLoc);
7609 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7610 // We need to preserve the AST regardless, so migration tool
7611 // can do its job.
7612 return false;
7613 }
7614 }
7615 }
7616
7617 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007618 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007619 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007620 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7621 NeedType = true;
7622 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007623 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007624 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7625 NeedType = true;
7626 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007627 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007628 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7629 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007630 case Expr::MLV_Valid:
7631 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007632 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007633 case Expr::MLV_MemberFunction:
7634 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007635 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7636 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007637 case Expr::MLV_IncompleteType:
7638 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007639 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007640 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007641 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007642 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7643 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007644 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007645 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007646 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007647 case Expr::MLV_InvalidMessageExpression:
7648 Diag = diag::error_readonly_message_assignment;
7649 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007650 case Expr::MLV_SubObjCPropertySetting:
7651 Diag = diag::error_no_subobject_property_setting;
7652 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007653 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007654
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007655 SourceRange Assign;
7656 if (Loc != OrigLoc)
7657 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007658 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007659 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007660 else
Mike Stump1eb44332009-09-09 15:08:12 +00007661 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007662 return true;
7663}
7664
Nico Weber7c81b432012-07-03 02:03:06 +00007665static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7666 SourceLocation Loc,
7667 Sema &Sema) {
7668 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007669 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7670 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7671 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7672 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007673 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007674 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007675
Nico Weber7c81b432012-07-03 02:03:06 +00007676 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007677 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7678 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7679 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7680 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7681 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7682 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007683 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007684 }
7685}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007686
7687// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007688QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007689 SourceLocation Loc,
7690 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007691 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7692
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007693 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007694 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007695 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007696
Richard Trieu268942b2011-09-07 01:33:52 +00007697 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007698 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7699 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007700 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007701 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007702 Expr *RHSCheck = RHS.get();
7703
Nico Weber7c81b432012-07-03 02:03:06 +00007704 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007705
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007706 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007707 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007708 if (RHS.isInvalid())
7709 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007710 // Special case of NSObject attributes on c-style pointer types.
7711 if (ConvTy == IncompatiblePointer &&
7712 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007713 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007714 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007715 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007716 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007717
John McCallf89e55a2010-11-18 06:31:45 +00007718 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007719 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007720 Diag(Loc, diag::err_objc_object_assignment)
7721 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007722
Chris Lattner2c156472008-08-21 18:04:13 +00007723 // If the RHS is a unary plus or minus, check to see if they = and + are
7724 // right next to each other. If so, the user may have typo'd "x =+ 4"
7725 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007726 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7727 RHSCheck = ICE->getSubExpr();
7728 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007729 if ((UO->getOpcode() == UO_Plus ||
7730 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007731 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007732 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007733 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007734 // And there is a space or other character before the subexpr of the
7735 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007736 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007737 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007738 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007739 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007740 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007741 }
Chris Lattner2c156472008-08-21 18:04:13 +00007742 }
John McCallf85e1932011-06-15 23:02:42 +00007743
7744 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00007745 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7746 // Warn about retain cycles where a block captures the LHS, but
7747 // not if the LHS is a simple variable into which the block is
7748 // being stored...unless that variable can be captured by reference!
7749 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7750 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7751 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7752 checkRetainCycles(LHSExpr, RHS.get());
7753
Jordan Rose58b6bdc2012-09-28 22:21:30 +00007754 // It is safe to assign a weak reference into a strong variable.
7755 // Although this code can still have problems:
7756 // id x = self.weakProp;
7757 // id y = self.weakProp;
7758 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7759 // paths through the function. This should be revisited if
7760 // -Wrepeated-use-of-weak is made flow-sensitive.
7761 DiagnosticsEngine::Level Level =
7762 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7763 RHS.get()->getLocStart());
7764 if (Level != DiagnosticsEngine::Ignored)
7765 getCurFunction()->markSafeWeakUse(RHS.get());
7766
Jordan Rosee10f4d32012-09-15 02:48:31 +00007767 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00007768 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00007769 }
John McCallf85e1932011-06-15 23:02:42 +00007770 }
Chris Lattner2c156472008-08-21 18:04:13 +00007771 } else {
7772 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007773 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007774 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007775
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007776 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007777 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007778 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007779
Richard Trieu268942b2011-09-07 01:33:52 +00007780 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007781
Reid Spencer5f016e22007-07-11 17:01:13 +00007782 // C99 6.5.16p3: The type of an assignment expression is the type of the
7783 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007784 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007785 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7786 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007787 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007788 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007789 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007790 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007791}
7792
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007793// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007794static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007795 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007796 LHS = S.CheckPlaceholderExpr(LHS.take());
7797 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007798 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007799 return QualType();
7800
John McCallcf2e5062010-10-12 07:14:40 +00007801 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7802 // operands, but not unary promotions.
7803 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007804
John McCallf6a16482010-12-04 03:47:34 +00007805 // So we treat the LHS as a ignored value, and in C++ we allow the
7806 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007807 LHS = S.IgnoredValueConversions(LHS.take());
7808 if (LHS.isInvalid())
7809 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007810
Eli Friedmana6115062012-05-24 00:47:05 +00007811 S.DiagnoseUnusedExprResult(LHS.get());
7812
David Blaikie4e4d0842012-03-11 07:00:24 +00007813 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007814 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7815 if (RHS.isInvalid())
7816 return QualType();
7817 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007818 S.RequireCompleteType(Loc, RHS.get()->getType(),
7819 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007820 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007821
John Wiegley429bb272011-04-08 18:41:53 +00007822 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007823}
7824
Steve Naroff49b45262007-07-13 16:58:59 +00007825/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7826/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007827static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7828 ExprValueKind &VK,
7829 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007830 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007831 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007832 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007833
Chris Lattner3528d352008-11-21 07:05:48 +00007834 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007835 // Atomic types can be used for increment / decrement where the non-atomic
7836 // versions can, so ignore the _Atomic() specifier for the purpose of
7837 // checking.
7838 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7839 ResType = ResAtomicType->getValueType();
7840
Chris Lattner3528d352008-11-21 07:05:48 +00007841 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007842
David Blaikie4e4d0842012-03-11 07:00:24 +00007843 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007844 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007845 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007846 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007847 return QualType();
7848 }
7849 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007850 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007851 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007852 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007853 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007854 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007855 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007856 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007857 } else if (ResType->isObjCObjectPointerType()) {
7858 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7859 // Otherwise, we just need a complete type.
7860 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7861 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7862 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007863 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007864 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007865 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007866 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007867 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007868 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007869 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007870 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007871 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007872 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007873 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007874 } else {
John McCall09431682010-11-18 19:01:18 +00007875 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007876 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007877 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007878 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007879 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007880 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007881 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007882 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007883 // In C++, a prefix increment is the same type as the operand. Otherwise
7884 // (in C or with postfix), the increment is the unqualified type of the
7885 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007886 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007887 VK = VK_LValue;
7888 return ResType;
7889 } else {
7890 VK = VK_RValue;
7891 return ResType.getUnqualifiedType();
7892 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007893}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007894
7895
Anders Carlsson369dee42008-02-01 07:15:58 +00007896/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007897/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007898/// where the declaration is needed for type checking. We only need to
7899/// handle cases when the expression references a function designator
7900/// or is an lvalue. Here are some examples:
7901/// - &(x) => x
7902/// - &*****f => f for f a function designator.
7903/// - &s.xx => s
7904/// - &s.zz[1].yy -> s, if zz is an array
7905/// - *(x + 1) -> x, if x is an array
7906/// - &"123"[2] -> 0
7907/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007908static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007909 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007910 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007911 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007912 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007913 // If this is an arrow operator, the address is an offset from
7914 // the base's value, so the object the base refers to is
7915 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007916 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007917 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007918 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007919 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007920 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007921 // FIXME: This code shouldn't be necessary! We should catch the implicit
7922 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007923 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7924 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7925 if (ICE->getSubExpr()->getType()->isArrayType())
7926 return getPrimaryDecl(ICE->getSubExpr());
7927 }
7928 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007929 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007930 case Stmt::UnaryOperatorClass: {
7931 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007932
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007933 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007934 case UO_Real:
7935 case UO_Imag:
7936 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007937 return getPrimaryDecl(UO->getSubExpr());
7938 default:
7939 return 0;
7940 }
7941 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007942 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007943 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007944 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007945 // If the result of an implicit cast is an l-value, we care about
7946 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007947 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007948 default:
7949 return 0;
7950 }
7951}
7952
Richard Trieu5520f232011-09-07 21:46:33 +00007953namespace {
7954 enum {
7955 AO_Bit_Field = 0,
7956 AO_Vector_Element = 1,
7957 AO_Property_Expansion = 2,
7958 AO_Register_Variable = 3,
7959 AO_No_Error = 4
7960 };
7961}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007962/// \brief Diagnose invalid operand for address of operations.
7963///
7964/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007965static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7966 Expr *E, unsigned Type) {
7967 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7968}
7969
Reid Spencer5f016e22007-07-11 17:01:13 +00007970/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007971/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007972/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007973/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007974/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007975/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007976/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007977static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007978 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007979 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7980 if (PTy->getKind() == BuiltinType::Overload) {
7981 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7982 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7983 << OrigOp.get()->getSourceRange();
7984 return QualType();
7985 }
7986
7987 return S.Context.OverloadTy;
7988 }
7989
7990 if (PTy->getKind() == BuiltinType::UnknownAny)
7991 return S.Context.UnknownAnyTy;
7992
7993 if (PTy->getKind() == BuiltinType::BoundMember) {
7994 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7995 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007996 return QualType();
7997 }
John McCall3c3b7f92011-10-25 17:37:35 +00007998
7999 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8000 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00008001 }
John McCall9c72c602010-08-27 09:08:28 +00008002
John McCall3c3b7f92011-10-25 17:37:35 +00008003 if (OrigOp.get()->isTypeDependent())
8004 return S.Context.DependentTy;
8005
8006 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008007
John McCall9c72c602010-08-27 09:08:28 +00008008 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00008009 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008010
David Blaikie4e4d0842012-03-11 07:00:24 +00008011 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008012 // Implement C99-only parts of addressof rules.
8013 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008014 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008015 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8016 // (assuming the deref expression is valid).
8017 return uOp->getSubExpr()->getType();
8018 }
8019 // Technically, there should be a check for array subscript
8020 // expressions here, but the result of one is always an lvalue anyway.
8021 }
John McCall5808ce42011-02-03 08:15:49 +00008022 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008023 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00008024 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008025
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008026 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008027 bool sfinae = S.isSFINAEContext();
8028 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8029 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008030 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008031 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008032 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008033 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008034 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008035 } else if (lval == Expr::LV_MemberFunction) {
8036 // If it's an instance method, make a member pointer.
8037 // The expression must have exactly the form &A::foo.
8038
8039 // If the underlying expression isn't a decl ref, give up.
8040 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008041 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008042 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008043 return QualType();
8044 }
8045 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8046 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8047
8048 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00008049 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00008050 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008051 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008052
8053 // The method was named without a qualifier.
8054 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00008055 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008056 << op->getSourceRange();
8057 }
8058
John McCall09431682010-11-18 19:01:18 +00008059 return S.Context.getMemberPointerType(op->getType(),
8060 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008061 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008062 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008063 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008064 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008065 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008066 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008067 AddressOfError = AO_Property_Expansion;
8068 } else {
8069 // FIXME: emit more specific diag...
8070 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8071 << op->getSourceRange();
8072 return QualType();
8073 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008074 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008075 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008076 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008077 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008078 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008079 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008080 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008081 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008082 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008083 // with the register storage-class specifier.
8084 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008085 // in C++ it is not error to take address of a register
8086 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008087 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008088 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008089 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008090 }
John McCallba135432009-11-21 08:51:07 +00008091 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008092 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008093 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008094 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008095 // Could be a pointer to member, though, if there is an explicit
8096 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008097 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008098 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008099 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008100 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008101 S.Diag(OpLoc,
8102 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008103 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008104 return QualType();
8105 }
Mike Stump1eb44332009-09-09 15:08:12 +00008106
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008107 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8108 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008109 return S.Context.getMemberPointerType(op->getType(),
8110 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008111 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008112 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008113 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008114 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008115 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008116
Richard Trieu5520f232011-09-07 21:46:33 +00008117 if (AddressOfError != AO_No_Error) {
8118 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8119 return QualType();
8120 }
8121
Eli Friedman441cf102009-05-16 23:27:50 +00008122 if (lval == Expr::LV_IncompleteVoidType) {
8123 // Taking the address of a void variable is technically illegal, but we
8124 // allow it in cases which are otherwise valid.
8125 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008126 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008127 }
8128
Reid Spencer5f016e22007-07-11 17:01:13 +00008129 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008130 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008131 return S.Context.getObjCObjectPointerType(op->getType());
8132 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008133}
8134
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008135/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008136static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8137 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008138 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008139 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008140
John Wiegley429bb272011-04-08 18:41:53 +00008141 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8142 if (ConvResult.isInvalid())
8143 return QualType();
8144 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008145 QualType OpTy = Op->getType();
8146 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008147
8148 if (isa<CXXReinterpretCastExpr>(Op)) {
8149 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8150 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8151 Op->getSourceRange());
8152 }
8153
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008154 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8155 // is an incomplete type or void. It would be possible to warn about
8156 // dereferencing a void pointer, but it's completely well-defined, and such a
8157 // warning is unlikely to catch any mistakes.
8158 if (const PointerType *PT = OpTy->getAs<PointerType>())
8159 Result = PT->getPointeeType();
8160 else if (const ObjCObjectPointerType *OPT =
8161 OpTy->getAs<ObjCObjectPointerType>())
8162 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008163 else {
John McCallfb8721c2011-04-10 19:13:55 +00008164 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008165 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008166 if (PR.take() != Op)
8167 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008168 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008169
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008170 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008171 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008172 << OpTy << Op->getSourceRange();
8173 return QualType();
8174 }
John McCall09431682010-11-18 19:01:18 +00008175
8176 // Dereferences are usually l-values...
8177 VK = VK_LValue;
8178
8179 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008180 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008181 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008182
8183 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008184}
8185
John McCall2de56d12010-08-25 11:45:40 +00008186static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008187 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008188 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008189 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008190 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008191 case tok::periodstar: Opc = BO_PtrMemD; break;
8192 case tok::arrowstar: Opc = BO_PtrMemI; break;
8193 case tok::star: Opc = BO_Mul; break;
8194 case tok::slash: Opc = BO_Div; break;
8195 case tok::percent: Opc = BO_Rem; break;
8196 case tok::plus: Opc = BO_Add; break;
8197 case tok::minus: Opc = BO_Sub; break;
8198 case tok::lessless: Opc = BO_Shl; break;
8199 case tok::greatergreater: Opc = BO_Shr; break;
8200 case tok::lessequal: Opc = BO_LE; break;
8201 case tok::less: Opc = BO_LT; break;
8202 case tok::greaterequal: Opc = BO_GE; break;
8203 case tok::greater: Opc = BO_GT; break;
8204 case tok::exclaimequal: Opc = BO_NE; break;
8205 case tok::equalequal: Opc = BO_EQ; break;
8206 case tok::amp: Opc = BO_And; break;
8207 case tok::caret: Opc = BO_Xor; break;
8208 case tok::pipe: Opc = BO_Or; break;
8209 case tok::ampamp: Opc = BO_LAnd; break;
8210 case tok::pipepipe: Opc = BO_LOr; break;
8211 case tok::equal: Opc = BO_Assign; break;
8212 case tok::starequal: Opc = BO_MulAssign; break;
8213 case tok::slashequal: Opc = BO_DivAssign; break;
8214 case tok::percentequal: Opc = BO_RemAssign; break;
8215 case tok::plusequal: Opc = BO_AddAssign; break;
8216 case tok::minusequal: Opc = BO_SubAssign; break;
8217 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8218 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8219 case tok::ampequal: Opc = BO_AndAssign; break;
8220 case tok::caretequal: Opc = BO_XorAssign; break;
8221 case tok::pipeequal: Opc = BO_OrAssign; break;
8222 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008223 }
8224 return Opc;
8225}
8226
John McCall2de56d12010-08-25 11:45:40 +00008227static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008228 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008229 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008230 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008231 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008232 case tok::plusplus: Opc = UO_PreInc; break;
8233 case tok::minusminus: Opc = UO_PreDec; break;
8234 case tok::amp: Opc = UO_AddrOf; break;
8235 case tok::star: Opc = UO_Deref; break;
8236 case tok::plus: Opc = UO_Plus; break;
8237 case tok::minus: Opc = UO_Minus; break;
8238 case tok::tilde: Opc = UO_Not; break;
8239 case tok::exclaim: Opc = UO_LNot; break;
8240 case tok::kw___real: Opc = UO_Real; break;
8241 case tok::kw___imag: Opc = UO_Imag; break;
8242 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008243 }
8244 return Opc;
8245}
8246
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008247/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8248/// This warning is only emitted for builtin assignment operations. It is also
8249/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008250static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008251 SourceLocation OpLoc) {
8252 if (!S.ActiveTemplateInstantiations.empty())
8253 return;
8254 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8255 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008256 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8257 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8258 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8259 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8260 if (!LHSDeclRef || !RHSDeclRef ||
8261 LHSDeclRef->getLocation().isMacroID() ||
8262 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008263 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008264 const ValueDecl *LHSDecl =
8265 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8266 const ValueDecl *RHSDecl =
8267 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8268 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008269 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008270 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008271 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008272 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008273 if (RefTy->getPointeeType().isVolatileQualified())
8274 return;
8275
8276 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008277 << LHSDeclRef->getType()
8278 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008279}
8280
Douglas Gregoreaebc752008-11-06 23:29:22 +00008281/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8282/// operator @p Opc at location @c TokLoc. This routine only supports
8283/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008284ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008285 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008286 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008287 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008288 // The syntax only allows initializer lists on the RHS of assignment,
8289 // so we don't need to worry about accepting invalid code for
8290 // non-assignment operators.
8291 // C++11 5.17p9:
8292 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8293 // of x = {} is x = T().
8294 InitializationKind Kind =
8295 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8296 InitializedEntity Entity =
8297 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8298 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008299 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008300 if (Init.isInvalid())
8301 return Init;
8302 RHSExpr = Init.take();
8303 }
8304
Richard Trieu78ea78b2011-09-07 01:49:20 +00008305 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008306 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008307 // The following two variables are used for compound assignment operators
8308 QualType CompLHSTy; // Type of LHS after promotions for computation
8309 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008310 ExprValueKind VK = VK_RValue;
8311 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008312
8313 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008314 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008315 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008316 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008317 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8318 VK = LHS.get()->getValueKind();
8319 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008320 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008321 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008322 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008323 break;
John McCall2de56d12010-08-25 11:45:40 +00008324 case BO_PtrMemD:
8325 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008326 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008327 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008328 break;
John McCall2de56d12010-08-25 11:45:40 +00008329 case BO_Mul:
8330 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008331 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008332 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008333 break;
John McCall2de56d12010-08-25 11:45:40 +00008334 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008335 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008336 break;
John McCall2de56d12010-08-25 11:45:40 +00008337 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008338 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008339 break;
John McCall2de56d12010-08-25 11:45:40 +00008340 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008341 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008342 break;
John McCall2de56d12010-08-25 11:45:40 +00008343 case BO_Shl:
8344 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008345 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008346 break;
John McCall2de56d12010-08-25 11:45:40 +00008347 case BO_LE:
8348 case BO_LT:
8349 case BO_GE:
8350 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008351 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008352 break;
John McCall2de56d12010-08-25 11:45:40 +00008353 case BO_EQ:
8354 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008355 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008356 break;
John McCall2de56d12010-08-25 11:45:40 +00008357 case BO_And:
8358 case BO_Xor:
8359 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008360 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008361 break;
John McCall2de56d12010-08-25 11:45:40 +00008362 case BO_LAnd:
8363 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008364 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008365 break;
John McCall2de56d12010-08-25 11:45:40 +00008366 case BO_MulAssign:
8367 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008368 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008369 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008370 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008371 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8372 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008373 break;
John McCall2de56d12010-08-25 11:45:40 +00008374 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008375 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008376 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008377 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8378 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008379 break;
John McCall2de56d12010-08-25 11:45:40 +00008380 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008381 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008382 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8383 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008384 break;
John McCall2de56d12010-08-25 11:45:40 +00008385 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008386 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8387 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8388 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008389 break;
John McCall2de56d12010-08-25 11:45:40 +00008390 case BO_ShlAssign:
8391 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008392 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008393 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008394 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8395 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008396 break;
John McCall2de56d12010-08-25 11:45:40 +00008397 case BO_AndAssign:
8398 case BO_XorAssign:
8399 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008400 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008401 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008402 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8403 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008404 break;
John McCall2de56d12010-08-25 11:45:40 +00008405 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008406 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008407 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008408 VK = RHS.get()->getValueKind();
8409 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008410 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008411 break;
8412 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008413 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008414 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008415
8416 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008417 CheckArrayAccess(LHS.get());
8418 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008419
Eli Friedmanab3a8522009-03-28 01:22:36 +00008420 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008421 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hamesbe9af122012-10-02 04:45:10 +00008422 ResultTy, VK, OK, OpLoc,
8423 FPFeatures.fp_contract));
David Blaikie4e4d0842012-03-11 07:00:24 +00008424 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008425 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008426 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008427 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008428 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008429 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008430 ResultTy, VK, OK, CompLHSTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00008431 CompResultTy, OpLoc,
8432 FPFeatures.fp_contract));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008433}
8434
Sebastian Redlaee3c932009-10-27 12:10:02 +00008435/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8436/// operators are mixed in a way that suggests that the programmer forgot that
8437/// comparison operators have higher precedence. The most typical example of
8438/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008439static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008440 SourceLocation OpLoc, Expr *LHSExpr,
8441 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008442 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008443 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8444 RHSopc = static_cast<BinOp::Opcode>(-1);
8445 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8446 LHSopc = BO->getOpcode();
8447 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8448 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008449
8450 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008451 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008452 return;
8453
8454 // Bitwise operations are sometimes used as eager logical ops.
8455 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008456 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8457 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008458 return;
8459
Richard Trieu78ea78b2011-09-07 01:49:20 +00008460 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8461 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008462 if (!isLeftComp && !isRightComp) return;
8463
Richard Trieu78ea78b2011-09-07 01:49:20 +00008464 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8465 OpLoc)
8466 : SourceRange(OpLoc, RHSExpr->getLocEnd());
David Blaikie0bea8632012-10-08 01:11:04 +00008467 StringRef OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8468 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008469 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008470 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8471 RHSExpr->getLocEnd())
8472 : SourceRange(LHSExpr->getLocStart(),
8473 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008474
8475 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8476 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8477 SuggestParentheses(Self, OpLoc,
8478 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008479 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008480 SuggestParentheses(Self, OpLoc,
8481 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8482 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008483}
8484
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008485/// \brief It accepts a '&' expr that is inside a '|' one.
8486/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8487/// in parentheses.
8488static void
8489EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8490 BinaryOperator *Bop) {
8491 assert(Bop->getOpcode() == BO_And);
8492 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8493 << Bop->getSourceRange() << OpLoc;
8494 SuggestParentheses(Self, Bop->getOperatorLoc(),
8495 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8496 Bop->getSourceRange());
8497}
8498
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008499/// \brief It accepts a '&&' expr that is inside a '||' one.
8500/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8501/// in parentheses.
8502static void
8503EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008504 BinaryOperator *Bop) {
8505 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008506 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8507 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008508 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008509 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008510 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008511}
8512
8513/// \brief Returns true if the given expression can be evaluated as a constant
8514/// 'true'.
8515static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8516 bool Res;
8517 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8518}
8519
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008520/// \brief Returns true if the given expression can be evaluated as a constant
8521/// 'false'.
8522static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8523 bool Res;
8524 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8525}
8526
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008527/// \brief Look for '&&' in the left hand of a '||' expr.
8528static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008529 Expr *LHSExpr, Expr *RHSExpr) {
8530 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008531 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008532 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008533 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008534 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008535 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8536 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8537 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8538 } else if (Bop->getOpcode() == BO_LOr) {
8539 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8540 // If it's "a || b && 1 || c" we didn't warn earlier for
8541 // "a || b && 1", but warn now.
8542 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8543 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8544 }
8545 }
8546 }
8547}
8548
8549/// \brief Look for '&&' in the right hand of a '||' expr.
8550static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008551 Expr *LHSExpr, Expr *RHSExpr) {
8552 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008553 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008554 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008555 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008556 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008557 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8558 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8559 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008560 }
8561 }
8562}
8563
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008564/// \brief Look for '&' in the left or right hand of a '|' expr.
8565static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8566 Expr *OrArg) {
8567 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8568 if (Bop->getOpcode() == BO_And)
8569 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8570 }
8571}
8572
David Blaikieb3f55c52012-10-05 00:41:03 +00008573static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8574 Expr *SubExpr, StringRef shift) {
8575 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8576 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
8577 StringRef op = Bop->getOpcode() == BO_Add ? "+" : "-";
8578 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
8579 << Bop->getSourceRange() << OpLoc << op << shift;
8580 SuggestParentheses(S, Bop->getOperatorLoc(),
8581 S.PDiag(diag::note_addition_in_bitshift_silence) << op,
8582 Bop->getSourceRange());
8583 }
8584 }
8585}
8586
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008587/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008588/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008589static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008590 SourceLocation OpLoc, Expr *LHSExpr,
8591 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008592 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008593 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008594 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008595
8596 // Diagnose "arg1 & arg2 | arg3"
8597 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008598 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8599 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008600 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008601
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008602 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8603 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008604 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008605 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8606 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008607 }
David Blaikieb3f55c52012-10-05 00:41:03 +00008608
8609 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8610 || Opc == BO_Shr) {
8611 StringRef shift = Opc == BO_Shl ? "<<" : ">>";
8612 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, shift);
8613 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, shift);
8614 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008615}
8616
Reid Spencer5f016e22007-07-11 17:01:13 +00008617// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008618ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008619 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008620 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008621 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008622 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8623 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008624
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008625 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008626 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008627
Richard Trieubefece12011-09-07 02:02:10 +00008628 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008629}
8630
John McCall3c3b7f92011-10-25 17:37:35 +00008631/// Build an overloaded binary operator expression in the given scope.
8632static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8633 BinaryOperatorKind Opc,
8634 Expr *LHS, Expr *RHS) {
8635 // Find all of the overloaded operators visible from this
8636 // point. We perform both an operator-name lookup from the local
8637 // scope and an argument-dependent lookup based on the types of
8638 // the arguments.
8639 UnresolvedSet<16> Functions;
8640 OverloadedOperatorKind OverOp
8641 = BinaryOperator::getOverloadedOperator(Opc);
8642 if (Sc && OverOp != OO_None)
8643 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8644 RHS->getType(), Functions);
8645
8646 // Build the (potentially-overloaded, potentially-dependent)
8647 // binary operation.
8648 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8649}
8650
John McCall60d7b3a2010-08-24 06:29:42 +00008651ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008652 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008653 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008654 // We want to end up calling one of checkPseudoObjectAssignment
8655 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8656 // both expressions are overloadable or either is type-dependent),
8657 // or CreateBuiltinBinOp (in any other case). We also want to get
8658 // any placeholder types out of the way.
8659
John McCall3c3b7f92011-10-25 17:37:35 +00008660 // Handle pseudo-objects in the LHS.
8661 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8662 // Assignments with a pseudo-object l-value need special analysis.
8663 if (pty->getKind() == BuiltinType::PseudoObject &&
8664 BinaryOperator::isAssignmentOp(Opc))
8665 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8666
8667 // Don't resolve overloads if the other type is overloadable.
8668 if (pty->getKind() == BuiltinType::Overload) {
8669 // We can't actually test that if we still have a placeholder,
8670 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008671 // code below are valid when the LHS is an overload set. Note
8672 // that an overload set can be dependently-typed, but it never
8673 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008674 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8675 if (resolvedRHS.isInvalid()) return ExprError();
8676 RHSExpr = resolvedRHS.take();
8677
John McCallac516502011-10-28 01:04:34 +00008678 if (RHSExpr->isTypeDependent() ||
8679 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008680 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8681 }
8682
8683 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8684 if (LHS.isInvalid()) return ExprError();
8685 LHSExpr = LHS.take();
8686 }
8687
8688 // Handle pseudo-objects in the RHS.
8689 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8690 // An overload in the RHS can potentially be resolved by the type
8691 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008692 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8693 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8694 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8695
Eli Friedman87884912012-01-17 21:27:43 +00008696 if (LHSExpr->getType()->isOverloadableType())
8697 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8698
John McCall3c3b7f92011-10-25 17:37:35 +00008699 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008700 }
John McCall3c3b7f92011-10-25 17:37:35 +00008701
8702 // Don't resolve overloads if the other type is overloadable.
8703 if (pty->getKind() == BuiltinType::Overload &&
8704 LHSExpr->getType()->isOverloadableType())
8705 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8706
8707 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8708 if (!resolvedRHS.isUsable()) return ExprError();
8709 RHSExpr = resolvedRHS.take();
8710 }
8711
David Blaikie4e4d0842012-03-11 07:00:24 +00008712 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008713 // If either expression is type-dependent, always build an
8714 // overloaded op.
8715 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8716 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008717
John McCallac516502011-10-28 01:04:34 +00008718 // Otherwise, build an overloaded op if either expression has an
8719 // overloadable type.
8720 if (LHSExpr->getType()->isOverloadableType() ||
8721 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008722 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008723 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008724
Douglas Gregoreaebc752008-11-06 23:29:22 +00008725 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008726 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008727}
8728
John McCall60d7b3a2010-08-24 06:29:42 +00008729ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008730 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008731 Expr *InputExpr) {
8732 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008733 ExprValueKind VK = VK_RValue;
8734 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008735 QualType resultType;
8736 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008737 case UO_PreInc:
8738 case UO_PreDec:
8739 case UO_PostInc:
8740 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008741 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008742 Opc == UO_PreInc ||
8743 Opc == UO_PostInc,
8744 Opc == UO_PreInc ||
8745 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008746 break;
John McCall2de56d12010-08-25 11:45:40 +00008747 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008748 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008749 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008750 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008751 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008752 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008753 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008754 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008755 }
John McCall2de56d12010-08-25 11:45:40 +00008756 case UO_Plus:
8757 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008758 Input = UsualUnaryConversions(Input.take());
8759 if (Input.isInvalid()) return ExprError();
8760 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008761 if (resultType->isDependentType())
8762 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008763 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8764 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008765 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008766 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008767 resultType->isEnumeralType())
8768 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008769 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008770 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008771 resultType->isPointerType())
8772 break;
8773
Sebastian Redl0eb23302009-01-19 00:08:26 +00008774 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008775 << resultType << Input.get()->getSourceRange());
8776
John McCall2de56d12010-08-25 11:45:40 +00008777 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008778 Input = UsualUnaryConversions(Input.take());
8779 if (Input.isInvalid()) return ExprError();
8780 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008781 if (resultType->isDependentType())
8782 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008783 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8784 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8785 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008786 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008787 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008788 else if (resultType->hasIntegerRepresentation())
8789 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008790 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008791 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008792 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008793 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008794 break;
John Wiegley429bb272011-04-08 18:41:53 +00008795
John McCall2de56d12010-08-25 11:45:40 +00008796 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008797 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008798 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8799 if (Input.isInvalid()) return ExprError();
8800 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008801
8802 // Though we still have to promote half FP to float...
8803 if (resultType->isHalfType()) {
8804 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8805 resultType = Context.FloatTy;
8806 }
8807
Sebastian Redl28507842009-02-26 14:39:58 +00008808 if (resultType->isDependentType())
8809 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008810 if (resultType->isScalarType()) {
8811 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008812 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008813 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8814 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008815 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8816 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008817 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008818 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008819 // Vector logical not returns the signed variant of the operand type.
8820 resultType = GetSignedVectorType(resultType);
8821 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008822 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008823 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008824 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008825 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008826
Reid Spencer5f016e22007-07-11 17:01:13 +00008827 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008828 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008829 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008830 break;
John McCall2de56d12010-08-25 11:45:40 +00008831 case UO_Real:
8832 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008833 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008834 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8835 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008836 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008837 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8838 if (Input.get()->getValueKind() != VK_RValue &&
8839 Input.get()->getObjectKind() == OK_Ordinary)
8840 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008841 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008842 // In C, a volatile scalar is read by __imag. In C++, it is not.
8843 Input = DefaultLvalueConversion(Input.take());
8844 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008845 break;
John McCall2de56d12010-08-25 11:45:40 +00008846 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008847 resultType = Input.get()->getType();
8848 VK = Input.get()->getValueKind();
8849 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008850 break;
8851 }
John Wiegley429bb272011-04-08 18:41:53 +00008852 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008853 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008854
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008855 // Check for array bounds violations in the operand of the UnaryOperator,
8856 // except for the '*' and '&' operators that have to be handled specially
8857 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8858 // that are explicitly defined as valid by the standard).
8859 if (Opc != UO_AddrOf && Opc != UO_Deref)
8860 CheckArrayAccess(Input.get());
8861
John Wiegley429bb272011-04-08 18:41:53 +00008862 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008863 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008864}
8865
Douglas Gregord3d08532011-12-14 21:23:13 +00008866/// \brief Determine whether the given expression is a qualified member
8867/// access expression, of a form that could be turned into a pointer to member
8868/// with the address-of operator.
8869static bool isQualifiedMemberAccess(Expr *E) {
8870 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8871 if (!DRE->getQualifier())
8872 return false;
8873
8874 ValueDecl *VD = DRE->getDecl();
8875 if (!VD->isCXXClassMember())
8876 return false;
8877
8878 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8879 return true;
8880 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8881 return Method->isInstance();
8882
8883 return false;
8884 }
8885
8886 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8887 if (!ULE->getQualifier())
8888 return false;
8889
8890 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8891 DEnd = ULE->decls_end();
8892 D != DEnd; ++D) {
8893 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8894 if (Method->isInstance())
8895 return true;
8896 } else {
8897 // Overload set does not contain methods.
8898 break;
8899 }
8900 }
8901
8902 return false;
8903 }
8904
8905 return false;
8906}
8907
John McCall60d7b3a2010-08-24 06:29:42 +00008908ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008909 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008910 // First things first: handle placeholders so that the
8911 // overloaded-operator check considers the right type.
8912 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8913 // Increment and decrement of pseudo-object references.
8914 if (pty->getKind() == BuiltinType::PseudoObject &&
8915 UnaryOperator::isIncrementDecrementOp(Opc))
8916 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8917
8918 // extension is always a builtin operator.
8919 if (Opc == UO_Extension)
8920 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8921
8922 // & gets special logic for several kinds of placeholder.
8923 // The builtin code knows what to do.
8924 if (Opc == UO_AddrOf &&
8925 (pty->getKind() == BuiltinType::Overload ||
8926 pty->getKind() == BuiltinType::UnknownAny ||
8927 pty->getKind() == BuiltinType::BoundMember))
8928 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8929
8930 // Anything else needs to be handled now.
8931 ExprResult Result = CheckPlaceholderExpr(Input);
8932 if (Result.isInvalid()) return ExprError();
8933 Input = Result.take();
8934 }
8935
David Blaikie4e4d0842012-03-11 07:00:24 +00008936 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008937 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8938 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008939 // Find all of the overloaded operators visible from this
8940 // point. We perform both an operator-name lookup from the local
8941 // scope and an argument-dependent lookup based on the types of
8942 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008943 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008944 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008945 if (S && OverOp != OO_None)
8946 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8947 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008948
John McCall9ae2f072010-08-23 23:25:46 +00008949 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008950 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008951
John McCall9ae2f072010-08-23 23:25:46 +00008952 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008953}
8954
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008955// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008956ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008957 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008958 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008959}
8960
Steve Naroff1b273c42007-09-16 14:56:35 +00008961/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008962ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008963 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008964 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008965 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008966 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008967 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008968}
8969
John McCallf85e1932011-06-15 23:02:42 +00008970/// Given the last statement in a statement-expression, check whether
8971/// the result is a producing expression (like a call to an
8972/// ns_returns_retained function) and, if so, rebuild it to hoist the
8973/// release out of the full-expression. Otherwise, return null.
8974/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008975static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008976 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008977 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008978 if (!cleanups) return 0;
8979
8980 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008981 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008982 return 0;
8983
8984 // Splice out the cast. This shouldn't modify any interesting
8985 // features of the statement.
8986 Expr *producer = cast->getSubExpr();
8987 assert(producer->getType() == cast->getType());
8988 assert(producer->getValueKind() == cast->getValueKind());
8989 cleanups->setSubExpr(producer);
8990 return cleanups;
8991}
8992
John McCall73f428c2012-04-04 01:27:53 +00008993void Sema::ActOnStartStmtExpr() {
8994 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8995}
8996
8997void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008998 // Note that function is also called by TreeTransform when leaving a
8999 // StmtExpr scope without rebuilding anything.
9000
John McCall73f428c2012-04-04 01:27:53 +00009001 DiscardCleanupsInEvaluationContext();
9002 PopExpressionEvaluationContext();
9003}
9004
John McCall60d7b3a2010-08-24 06:29:42 +00009005ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009006Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009007 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009008 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9009 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9010
John McCall73f428c2012-04-04 01:27:53 +00009011 if (hasAnyUnrecoverableErrorsInThisFunction())
9012 DiscardCleanupsInEvaluationContext();
9013 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9014 PopExpressionEvaluationContext();
9015
Douglas Gregordd8f5692010-03-10 04:54:39 +00009016 bool isFileScope
9017 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009018 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009019 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009020
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009021 // FIXME: there are a variety of strange constraints to enforce here, for
9022 // example, it is not possible to goto into a stmt expression apparently.
9023 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009024
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009025 // If there are sub stmts in the compound stmt, take the type of the last one
9026 // as the type of the stmtexpr.
9027 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009028 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009029 if (!Compound->body_empty()) {
9030 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009031 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009032 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009033 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9034 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009035 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009036 }
John McCallf85e1932011-06-15 23:02:42 +00009037
John Wiegley429bb272011-04-08 18:41:53 +00009038 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009039 // Do function/array conversion on the last expression, but not
9040 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009041 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9042 if (LastExpr.isInvalid())
9043 return ExprError();
9044 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009045
John Wiegley429bb272011-04-08 18:41:53 +00009046 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009047 // In ARC, if the final expression ends in a consume, splice
9048 // the consume out and bind it later. In the alternate case
9049 // (when dealing with a retainable type), the result
9050 // initialization will create a produce. In both cases the
9051 // result will be +1, and we'll need to balance that out with
9052 // a bind.
9053 if (Expr *rebuiltLastStmt
9054 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9055 LastExpr = rebuiltLastStmt;
9056 } else {
9057 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009058 InitializedEntity::InitializeResult(LPLoc,
9059 Ty,
9060 false),
9061 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009062 LastExpr);
9063 }
9064
John Wiegley429bb272011-04-08 18:41:53 +00009065 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009066 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009067 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009068 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009069 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009070 else
John Wiegley429bb272011-04-08 18:41:53 +00009071 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009072 StmtExprMayBindToTemp = true;
9073 }
9074 }
9075 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009076 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009077
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009078 // FIXME: Check that expression type is complete/non-abstract; statement
9079 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009080 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9081 if (StmtExprMayBindToTemp)
9082 return MaybeBindToTemporary(ResStmtExpr);
9083 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009084}
Steve Naroffd34e9152007-08-01 22:05:33 +00009085
John McCall60d7b3a2010-08-24 06:29:42 +00009086ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009087 TypeSourceInfo *TInfo,
9088 OffsetOfComponent *CompPtr,
9089 unsigned NumComponents,
9090 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009091 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009092 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009093 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009094
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009095 // We must have at least one component that refers to the type, and the first
9096 // one is known to be a field designator. Verify that the ArgTy represents
9097 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009098 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009099 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9100 << ArgTy << TypeRange);
9101
9102 // Type must be complete per C99 7.17p3 because a declaring a variable
9103 // with an incomplete type would be ill-formed.
9104 if (!Dependent
9105 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009106 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009107 return ExprError();
9108
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009109 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9110 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009111 // FIXME: This diagnostic isn't actually visible because the location is in
9112 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009113 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009114 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9115 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009116
9117 bool DidWarnAboutNonPOD = false;
9118 QualType CurrentType = ArgTy;
9119 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009120 SmallVector<OffsetOfNode, 4> Comps;
9121 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009122 for (unsigned i = 0; i != NumComponents; ++i) {
9123 const OffsetOfComponent &OC = CompPtr[i];
9124 if (OC.isBrackets) {
9125 // Offset of an array sub-field. TODO: Should we allow vector elements?
9126 if (!CurrentType->isDependentType()) {
9127 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9128 if(!AT)
9129 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9130 << CurrentType);
9131 CurrentType = AT->getElementType();
9132 } else
9133 CurrentType = Context.DependentTy;
9134
Richard Smithea011432011-10-17 23:29:39 +00009135 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9136 if (IdxRval.isInvalid())
9137 return ExprError();
9138 Expr *Idx = IdxRval.take();
9139
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009140 // The expression must be an integral expression.
9141 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009142 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9143 !Idx->getType()->isIntegerType())
9144 return ExprError(Diag(Idx->getLocStart(),
9145 diag::err_typecheck_subscript_not_integer)
9146 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009147
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009148 // Record this array index.
9149 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009150 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009151 continue;
9152 }
9153
9154 // Offset of a field.
9155 if (CurrentType->isDependentType()) {
9156 // We have the offset of a field, but we can't look into the dependent
9157 // type. Just record the identifier of the field.
9158 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9159 CurrentType = Context.DependentTy;
9160 continue;
9161 }
9162
9163 // We need to have a complete type to look into.
9164 if (RequireCompleteType(OC.LocStart, CurrentType,
9165 diag::err_offsetof_incomplete_type))
9166 return ExprError();
9167
9168 // Look for the designated field.
9169 const RecordType *RC = CurrentType->getAs<RecordType>();
9170 if (!RC)
9171 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9172 << CurrentType);
9173 RecordDecl *RD = RC->getDecl();
9174
9175 // C++ [lib.support.types]p5:
9176 // The macro offsetof accepts a restricted set of type arguments in this
9177 // International Standard. type shall be a POD structure or a POD union
9178 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009179 // C++11 [support.types]p4:
9180 // If type is not a standard-layout class (Clause 9), the results are
9181 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009182 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009183 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9184 unsigned DiagID =
9185 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9186 : diag::warn_offsetof_non_pod_type;
9187
9188 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009189 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009190 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009191 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9192 << CurrentType))
9193 DidWarnAboutNonPOD = true;
9194 }
9195
9196 // Look for the field.
9197 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9198 LookupQualifiedName(R, RD);
9199 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009200 IndirectFieldDecl *IndirectMemberDecl = 0;
9201 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009202 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009203 MemberDecl = IndirectMemberDecl->getAnonField();
9204 }
9205
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009206 if (!MemberDecl)
9207 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9208 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9209 OC.LocEnd));
9210
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009211 // C99 7.17p3:
9212 // (If the specified member is a bit-field, the behavior is undefined.)
9213 //
9214 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009215 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009216 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9217 << MemberDecl->getDeclName()
9218 << SourceRange(BuiltinLoc, RParenLoc);
9219 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9220 return ExprError();
9221 }
Eli Friedman19410a72010-08-05 10:11:36 +00009222
9223 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009224 if (IndirectMemberDecl)
9225 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009226
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009227 // If the member was found in a base class, introduce OffsetOfNodes for
9228 // the base class indirections.
9229 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9230 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009231 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009232 CXXBasePath &Path = Paths.front();
9233 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9234 B != BEnd; ++B)
9235 Comps.push_back(OffsetOfNode(B->Base));
9236 }
Eli Friedman19410a72010-08-05 10:11:36 +00009237
Francois Pichet87c2e122010-11-21 06:08:52 +00009238 if (IndirectMemberDecl) {
9239 for (IndirectFieldDecl::chain_iterator FI =
9240 IndirectMemberDecl->chain_begin(),
9241 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9242 assert(isa<FieldDecl>(*FI));
9243 Comps.push_back(OffsetOfNode(OC.LocStart,
9244 cast<FieldDecl>(*FI), OC.LocEnd));
9245 }
9246 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009247 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009248
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009249 CurrentType = MemberDecl->getType().getNonReferenceType();
9250 }
9251
9252 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009253 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009254}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009255
John McCall60d7b3a2010-08-24 06:29:42 +00009256ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009257 SourceLocation BuiltinLoc,
9258 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009259 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009260 OffsetOfComponent *CompPtr,
9261 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009262 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009263
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009264 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009265 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009266 if (ArgTy.isNull())
9267 return ExprError();
9268
Eli Friedman5a15dc12010-08-05 10:15:45 +00009269 if (!ArgTInfo)
9270 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9271
9272 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009273 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009274}
9275
9276
John McCall60d7b3a2010-08-24 06:29:42 +00009277ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009278 Expr *CondExpr,
9279 Expr *LHSExpr, Expr *RHSExpr,
9280 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009281 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9282
John McCallf89e55a2010-11-18 06:31:45 +00009283 ExprValueKind VK = VK_RValue;
9284 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009285 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009286 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009287 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009288 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009289 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009290 } else {
9291 // The conditional expression is required to be a constant expression.
9292 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009293 ExprResult CondICE
9294 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9295 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009296 if (CondICE.isInvalid())
9297 return ExprError();
9298 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009299
Sebastian Redl28507842009-02-26 14:39:58 +00009300 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009301 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9302
9303 resType = ActiveExpr->getType();
9304 ValueDependent = ActiveExpr->isValueDependent();
9305 VK = ActiveExpr->getValueKind();
9306 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009307 }
9308
Sebastian Redlf53597f2009-03-15 17:47:39 +00009309 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009310 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009311 resType->isDependentType(),
9312 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009313}
9314
Steve Naroff4eb206b2008-09-03 18:15:37 +00009315//===----------------------------------------------------------------------===//
9316// Clang Extensions.
9317//===----------------------------------------------------------------------===//
9318
9319/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009320void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009321 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009322 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009323 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009324 if (CurScope)
9325 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009326 else
9327 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009328
Eli Friedman84b007f2012-01-26 03:00:14 +00009329 getCurBlock()->HasImplicitReturnType = true;
9330
John McCall538773c2011-11-11 03:19:12 +00009331 // Enter a new evaluation context to insulate the block from any
9332 // cleanups from the enclosing full-expression.
9333 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009334}
9335
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009336void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9337 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009338 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009339 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009340 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009341
John McCallbf1a0282010-06-04 23:28:52 +00009342 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009343 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009344
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009345 // FIXME: We should allow unexpanded parameter packs here, but that would,
9346 // in turn, make the block expression contain unexpanded parameter packs.
9347 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9348 // Drop the parameters.
9349 FunctionProtoType::ExtProtoInfo EPI;
9350 EPI.HasTrailingReturn = false;
9351 EPI.TypeQuals |= DeclSpec::TQ_const;
9352 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9353 EPI);
9354 Sig = Context.getTrivialTypeSourceInfo(T);
9355 }
9356
John McCall711c52b2011-01-05 12:14:39 +00009357 // GetTypeForDeclarator always produces a function type for a block
9358 // literal signature. Furthermore, it is always a FunctionProtoType
9359 // unless the function was written with a typedef.
9360 assert(T->isFunctionType() &&
9361 "GetTypeForDeclarator made a non-function block signature");
9362
9363 // Look for an explicit signature in that function type.
9364 FunctionProtoTypeLoc ExplicitSignature;
9365
9366 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9367 if (isa<FunctionProtoTypeLoc>(tmp)) {
9368 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9369
9370 // Check whether that explicit signature was synthesized by
9371 // GetTypeForDeclarator. If so, don't save that as part of the
9372 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009373 if (ExplicitSignature.getLocalRangeBegin() ==
9374 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009375 // This would be much cheaper if we stored TypeLocs instead of
9376 // TypeSourceInfos.
9377 TypeLoc Result = ExplicitSignature.getResultLoc();
9378 unsigned Size = Result.getFullDataSize();
9379 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9380 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9381
9382 ExplicitSignature = FunctionProtoTypeLoc();
9383 }
John McCall82dc0092010-06-04 11:21:44 +00009384 }
Mike Stump1eb44332009-09-09 15:08:12 +00009385
John McCall711c52b2011-01-05 12:14:39 +00009386 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9387 CurBlock->FunctionType = T;
9388
9389 const FunctionType *Fn = T->getAs<FunctionType>();
9390 QualType RetTy = Fn->getResultType();
9391 bool isVariadic =
9392 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9393
John McCallc71a4912010-06-04 19:02:56 +00009394 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009395
John McCall82dc0092010-06-04 11:21:44 +00009396 // Don't allow returning a objc interface by value.
9397 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009398 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009399 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9400 return;
9401 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009402
John McCall82dc0092010-06-04 11:21:44 +00009403 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009404 // return type. TODO: what should we do with declarators like:
9405 // ^ * { ... }
9406 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009407 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009408 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009409 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009410 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009411 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009412
John McCall82dc0092010-06-04 11:21:44 +00009413 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009414 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009415 if (ExplicitSignature) {
9416 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9417 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009418 if (Param->getIdentifier() == 0 &&
9419 !Param->isImplicit() &&
9420 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009421 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009422 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009423 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009424 }
John McCall82dc0092010-06-04 11:21:44 +00009425
9426 // Fake up parameter variables if we have a typedef, like
9427 // ^ fntype { ... }
9428 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9429 for (FunctionProtoType::arg_type_iterator
9430 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9431 ParmVarDecl *Param =
9432 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009433 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009434 *I);
John McCallc71a4912010-06-04 19:02:56 +00009435 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009436 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009437 }
John McCall82dc0092010-06-04 11:21:44 +00009438
John McCallc71a4912010-06-04 19:02:56 +00009439 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009440 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009441 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009442 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9443 CurBlock->TheDecl->param_end(),
9444 /*CheckParameterNames=*/false);
9445 }
9446
John McCall82dc0092010-06-04 11:21:44 +00009447 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009448 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009449
John McCall82dc0092010-06-04 11:21:44 +00009450 // Put the parameter variables in scope. We can bail out immediately
9451 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009452 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009453 return;
9454
Steve Naroff090276f2008-10-10 01:28:17 +00009455 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009456 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9457 (*AI)->setOwningFunction(CurBlock->TheDecl);
9458
Steve Naroff090276f2008-10-10 01:28:17 +00009459 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009460 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009461 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009462
Steve Naroff090276f2008-10-10 01:28:17 +00009463 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009464 }
John McCall7a9813c2010-01-22 00:28:27 +00009465 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009466}
9467
9468/// ActOnBlockError - If there is an error parsing a block, this callback
9469/// is invoked to pop the information about the block from the action impl.
9470void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009471 // Leave the expression-evaluation context.
9472 DiscardCleanupsInEvaluationContext();
9473 PopExpressionEvaluationContext();
9474
Steve Naroff4eb206b2008-09-03 18:15:37 +00009475 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009476 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009477 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009478}
9479
9480/// ActOnBlockStmtExpr - This is called when the body of a block statement
9481/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009482ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009483 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009484 // If blocks are disabled, emit an error.
9485 if (!LangOpts.Blocks)
9486 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009487
John McCall538773c2011-11-11 03:19:12 +00009488 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009489 if (hasAnyUnrecoverableErrorsInThisFunction())
9490 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009491 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9492 PopExpressionEvaluationContext();
9493
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009494 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009495
9496 if (BSI->HasImplicitReturnType)
9497 deduceClosureReturnType(*BSI);
9498
Steve Naroff090276f2008-10-10 01:28:17 +00009499 PopDeclContext();
9500
Steve Naroff4eb206b2008-09-03 18:15:37 +00009501 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009502 if (!BSI->ReturnType.isNull())
9503 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009504
Mike Stump56925862009-07-28 22:04:01 +00009505 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009506 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009507
John McCall469a1eb2011-02-02 13:00:07 +00009508 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009509 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9510 SmallVector<BlockDecl::Capture, 4> Captures;
9511 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9512 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9513 if (Cap.isThisCapture())
9514 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009515 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009516 Cap.isNested(), Cap.getCopyExpr());
9517 Captures.push_back(NewCap);
9518 }
9519 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9520 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009521
John McCallc71a4912010-06-04 19:02:56 +00009522 // If the user wrote a function type in some form, try to use that.
9523 if (!BSI->FunctionType.isNull()) {
9524 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9525
9526 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9527 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9528
9529 // Turn protoless block types into nullary block types.
9530 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009531 FunctionProtoType::ExtProtoInfo EPI;
9532 EPI.ExtInfo = Ext;
9533 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009534
9535 // Otherwise, if we don't need to change anything about the function type,
9536 // preserve its sugar structure.
9537 } else if (FTy->getResultType() == RetTy &&
9538 (!NoReturn || FTy->getNoReturnAttr())) {
9539 BlockTy = BSI->FunctionType;
9540
9541 // Otherwise, make the minimal modifications to the function type.
9542 } else {
9543 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009544 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9545 EPI.TypeQuals = 0; // FIXME: silently?
9546 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009547 BlockTy = Context.getFunctionType(RetTy,
9548 FPT->arg_type_begin(),
9549 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009550 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009551 }
9552
9553 // If we don't have a function type, just build one from nothing.
9554 } else {
John McCalle23cf432010-12-14 08:05:40 +00009555 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009556 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009557 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009558 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009559
John McCallc71a4912010-06-04 19:02:56 +00009560 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9561 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009562 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009563
Chris Lattner17a78302009-04-19 05:28:12 +00009564 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009565 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009566 !hasAnyUnrecoverableErrorsInThisFunction() &&
9567 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009568 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009569
Chris Lattnere476bdc2011-02-17 23:58:47 +00009570 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009571
Jordan Rose7dd900e2012-07-02 21:19:23 +00009572 // Try to apply the named return value optimization. We have to check again
9573 // if we can do this, though, because blocks keep return statements around
9574 // to deduce an implicit return type.
9575 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9576 !BSI->TheDecl->isDependentContext())
9577 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009578
Benjamin Kramerd2486192011-07-12 14:11:05 +00009579 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9580 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009581 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009582
John McCall80ee6e82011-11-10 05:35:25 +00009583 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009584 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009585 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009586 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009587 ExprCleanupObjects.push_back(Result->getBlockDecl());
9588 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009589
9590 // It also gets a branch-protected scope if any of the captured
9591 // variables needs destruction.
9592 for (BlockDecl::capture_const_iterator
9593 ci = Result->getBlockDecl()->capture_begin(),
9594 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9595 const VarDecl *var = ci->getVariable();
9596 if (var->getType().isDestructedType() != QualType::DK_none) {
9597 getCurFunction()->setHasBranchProtectedScope();
9598 break;
9599 }
9600 }
John McCall80ee6e82011-11-10 05:35:25 +00009601 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009602
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009603 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009604}
9605
John McCall60d7b3a2010-08-24 06:29:42 +00009606ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009607 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009608 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009609 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009610 GetTypeFromParser(Ty, &TInfo);
9611 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009612}
9613
John McCall60d7b3a2010-08-24 06:29:42 +00009614ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009615 Expr *E, TypeSourceInfo *TInfo,
9616 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009617 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009618
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009619 // Get the va_list type
9620 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009621 if (VaListType->isArrayType()) {
9622 // Deal with implicit array decay; for example, on x86-64,
9623 // va_list is an array, but it's supposed to decay to
9624 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009625 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009626 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009627 ExprResult Result = UsualUnaryConversions(E);
9628 if (Result.isInvalid())
9629 return ExprError();
9630 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009631 } else {
9632 // Otherwise, the va_list argument must be an l-value because
9633 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009634 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009635 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009636 return ExprError();
9637 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009638
Douglas Gregordd027302009-05-19 23:10:31 +00009639 if (!E->isTypeDependent() &&
9640 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009641 return ExprError(Diag(E->getLocStart(),
9642 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009643 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009644 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009645
David Majnemer0adde122011-06-14 05:17:32 +00009646 if (!TInfo->getType()->isDependentType()) {
9647 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009648 diag::err_second_parameter_to_va_arg_incomplete,
9649 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009650 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009651
David Majnemer0adde122011-06-14 05:17:32 +00009652 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009653 TInfo->getType(),
9654 diag::err_second_parameter_to_va_arg_abstract,
9655 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009656 return ExprError();
9657
Douglas Gregor4eb75222011-07-30 06:45:27 +00009658 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009659 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009660 TInfo->getType()->isObjCLifetimeType()
9661 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9662 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009663 << TInfo->getType()
9664 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009665 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009666
9667 // Check for va_arg where arguments of the given type will be promoted
9668 // (i.e. this va_arg is guaranteed to have undefined behavior).
9669 QualType PromoteType;
9670 if (TInfo->getType()->isPromotableIntegerType()) {
9671 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9672 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9673 PromoteType = QualType();
9674 }
9675 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9676 PromoteType = Context.DoubleTy;
9677 if (!PromoteType.isNull())
9678 Diag(TInfo->getTypeLoc().getBeginLoc(),
9679 diag::warn_second_parameter_to_va_arg_never_compatible)
9680 << TInfo->getType()
9681 << PromoteType
9682 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009683 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009684
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009685 QualType T = TInfo->getType().getNonLValueExprType(Context);
9686 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009687}
9688
John McCall60d7b3a2010-08-24 06:29:42 +00009689ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009690 // The type of __null will be int or long, depending on the size of
9691 // pointers on the target.
9692 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009693 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9694 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009695 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009696 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009697 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009698 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009699 Ty = Context.LongLongTy;
9700 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009701 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009702 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009703
Sebastian Redlf53597f2009-03-15 17:47:39 +00009704 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009705}
9706
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009707static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009708 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009709 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009710 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009711
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009712 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9713 if (!PT)
9714 return;
9715
9716 // Check if the destination is of type 'id'.
9717 if (!PT->isObjCIdType()) {
9718 // Check if the destination is the 'NSString' interface.
9719 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9720 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9721 return;
9722 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009723
John McCall4b9c2d22011-11-06 09:01:30 +00009724 // Ignore any parens, implicit casts (should only be
9725 // array-to-pointer decays), and not-so-opaque values. The last is
9726 // important for making this trigger for property assignments.
9727 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9728 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9729 if (OV->getSourceExpr())
9730 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9731
9732 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009733 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009734 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009735
Douglas Gregor849b2432010-03-31 17:46:05 +00009736 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009737}
9738
Chris Lattner5cf216b2008-01-04 18:04:52 +00009739bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9740 SourceLocation Loc,
9741 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009742 Expr *SrcExpr, AssignmentAction Action,
9743 bool *Complained) {
9744 if (Complained)
9745 *Complained = false;
9746
Chris Lattner5cf216b2008-01-04 18:04:52 +00009747 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009748 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009749 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009750 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009751 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009752 ConversionFixItGenerator ConvHints;
9753 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009754 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009755
Chris Lattner5cf216b2008-01-04 18:04:52 +00009756 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009757 case Compatible:
9758 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9759 return false;
9760
Chris Lattnerb7b61152008-01-04 18:22:42 +00009761 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009762 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009763 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9764 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009765 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009766 case IntToPointer:
9767 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009768 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9769 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009770 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009771 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009772 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009773 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009774 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9775 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009776 if (Hint.isNull() && !CheckInferredResultType) {
9777 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9778 }
9779 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009780 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009781 case IncompatiblePointerSign:
9782 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9783 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009784 case FunctionVoidPointer:
9785 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9786 break;
John McCall86c05f32011-02-01 00:10:29 +00009787 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009788 // Perform array-to-pointer decay if necessary.
9789 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9790
John McCall86c05f32011-02-01 00:10:29 +00009791 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9792 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9793 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9794 DiagKind = diag::err_typecheck_incompatible_address_space;
9795 break;
John McCallf85e1932011-06-15 23:02:42 +00009796
9797
9798 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009799 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009800 break;
John McCall86c05f32011-02-01 00:10:29 +00009801 }
9802
9803 llvm_unreachable("unknown error case for discarding qualifiers!");
9804 // fallthrough
9805 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009806 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009807 // If the qualifiers lost were because we were applying the
9808 // (deprecated) C++ conversion from a string literal to a char*
9809 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9810 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009811 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009812 // bit of refactoring (so that the second argument is an
9813 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009814 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009815 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009816 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009817 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9818 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009819 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9820 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009821 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009822 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009823 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009824 case IntToBlockPointer:
9825 DiagKind = diag::err_int_to_block_pointer;
9826 break;
9827 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009828 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009829 break;
Steve Naroff39579072008-10-14 22:18:38 +00009830 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009831 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009832 // it can give a more specific diagnostic.
9833 DiagKind = diag::warn_incompatible_qualified_id;
9834 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009835 case IncompatibleVectors:
9836 DiagKind = diag::warn_incompatible_vectors;
9837 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009838 case IncompatibleObjCWeakRef:
9839 DiagKind = diag::err_arc_weak_unavailable_assign;
9840 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009841 case Incompatible:
9842 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009843 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9844 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009845 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009846 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009847 break;
9848 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009849
Douglas Gregord4eea832010-04-09 00:35:39 +00009850 QualType FirstType, SecondType;
9851 switch (Action) {
9852 case AA_Assigning:
9853 case AA_Initializing:
9854 // The destination type comes first.
9855 FirstType = DstType;
9856 SecondType = SrcType;
9857 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009858
Douglas Gregord4eea832010-04-09 00:35:39 +00009859 case AA_Returning:
9860 case AA_Passing:
9861 case AA_Converting:
9862 case AA_Sending:
9863 case AA_Casting:
9864 // The source type comes first.
9865 FirstType = SrcType;
9866 SecondType = DstType;
9867 break;
9868 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009869
Anna Zaks67221552011-07-28 19:51:27 +00009870 PartialDiagnostic FDiag = PDiag(DiagKind);
9871 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9872
9873 // If we can fix the conversion, suggest the FixIts.
9874 assert(ConvHints.isNull() || Hint.isNull());
9875 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009876 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9877 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009878 FDiag << *HI;
9879 } else {
9880 FDiag << Hint;
9881 }
9882 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9883
Richard Trieu6efd4c52011-11-23 22:32:32 +00009884 if (MayHaveFunctionDiff)
9885 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9886
Anna Zaks67221552011-07-28 19:51:27 +00009887 Diag(Loc, FDiag);
9888
Richard Trieu6efd4c52011-11-23 22:32:32 +00009889 if (SecondType == Context.OverloadTy)
9890 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9891 FirstType);
9892
Douglas Gregor926df6c2011-06-11 01:09:30 +00009893 if (CheckInferredResultType)
9894 EmitRelatedResultTypeNote(SrcExpr);
9895
Douglas Gregora41a8c52010-04-22 00:20:18 +00009896 if (Complained)
9897 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009898 return isInvalid;
9899}
Anders Carlssone21555e2008-11-30 19:50:32 +00009900
Richard Smith282e7e62012-02-04 09:53:13 +00009901ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9902 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009903 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9904 public:
9905 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9906 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9907 }
9908 } Diagnoser;
9909
9910 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9911}
9912
9913ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9914 llvm::APSInt *Result,
9915 unsigned DiagID,
9916 bool AllowFold) {
9917 class IDDiagnoser : public VerifyICEDiagnoser {
9918 unsigned DiagID;
9919
9920 public:
9921 IDDiagnoser(unsigned DiagID)
9922 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9923
9924 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9925 S.Diag(Loc, DiagID) << SR;
9926 }
9927 } Diagnoser(DiagID);
9928
9929 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9930}
9931
9932void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9933 SourceRange SR) {
9934 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009935}
9936
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009937ExprResult
9938Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009939 VerifyICEDiagnoser &Diagnoser,
9940 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009941 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009942
David Blaikie4e4d0842012-03-11 07:00:24 +00009943 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009944 // C++11 [expr.const]p5:
9945 // If an expression of literal class type is used in a context where an
9946 // integral constant expression is required, then that class type shall
9947 // have a single non-explicit conversion function to an integral or
9948 // unscoped enumeration type
9949 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009950 if (!Diagnoser.Suppress) {
9951 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9952 public:
9953 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9954
9955 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9956 QualType T) {
9957 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9958 }
9959
9960 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9961 SourceLocation Loc,
9962 QualType T) {
9963 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9964 }
9965
9966 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9967 SourceLocation Loc,
9968 QualType T,
9969 QualType ConvTy) {
9970 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9971 }
9972
9973 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9974 CXXConversionDecl *Conv,
9975 QualType ConvTy) {
9976 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9977 << ConvTy->isEnumeralType() << ConvTy;
9978 }
9979
9980 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9981 QualType T) {
9982 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9983 }
9984
9985 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9986 CXXConversionDecl *Conv,
9987 QualType ConvTy) {
9988 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9989 << ConvTy->isEnumeralType() << ConvTy;
9990 }
9991
9992 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9993 SourceLocation Loc,
9994 QualType T,
9995 QualType ConvTy) {
9996 return DiagnosticBuilder::getEmpty();
9997 }
9998 } ConvertDiagnoser;
9999
10000 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10001 ConvertDiagnoser,
10002 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +000010003 } else {
10004 // The caller wants to silently enquire whether this is an ICE. Don't
10005 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010006 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10007 public:
10008 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10009
10010 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10011 QualType T) {
10012 return DiagnosticBuilder::getEmpty();
10013 }
10014
10015 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10016 SourceLocation Loc,
10017 QualType T) {
10018 return DiagnosticBuilder::getEmpty();
10019 }
10020
10021 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10022 SourceLocation Loc,
10023 QualType T,
10024 QualType ConvTy) {
10025 return DiagnosticBuilder::getEmpty();
10026 }
10027
10028 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10029 CXXConversionDecl *Conv,
10030 QualType ConvTy) {
10031 return DiagnosticBuilder::getEmpty();
10032 }
10033
10034 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10035 QualType T) {
10036 return DiagnosticBuilder::getEmpty();
10037 }
10038
10039 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10040 CXXConversionDecl *Conv,
10041 QualType ConvTy) {
10042 return DiagnosticBuilder::getEmpty();
10043 }
10044
10045 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10046 SourceLocation Loc,
10047 QualType T,
10048 QualType ConvTy) {
10049 return DiagnosticBuilder::getEmpty();
10050 }
10051 } ConvertDiagnoser;
10052
10053 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10054 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +000010055 }
10056 if (Converted.isInvalid())
10057 return Converted;
10058 E = Converted.take();
10059 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10060 return ExprError();
10061 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10062 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010063 if (!Diagnoser.Suppress)
10064 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000010065 return ExprError();
10066 }
10067
Richard Smithdaaefc52011-12-14 23:32:26 +000010068 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10069 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +000010070 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000010071 if (Result)
10072 *Result = E->EvaluateKnownConstInt(Context);
10073 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010074 }
10075
Anders Carlssone21555e2008-11-30 19:50:32 +000010076 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +000010077 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10078 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000010079
Richard Smithdaaefc52011-12-14 23:32:26 +000010080 // Try to evaluate the expression, and produce diagnostics explaining why it's
10081 // not a constant expression as a side-effect.
10082 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10083 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10084
10085 // In C++11, we can rely on diagnostics being produced for any expression
10086 // which is not a constant expression. If no diagnostics were produced, then
10087 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +000010088 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010089 if (Result)
10090 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010091 return Owned(E);
10092 }
10093
10094 // If our only note is the usual "invalid subexpression" note, just point
10095 // the caret at its location rather than producing an essentially
10096 // redundant note.
10097 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10098 diag::note_invalid_subexpr_in_const_expr) {
10099 DiagLoc = Notes[0].first;
10100 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010101 }
10102
10103 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010104 if (!Diagnoser.Suppress) {
10105 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010106 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10107 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010108 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010109
Richard Smith282e7e62012-02-04 09:53:13 +000010110 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010111 }
10112
Douglas Gregorab41fe92012-05-04 22:38:52 +000010113 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010114 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10115 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010116
Anders Carlssone21555e2008-11-30 19:50:32 +000010117 if (Result)
10118 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010119 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010120}
Douglas Gregore0762c92009-06-19 23:52:42 +000010121
Eli Friedmanef331b72012-01-20 01:26:23 +000010122namespace {
10123 // Handle the case where we conclude a expression which we speculatively
10124 // considered to be unevaluated is actually evaluated.
10125 class TransformToPE : public TreeTransform<TransformToPE> {
10126 typedef TreeTransform<TransformToPE> BaseTransform;
10127
10128 public:
10129 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10130
10131 // Make sure we redo semantic analysis
10132 bool AlwaysRebuild() { return true; }
10133
Eli Friedman56ff2832012-02-06 23:29:57 +000010134 // Make sure we handle LabelStmts correctly.
10135 // FIXME: This does the right thing, but maybe we need a more general
10136 // fix to TreeTransform?
10137 StmtResult TransformLabelStmt(LabelStmt *S) {
10138 S->getDecl()->setStmt(0);
10139 return BaseTransform::TransformLabelStmt(S);
10140 }
10141
Eli Friedmanef331b72012-01-20 01:26:23 +000010142 // We need to special-case DeclRefExprs referring to FieldDecls which
10143 // are not part of a member pointer formation; normal TreeTransforming
10144 // doesn't catch this case because of the way we represent them in the AST.
10145 // FIXME: This is a bit ugly; is it really the best way to handle this
10146 // case?
10147 //
10148 // Error on DeclRefExprs referring to FieldDecls.
10149 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10150 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010151 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010152 return SemaRef.Diag(E->getLocation(),
10153 diag::err_invalid_non_static_member_use)
10154 << E->getDecl() << E->getSourceRange();
10155
10156 return BaseTransform::TransformDeclRefExpr(E);
10157 }
10158
10159 // Exception: filter out member pointer formation
10160 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10161 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10162 return E;
10163
10164 return BaseTransform::TransformUnaryOperator(E);
10165 }
10166
Douglas Gregore2c59132012-02-09 08:14:43 +000010167 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10168 // Lambdas never need to be transformed.
10169 return E;
10170 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010171 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010172}
10173
Eli Friedmanef331b72012-01-20 01:26:23 +000010174ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010175 assert(ExprEvalContexts.back().Context == Unevaluated &&
10176 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010177 ExprEvalContexts.back().Context =
10178 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10179 if (ExprEvalContexts.back().Context == Unevaluated)
10180 return E;
10181 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010182}
10183
Douglas Gregor2afce722009-11-26 00:44:06 +000010184void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010185Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010186 Decl *LambdaContextDecl,
10187 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010188 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010189 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010190 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010191 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010192 LambdaContextDecl,
10193 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010194 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010195 if (!MaybeODRUseExprs.empty())
10196 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010197}
10198
Eli Friedman80bfa3d2012-09-26 04:34:21 +000010199void
10200Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10201 ReuseLambdaContextDecl_t,
10202 bool IsDecltype) {
10203 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10204 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10205}
10206
Richard Trieu67e29332011-08-02 04:35:43 +000010207void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010208 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010209
Douglas Gregore2c59132012-02-09 08:14:43 +000010210 if (!Rec.Lambdas.empty()) {
10211 if (Rec.Context == Unevaluated) {
10212 // C++11 [expr.prim.lambda]p2:
10213 // A lambda-expression shall not appear in an unevaluated operand
10214 // (Clause 5).
10215 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10216 Diag(Rec.Lambdas[I]->getLocStart(),
10217 diag::err_lambda_unevaluated_operand);
10218 } else {
10219 // Mark the capture expressions odr-used. This was deferred
10220 // during lambda expression creation.
10221 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10222 LambdaExpr *Lambda = Rec.Lambdas[I];
10223 for (LambdaExpr::capture_init_iterator
10224 C = Lambda->capture_init_begin(),
10225 CEnd = Lambda->capture_init_end();
10226 C != CEnd; ++C) {
10227 MarkDeclarationsReferencedInExpr(*C);
10228 }
10229 }
10230 }
10231 }
10232
Douglas Gregor2afce722009-11-26 00:44:06 +000010233 // When are coming out of an unevaluated context, clear out any
10234 // temporaries that we may have created as part of the evaluation of
10235 // the expression in that context: they aren't relevant because they
10236 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010237 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010238 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10239 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010240 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010241 CleanupVarDeclMarking();
10242 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010243 // Otherwise, merge the contexts together.
10244 } else {
10245 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010246 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10247 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010248 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010249
10250 // Pop the current expression evaluation context off the stack.
10251 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010252}
Douglas Gregore0762c92009-06-19 23:52:42 +000010253
John McCallf85e1932011-06-15 23:02:42 +000010254void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010255 ExprCleanupObjects.erase(
10256 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10257 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010258 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010259 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010260}
10261
Eli Friedman71b8fb52012-01-21 01:01:51 +000010262ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10263 if (!E->getType()->isVariablyModifiedType())
10264 return E;
10265 return TranformToPotentiallyEvaluated(E);
10266}
10267
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010268static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010269 // Do not mark anything as "used" within a dependent context; wait for
10270 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010271 if (SemaRef.CurContext->isDependentContext())
10272 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010273
Eli Friedman5f2987c2012-02-02 03:46:19 +000010274 switch (SemaRef.ExprEvalContexts.back().Context) {
10275 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010276 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010277 // (Depending on how you read the standard, we actually do need to do
10278 // something here for null pointer constants, but the standard's
10279 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010280 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010281
Eli Friedman5f2987c2012-02-02 03:46:19 +000010282 case Sema::ConstantEvaluated:
10283 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010284 // We are in a potentially evaluated expression (or a constant-expression
10285 // in C++03); we need to do implicit template instantiation, implicitly
10286 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010287 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010288
Eli Friedman5f2987c2012-02-02 03:46:19 +000010289 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010290 // Referenced declarations will only be used if the construct in the
10291 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010292 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010293 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010294 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010295}
10296
10297/// \brief Mark a function referenced, and check whether it is odr-used
10298/// (C++ [basic.def.odr]p2, C99 6.9p3)
10299void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10300 assert(Func && "No function?");
10301
10302 Func->setReferenced();
10303
Richard Smith57b9c4e2012-02-14 22:25:15 +000010304 // Don't mark this function as used multiple times, unless it's a constexpr
10305 // function which we need to instantiate.
10306 if (Func->isUsed(false) &&
10307 !(Func->isConstexpr() && !Func->getBody() &&
10308 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010309 return;
10310
10311 if (!IsPotentiallyEvaluatedContext(*this))
10312 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010313
Douglas Gregore0762c92009-06-19 23:52:42 +000010314 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010315 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010316 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010317 if (Constructor->isDefaultConstructor()) {
10318 if (Constructor->isTrivial())
10319 return;
10320 if (!Constructor->isUsed(false))
10321 DefineImplicitDefaultConstructor(Loc, Constructor);
10322 } else if (Constructor->isCopyConstructor()) {
10323 if (!Constructor->isUsed(false))
10324 DefineImplicitCopyConstructor(Loc, Constructor);
10325 } else if (Constructor->isMoveConstructor()) {
10326 if (!Constructor->isUsed(false))
10327 DefineImplicitMoveConstructor(Loc, Constructor);
10328 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010329 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010330
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010331 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010332 } else if (CXXDestructorDecl *Destructor =
10333 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010334 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10335 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010336 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010337 if (Destructor->isVirtual())
10338 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010339 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010340 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10341 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010342 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010343 if (!MethodDecl->isUsed(false)) {
10344 if (MethodDecl->isCopyAssignmentOperator())
10345 DefineImplicitCopyAssignment(Loc, MethodDecl);
10346 else
10347 DefineImplicitMoveAssignment(Loc, MethodDecl);
10348 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010349 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10350 MethodDecl->getParent()->isLambda()) {
10351 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10352 if (Conversion->isLambdaToBlockPointerConversion())
10353 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10354 else
10355 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010356 } else if (MethodDecl->isVirtual())
10357 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010358 }
John McCall15e310a2011-02-19 02:53:41 +000010359
Eli Friedman5f2987c2012-02-02 03:46:19 +000010360 // Recursive functions should be marked when used from another function.
10361 // FIXME: Is this really right?
10362 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010363
Richard Smithb9d0b762012-07-27 04:22:15 +000010364 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010365 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010366 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010367 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10368 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010369
Eli Friedman5f2987c2012-02-02 03:46:19 +000010370 // Implicit instantiation of function templates and member functions of
10371 // class templates.
10372 if (Func->isImplicitlyInstantiable()) {
10373 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010374 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010375 if (FunctionTemplateSpecializationInfo *SpecInfo
10376 = Func->getTemplateSpecializationInfo()) {
10377 if (SpecInfo->getPointOfInstantiation().isInvalid())
10378 SpecInfo->setPointOfInstantiation(Loc);
10379 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010380 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010381 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010382 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10383 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010384 } else if (MemberSpecializationInfo *MSInfo
10385 = Func->getMemberSpecializationInfo()) {
10386 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010387 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010388 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010389 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010390 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010391 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10392 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010393 }
Mike Stump1eb44332009-09-09 15:08:12 +000010394
Richard Smith57b9c4e2012-02-14 22:25:15 +000010395 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010396 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10397 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010398 PendingLocalImplicitInstantiations.push_back(
10399 std::make_pair(Func, PointOfInstantiation));
10400 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010401 // Do not defer instantiations of constexpr functions, to avoid the
10402 // expression evaluator needing to call back into Sema if it sees a
10403 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010404 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010405 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010406 PendingInstantiations.push_back(std::make_pair(Func,
10407 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010408 // Notify the consumer that a function was implicitly instantiated.
10409 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10410 }
John McCall15e310a2011-02-19 02:53:41 +000010411 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010412 } else {
10413 // Walk redefinitions, as some of them may be instantiable.
10414 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10415 e(Func->redecls_end()); i != e; ++i) {
10416 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10417 MarkFunctionReferenced(Loc, *i);
10418 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010419 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010420
10421 // Keep track of used but undefined functions.
10422 if (!Func->isPure() && !Func->hasBody() &&
10423 Func->getLinkage() != ExternalLinkage) {
10424 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10425 if (old.isInvalid()) old = Loc;
10426 }
10427
10428 Func->setUsed(true);
10429}
10430
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010431static void
10432diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10433 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010434 DeclContext *VarDC = var->getDeclContext();
10435
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010436 // If the parameter still belongs to the translation unit, then
10437 // we're actually just using one parameter in the declaration of
10438 // the next.
10439 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010440 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010441 return;
10442
Eli Friedman0a294222012-02-07 00:15:00 +000010443 // For C code, don't diagnose about capture if we're not actually in code
10444 // right now; it's impossible to write a non-constant expression outside of
10445 // function context, so we'll get other (more useful) diagnostics later.
10446 //
10447 // For C++, things get a bit more nasty... it would be nice to suppress this
10448 // diagnostic for certain cases like using a local variable in an array bound
10449 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010450 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010451 return;
10452
Eli Friedman0a294222012-02-07 00:15:00 +000010453 if (isa<CXXMethodDecl>(VarDC) &&
10454 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10455 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10456 << var->getIdentifier();
10457 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10458 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10459 << var->getIdentifier() << fn->getDeclName();
10460 } else if (isa<BlockDecl>(VarDC)) {
10461 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10462 << var->getIdentifier();
10463 } else {
10464 // FIXME: Is there any other context where a local variable can be
10465 // declared?
10466 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10467 << var->getIdentifier();
10468 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010469
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010470 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10471 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010472
10473 // FIXME: Add additional diagnostic info about class etc. which prevents
10474 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010475}
10476
Douglas Gregorf8af9822012-02-12 18:42:33 +000010477/// \brief Capture the given variable in the given lambda expression.
10478static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010479 VarDecl *Var, QualType FieldType,
10480 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010481 SourceLocation Loc,
10482 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010483 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010484
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010485 // Build the non-static data member.
10486 FieldDecl *Field
10487 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10488 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010489 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010490 Field->setImplicit(true);
10491 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010492 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010493
10494 // C++11 [expr.prim.lambda]p21:
10495 // When the lambda-expression is evaluated, the entities that
10496 // are captured by copy are used to direct-initialize each
10497 // corresponding non-static data member of the resulting closure
10498 // object. (For array members, the array elements are
10499 // direct-initialized in increasing subscript order.) These
10500 // initializations are performed in the (unspecified) order in
10501 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010502
Douglas Gregore2c59132012-02-09 08:14:43 +000010503 // Introduce a new evaluation context for the initialization, so
10504 // that temporaries introduced as part of the capture are retained
10505 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010506 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10507
Douglas Gregor73d90922012-02-10 09:26:04 +000010508 // C++ [expr.prim.labda]p12:
10509 // An entity captured by a lambda-expression is odr-used (3.2) in
10510 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010511 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10512 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010513 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010514 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010515
10516 // When the field has array type, create index variables for each
10517 // dimension of the array. We use these index variables to subscript
10518 // the source array, and other clients (e.g., CodeGen) will perform
10519 // the necessary iteration with these index variables.
10520 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010521 QualType BaseType = FieldType;
10522 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010523 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010524 while (const ConstantArrayType *Array
10525 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010526 // Create the iteration variable for this array index.
10527 IdentifierInfo *IterationVarName = 0;
10528 {
10529 SmallString<8> Str;
10530 llvm::raw_svector_ostream OS(Str);
10531 OS << "__i" << IndexVariables.size();
10532 IterationVarName = &S.Context.Idents.get(OS.str());
10533 }
10534 VarDecl *IterationVar
10535 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10536 IterationVarName, SizeType,
10537 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10538 SC_None, SC_None);
10539 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010540 LSI->ArrayIndexVars.push_back(IterationVar);
10541
Douglas Gregor18fe0842012-02-09 02:45:47 +000010542 // Create a reference to the iteration variable.
10543 ExprResult IterationVarRef
10544 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10545 assert(!IterationVarRef.isInvalid() &&
10546 "Reference to invented variable cannot fail!");
10547 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10548 assert(!IterationVarRef.isInvalid() &&
10549 "Conversion of invented variable cannot fail!");
10550
10551 // Subscript the array with this iteration variable.
10552 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10553 Ref, Loc, IterationVarRef.take(), Loc);
10554 if (Subscript.isInvalid()) {
10555 S.CleanupVarDeclMarking();
10556 S.DiscardCleanupsInEvaluationContext();
10557 S.PopExpressionEvaluationContext();
10558 return ExprError();
10559 }
10560
10561 Ref = Subscript.take();
10562 BaseType = Array->getElementType();
10563 }
10564
10565 // Construct the entity that we will be initializing. For an array, this
10566 // will be first element in the array, which may require several levels
10567 // of array-subscript entities.
10568 SmallVector<InitializedEntity, 4> Entities;
10569 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010570 Entities.push_back(
10571 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010572 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10573 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10574 0,
10575 Entities.back()));
10576
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010577 InitializationKind InitKind
10578 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010579 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010580 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010581 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010582 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010583
10584 // If this initialization requires any cleanups (e.g., due to a
10585 // default argument to a copy constructor), note that for the
10586 // lambda.
10587 if (S.ExprNeedsCleanups)
10588 LSI->ExprNeedsCleanups = true;
10589
10590 // Exit the expression evaluation context used for the capture.
10591 S.CleanupVarDeclMarking();
10592 S.DiscardCleanupsInEvaluationContext();
10593 S.PopExpressionEvaluationContext();
10594 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010595}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010596
Douglas Gregor999713e2012-02-18 09:37:24 +000010597bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10598 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10599 bool BuildAndDiagnose,
10600 QualType &CaptureType,
10601 QualType &DeclRefType) {
10602 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010603
Eli Friedmanb942cb22012-02-03 22:47:37 +000010604 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010605 if (Var->getDeclContext() == DC) return true;
10606 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010607
Douglas Gregorf8af9822012-02-12 18:42:33 +000010608 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010609
Douglas Gregor999713e2012-02-18 09:37:24 +000010610 // Walk up the stack to determine whether we can capture the variable,
10611 // performing the "simple" checks that don't depend on type. We stop when
10612 // we've either hit the declared scope of the variable or find an existing
10613 // capture of that variable.
10614 CaptureType = Var->getType();
10615 DeclRefType = CaptureType.getNonReferenceType();
10616 bool Explicit = (Kind != TryCapture_Implicit);
10617 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010618 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010619 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010620 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010621 DeclContext *ParentDC;
10622 if (isa<BlockDecl>(DC))
10623 ParentDC = DC->getParent();
10624 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010625 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010626 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10627 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010628 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010629 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010630 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010631 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010632 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010633
Eli Friedmanb942cb22012-02-03 22:47:37 +000010634 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010635 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010636
Eli Friedmanb942cb22012-02-03 22:47:37 +000010637 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010638 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010639 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010640 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010641
10642 // Retrieve the capture type for this variable.
10643 CaptureType = CSI->getCapture(Var).getCaptureType();
10644
10645 // Compute the type of an expression that refers to this variable.
10646 DeclRefType = CaptureType.getNonReferenceType();
10647
10648 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10649 if (Cap.isCopyCapture() &&
10650 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10651 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010652 break;
10653 }
10654
Douglas Gregorf8af9822012-02-12 18:42:33 +000010655 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010656 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010657
10658 // Lambdas are not allowed to capture unnamed variables
10659 // (e.g. anonymous unions).
10660 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10661 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010662 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010663 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010664 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10665 Diag(Var->getLocation(), diag::note_declared_at);
10666 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010667 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010668 }
10669
10670 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010671 if (Var->getType()->isVariablyModifiedType()) {
10672 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010673 if (IsBlock)
10674 Diag(Loc, diag::err_ref_vm_type);
10675 else
10676 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10677 Diag(Var->getLocation(), diag::note_previous_decl)
10678 << Var->getDeclName();
10679 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010680 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010681 }
10682
Eli Friedmanb942cb22012-02-03 22:47:37 +000010683 // Lambdas are not allowed to capture __block variables; they don't
10684 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010685 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010686 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010687 Diag(Loc, diag::err_lambda_capture_block)
10688 << Var->getDeclName();
10689 Diag(Var->getLocation(), diag::note_previous_decl)
10690 << Var->getDeclName();
10691 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010692 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010693 }
10694
Douglas Gregorf8af9822012-02-12 18:42:33 +000010695 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10696 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010697 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010698 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10699 Diag(Var->getLocation(), diag::note_previous_decl)
10700 << Var->getDeclName();
10701 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10702 diag::note_lambda_decl);
10703 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010704 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010705 }
10706
10707 FunctionScopesIndex--;
10708 DC = ParentDC;
10709 Explicit = false;
10710 } while (!Var->getDeclContext()->Equals(DC));
10711
Douglas Gregor999713e2012-02-18 09:37:24 +000010712 // Walk back down the scope stack, computing the type of the capture at
10713 // each step, checking type-specific requirements, and adding captures if
10714 // requested.
10715 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10716 ++I) {
10717 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010718
Douglas Gregor999713e2012-02-18 09:37:24 +000010719 // Compute the type of the capture and of a reference to the capture within
10720 // this scope.
10721 if (isa<BlockScopeInfo>(CSI)) {
10722 Expr *CopyExpr = 0;
10723 bool ByRef = false;
10724
10725 // Blocks are not allowed to capture arrays.
10726 if (CaptureType->isArrayType()) {
10727 if (BuildAndDiagnose) {
10728 Diag(Loc, diag::err_ref_array_type);
10729 Diag(Var->getLocation(), diag::note_previous_decl)
10730 << Var->getDeclName();
10731 }
10732 return true;
10733 }
10734
John McCall100c6492012-03-30 05:23:48 +000010735 // Forbid the block-capture of autoreleasing variables.
10736 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10737 if (BuildAndDiagnose) {
10738 Diag(Loc, diag::err_arc_autoreleasing_capture)
10739 << /*block*/ 0;
10740 Diag(Var->getLocation(), diag::note_previous_decl)
10741 << Var->getDeclName();
10742 }
10743 return true;
10744 }
10745
Douglas Gregor999713e2012-02-18 09:37:24 +000010746 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10747 // Block capture by reference does not change the capture or
10748 // declaration reference types.
10749 ByRef = true;
10750 } else {
10751 // Block capture by copy introduces 'const'.
10752 CaptureType = CaptureType.getNonReferenceType().withConst();
10753 DeclRefType = CaptureType;
10754
David Blaikie4e4d0842012-03-11 07:00:24 +000010755 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010756 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10757 // The capture logic needs the destructor, so make sure we mark it.
10758 // Usually this is unnecessary because most local variables have
10759 // their destructors marked at declaration time, but parameters are
10760 // an exception because it's technically only the call site that
10761 // actually requires the destructor.
10762 if (isa<ParmVarDecl>(Var))
10763 FinalizeVarWithDestructor(Var, Record);
10764
10765 // According to the blocks spec, the capture of a variable from
10766 // the stack requires a const copy constructor. This is not true
10767 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010768 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010769 DeclRefType.withConst(),
10770 VK_LValue, Loc);
10771 ExprResult Result
10772 = PerformCopyInitialization(
10773 InitializedEntity::InitializeBlock(Var->getLocation(),
10774 CaptureType, false),
10775 Loc, Owned(DeclRef));
10776
10777 // Build a full-expression copy expression if initialization
10778 // succeeded and used a non-trivial constructor. Recover from
10779 // errors by pretending that the copy isn't necessary.
10780 if (!Result.isInvalid() &&
10781 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10782 ->isTrivial()) {
10783 Result = MaybeCreateExprWithCleanups(Result);
10784 CopyExpr = Result.take();
10785 }
10786 }
10787 }
10788 }
10789
10790 // Actually capture the variable.
10791 if (BuildAndDiagnose)
10792 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10793 SourceLocation(), CaptureType, CopyExpr);
10794 Nested = true;
10795 continue;
10796 }
Douglas Gregor68932842012-02-18 05:51:20 +000010797
Douglas Gregor999713e2012-02-18 09:37:24 +000010798 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10799
10800 // Determine whether we are capturing by reference or by value.
10801 bool ByRef = false;
10802 if (I == N - 1 && Kind != TryCapture_Implicit) {
10803 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010804 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010805 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010806 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010807
10808 // Compute the type of the field that will capture this variable.
10809 if (ByRef) {
10810 // C++11 [expr.prim.lambda]p15:
10811 // An entity is captured by reference if it is implicitly or
10812 // explicitly captured but not captured by copy. It is
10813 // unspecified whether additional unnamed non-static data
10814 // members are declared in the closure type for entities
10815 // captured by reference.
10816 //
10817 // FIXME: It is not clear whether we want to build an lvalue reference
10818 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10819 // to do the former, while EDG does the latter. Core issue 1249 will
10820 // clarify, but for now we follow GCC because it's a more permissive and
10821 // easily defensible position.
10822 CaptureType = Context.getLValueReferenceType(DeclRefType);
10823 } else {
10824 // C++11 [expr.prim.lambda]p14:
10825 // For each entity captured by copy, an unnamed non-static
10826 // data member is declared in the closure type. The
10827 // declaration order of these members is unspecified. The type
10828 // of such a data member is the type of the corresponding
10829 // captured entity if the entity is not a reference to an
10830 // object, or the referenced type otherwise. [Note: If the
10831 // captured entity is a reference to a function, the
10832 // corresponding data member is also a reference to a
10833 // function. - end note ]
10834 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10835 if (!RefType->getPointeeType()->isFunctionType())
10836 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010837 }
John McCall100c6492012-03-30 05:23:48 +000010838
10839 // Forbid the lambda copy-capture of autoreleasing variables.
10840 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10841 if (BuildAndDiagnose) {
10842 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10843 Diag(Var->getLocation(), diag::note_previous_decl)
10844 << Var->getDeclName();
10845 }
10846 return true;
10847 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010848 }
10849
Douglas Gregor999713e2012-02-18 09:37:24 +000010850 // Capture this variable in the lambda.
10851 Expr *CopyExpr = 0;
10852 if (BuildAndDiagnose) {
10853 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010854 DeclRefType, Loc,
10855 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010856 if (!Result.isInvalid())
10857 CopyExpr = Result.take();
10858 }
10859
10860 // Compute the type of a reference to this captured variable.
10861 if (ByRef)
10862 DeclRefType = CaptureType.getNonReferenceType();
10863 else {
10864 // C++ [expr.prim.lambda]p5:
10865 // The closure type for a lambda-expression has a public inline
10866 // function call operator [...]. This function call operator is
10867 // declared const (9.3.1) if and only if the lambda-expression’s
10868 // parameter-declaration-clause is not followed by mutable.
10869 DeclRefType = CaptureType.getNonReferenceType();
10870 if (!LSI->Mutable && !CaptureType->isReferenceType())
10871 DeclRefType.addConst();
10872 }
10873
10874 // Add the capture.
10875 if (BuildAndDiagnose)
10876 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10877 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010878 Nested = true;
10879 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010880
10881 return false;
10882}
10883
10884bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10885 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10886 QualType CaptureType;
10887 QualType DeclRefType;
10888 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10889 /*BuildAndDiagnose=*/true, CaptureType,
10890 DeclRefType);
10891}
10892
10893QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10894 QualType CaptureType;
10895 QualType DeclRefType;
10896
10897 // Determine whether we can capture this variable.
10898 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10899 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10900 return QualType();
10901
10902 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010903}
10904
Eli Friedmand2cce132012-02-02 23:15:15 +000010905static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10906 SourceLocation Loc) {
10907 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010908 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010909 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010910 Var->getLinkage() != ExternalLinkage &&
10911 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010912 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10913 if (old.isInvalid()) old = Loc;
10914 }
10915
Douglas Gregor999713e2012-02-18 09:37:24 +000010916 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010917
Eli Friedmand2cce132012-02-02 23:15:15 +000010918 Var->setUsed(true);
10919}
10920
10921void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10922 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10923 // an object that satisfies the requirements for appearing in a
10924 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10925 // is immediately applied." This function handles the lvalue-to-rvalue
10926 // conversion part.
10927 MaybeODRUseExprs.erase(E->IgnoreParens());
10928}
10929
Eli Friedmanac626012012-02-29 03:16:56 +000010930ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10931 if (!Res.isUsable())
10932 return Res;
10933
10934 // If a constant-expression is a reference to a variable where we delay
10935 // deciding whether it is an odr-use, just assume we will apply the
10936 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10937 // (a non-type template argument), we have special handling anyway.
10938 UpdateMarkingForLValueToRValue(Res.get());
10939 return Res;
10940}
10941
Eli Friedmand2cce132012-02-02 23:15:15 +000010942void Sema::CleanupVarDeclMarking() {
10943 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10944 e = MaybeODRUseExprs.end();
10945 i != e; ++i) {
10946 VarDecl *Var;
10947 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010948 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010949 Var = cast<VarDecl>(DRE->getDecl());
10950 Loc = DRE->getLocation();
10951 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10952 Var = cast<VarDecl>(ME->getMemberDecl());
10953 Loc = ME->getMemberLoc();
10954 } else {
10955 llvm_unreachable("Unexpcted expression");
10956 }
10957
10958 MarkVarDeclODRUsed(*this, Var, Loc);
10959 }
10960
10961 MaybeODRUseExprs.clear();
10962}
10963
10964// Mark a VarDecl referenced, and perform the necessary handling to compute
10965// odr-uses.
10966static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10967 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010968 Var->setReferenced();
10969
Eli Friedmand2cce132012-02-02 23:15:15 +000010970 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010971 return;
10972
10973 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010974 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010975 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10976 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010977 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10978 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010979 (!AlreadyInstantiated ||
10980 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010981 if (!AlreadyInstantiated) {
10982 // This is a modification of an existing AST node. Notify listeners.
10983 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10984 L->StaticDataMemberInstantiated(Var);
10985 MSInfo->setPointOfInstantiation(Loc);
10986 }
10987 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010988 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010989 // Do not defer instantiations of variables which could be used in a
10990 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000010991 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010992 else
Richard Smith37ce0102012-02-15 02:42:50 +000010993 SemaRef.PendingInstantiations.push_back(
10994 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010995 }
10996 }
10997
Eli Friedmand2cce132012-02-02 23:15:15 +000010998 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10999 // an object that satisfies the requirements for appearing in a
11000 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11001 // is immediately applied." We check the first part here, and
11002 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11003 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000011004 // C++03 depends on whether we get the C++03 version correct. This does not
11005 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000011006 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000011007 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011008 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000011009 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
11010 SemaRef.MaybeODRUseExprs.insert(E);
11011 else
11012 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11013}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011014
Eli Friedmand2cce132012-02-02 23:15:15 +000011015/// \brief Mark a variable referenced, and check whether it is odr-used
11016/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11017/// used directly for normal expressions referring to VarDecl.
11018void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11019 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011020}
11021
11022static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11023 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011024 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11025 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11026 return;
11027 }
11028
Eli Friedman5f2987c2012-02-02 03:46:19 +000011029 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011030
11031 // If this is a call to a method via a cast, also mark the method in the
11032 // derived class used in case codegen can devirtualize the call.
11033 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11034 if (!ME)
11035 return;
11036 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11037 if (!MD)
11038 return;
11039 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000011040 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011041 if (!MostDerivedClassDecl)
11042 return;
11043 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000011044 if (!DM)
11045 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011046 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011047}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011048
Eli Friedman5f2987c2012-02-02 03:46:19 +000011049/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11050void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11051 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11052}
11053
11054/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11055void Sema::MarkMemberReferenced(MemberExpr *E) {
11056 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11057}
11058
Douglas Gregor73d90922012-02-10 09:26:04 +000011059/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000011060/// marks the declaration referenced, and performs odr-use checking for functions
11061/// and variables. This method should not be used when building an normal
11062/// expression which refers to a variable.
11063void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11064 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11065 MarkVariableReferenced(Loc, VD);
11066 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11067 MarkFunctionReferenced(Loc, FD);
11068 else
11069 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000011070}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011071
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011072namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011073 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011074 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011075 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011076 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11077 Sema &S;
11078 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011079
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011080 public:
11081 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011082
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011083 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011084
11085 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11086 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011087 };
11088}
11089
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011090bool MarkReferencedDecls::TraverseTemplateArgument(
11091 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011092 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011093 if (Decl *D = Arg.getAsDecl())
11094 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011095 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011096
11097 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011098}
11099
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011100bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011101 if (ClassTemplateSpecializationDecl *Spec
11102 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11103 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011104 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011105 }
11106
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011107 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011108}
11109
11110void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11111 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011112 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011113}
11114
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011115namespace {
11116 /// \brief Helper class that marks all of the declarations referenced by
11117 /// potentially-evaluated subexpressions as "referenced".
11118 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11119 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011120 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011121
11122 public:
11123 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11124
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011125 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11126 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011127
11128 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011129 // If we were asked not to visit local variables, don't.
11130 if (SkipLocalVariables) {
11131 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11132 if (VD->hasLocalStorage())
11133 return;
11134 }
11135
Eli Friedman5f2987c2012-02-02 03:46:19 +000011136 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011137 }
11138
11139 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011140 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011141 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011142 }
11143
John McCall80ee6e82011-11-10 05:35:25 +000011144 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011145 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011146 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11147 Visit(E->getSubExpr());
11148 }
11149
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011150 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011151 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011152 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011153 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011154 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011155 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011156 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011157
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011158 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11159 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011160 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011161 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11162 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11163 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011164 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011165 S.LookupDestructor(Record));
11166 }
11167
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011168 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011169 }
11170
11171 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011172 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011173 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011174 }
11175
Douglas Gregor102ff972010-10-19 17:17:35 +000011176 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11177 Visit(E->getExpr());
11178 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011179
11180 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11181 Inherited::VisitImplicitCastExpr(E);
11182
11183 if (E->getCastKind() == CK_LValueToRValue)
11184 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11185 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011186 };
11187}
11188
11189/// \brief Mark any declarations that appear within this expression or any
11190/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011191///
11192/// \param SkipLocalVariables If true, don't mark local variables as
11193/// 'referenced'.
11194void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11195 bool SkipLocalVariables) {
11196 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011197}
11198
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011199/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11200/// of the program being compiled.
11201///
11202/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011203/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011204/// possibility that the code will actually be executable. Code in sizeof()
11205/// expressions, code used only during overload resolution, etc., are not
11206/// potentially evaluated. This routine will suppress such diagnostics or,
11207/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011208/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011209/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011210///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011211/// This routine should be used for all diagnostics that describe the run-time
11212/// behavior of a program, such as passing a non-POD value through an ellipsis.
11213/// Failure to do so will likely result in spurious diagnostics or failures
11214/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011215bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011216 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011217 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011218 case Unevaluated:
11219 // The argument will never be evaluated, so don't complain.
11220 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011221
Richard Smithf6702a32011-12-20 02:08:33 +000011222 case ConstantEvaluated:
11223 // Relevant diagnostics should be produced by constant evaluation.
11224 break;
11225
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011226 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011227 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011228 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011229 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011230 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011231 }
11232 else
11233 Diag(Loc, PD);
11234
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011235 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011236 }
11237
11238 return false;
11239}
11240
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011241bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11242 CallExpr *CE, FunctionDecl *FD) {
11243 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11244 return false;
11245
Richard Smith76f3f692012-02-22 02:04:18 +000011246 // If we're inside a decltype's expression, don't check for a valid return
11247 // type or construct temporaries until we know whether this is the last call.
11248 if (ExprEvalContexts.back().IsDecltype) {
11249 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11250 return false;
11251 }
11252
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011253 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011254 FunctionDecl *FD;
11255 CallExpr *CE;
11256
11257 public:
11258 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11259 : FD(FD), CE(CE) { }
11260
11261 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11262 if (!FD) {
11263 S.Diag(Loc, diag::err_call_incomplete_return)
11264 << T << CE->getSourceRange();
11265 return;
11266 }
11267
11268 S.Diag(Loc, diag::err_call_function_incomplete_return)
11269 << CE->getSourceRange() << FD->getDeclName() << T;
11270 S.Diag(FD->getLocation(),
11271 diag::note_function_with_incomplete_return_type_declared_here)
11272 << FD->getDeclName();
11273 }
11274 } Diagnoser(FD, CE);
11275
11276 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011277 return true;
11278
11279 return false;
11280}
11281
Douglas Gregor92c3a042011-01-19 16:50:08 +000011282// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011283// will prevent this condition from triggering, which is what we want.
11284void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11285 SourceLocation Loc;
11286
John McCalla52ef082009-11-11 02:41:58 +000011287 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011288 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011289
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011290 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011291 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011292 return;
11293
Douglas Gregor92c3a042011-01-19 16:50:08 +000011294 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11295
John McCallc8d8ac52009-11-12 00:06:05 +000011296 // Greylist some idioms by putting them into a warning subcategory.
11297 if (ObjCMessageExpr *ME
11298 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11299 Selector Sel = ME->getSelector();
11300
John McCallc8d8ac52009-11-12 00:06:05 +000011301 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011302 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011303 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11304
11305 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011306 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011307 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11308 }
John McCalla52ef082009-11-11 02:41:58 +000011309
John McCall5a881bb2009-10-12 21:59:07 +000011310 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011311 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011312 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011313 return;
11314
Douglas Gregor92c3a042011-01-19 16:50:08 +000011315 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011316 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011317 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11318 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11319 else {
John McCall5a881bb2009-10-12 21:59:07 +000011320 // Not an assignment.
11321 return;
11322 }
11323
Douglas Gregor55b38842010-04-14 16:09:52 +000011324 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011325
Daniel Dunbar96a00142012-03-09 18:35:03 +000011326 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011327 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11328 Diag(Loc, diag::note_condition_assign_silence)
11329 << FixItHint::CreateInsertion(Open, "(")
11330 << FixItHint::CreateInsertion(Close, ")");
11331
Douglas Gregor92c3a042011-01-19 16:50:08 +000011332 if (IsOrAssign)
11333 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11334 << FixItHint::CreateReplacement(Loc, "!=");
11335 else
11336 Diag(Loc, diag::note_condition_assign_to_comparison)
11337 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011338}
11339
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011340/// \brief Redundant parentheses over an equality comparison can indicate
11341/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011342void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011343 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011344 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011345 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11346 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011347 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011348 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011349 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011350
Richard Trieuccd891a2011-09-09 01:45:06 +000011351 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011352
11353 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011354 if (opE->getOpcode() == BO_EQ &&
11355 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11356 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011357 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011358
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011359 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011360 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011361 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011362 << FixItHint::CreateRemoval(ParenERange.getBegin())
11363 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011364 Diag(Loc, diag::note_equality_comparison_to_assign)
11365 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011366 }
11367}
11368
John Wiegley429bb272011-04-08 18:41:53 +000011369ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011370 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011371 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11372 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011373
John McCall864c0412011-04-26 20:42:42 +000011374 ExprResult result = CheckPlaceholderExpr(E);
11375 if (result.isInvalid()) return ExprError();
11376 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011377
John McCall864c0412011-04-26 20:42:42 +000011378 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011379 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011380 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11381
John Wiegley429bb272011-04-08 18:41:53 +000011382 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11383 if (ERes.isInvalid())
11384 return ExprError();
11385 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011386
11387 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011388 if (!T->isScalarType()) { // C99 6.8.4.1p1
11389 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11390 << T << E->getSourceRange();
11391 return ExprError();
11392 }
John McCall5a881bb2009-10-12 21:59:07 +000011393 }
11394
John Wiegley429bb272011-04-08 18:41:53 +000011395 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011396}
Douglas Gregor586596f2010-05-06 17:25:47 +000011397
John McCall60d7b3a2010-08-24 06:29:42 +000011398ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011399 Expr *SubExpr) {
11400 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011401 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011402
Richard Trieuccd891a2011-09-09 01:45:06 +000011403 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011404}
John McCall2a984ca2010-10-12 00:20:44 +000011405
John McCall1de4d4e2011-04-07 08:22:57 +000011406namespace {
John McCall755d8492011-04-12 00:42:48 +000011407 /// A visitor for rebuilding a call to an __unknown_any expression
11408 /// to have an appropriate type.
11409 struct RebuildUnknownAnyFunction
11410 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11411
11412 Sema &S;
11413
11414 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11415
11416 ExprResult VisitStmt(Stmt *S) {
11417 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011418 }
11419
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011420 ExprResult VisitExpr(Expr *E) {
11421 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11422 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011423 return ExprError();
11424 }
11425
11426 /// Rebuild an expression which simply semantically wraps another
11427 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011428 template <class T> ExprResult rebuildSugarExpr(T *E) {
11429 ExprResult SubResult = Visit(E->getSubExpr());
11430 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011431
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011432 Expr *SubExpr = SubResult.take();
11433 E->setSubExpr(SubExpr);
11434 E->setType(SubExpr->getType());
11435 E->setValueKind(SubExpr->getValueKind());
11436 assert(E->getObjectKind() == OK_Ordinary);
11437 return E;
John McCall755d8492011-04-12 00:42:48 +000011438 }
11439
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011440 ExprResult VisitParenExpr(ParenExpr *E) {
11441 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011442 }
11443
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011444 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11445 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011446 }
11447
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011448 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11449 ExprResult SubResult = Visit(E->getSubExpr());
11450 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011451
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011452 Expr *SubExpr = SubResult.take();
11453 E->setSubExpr(SubExpr);
11454 E->setType(S.Context.getPointerType(SubExpr->getType()));
11455 assert(E->getValueKind() == VK_RValue);
11456 assert(E->getObjectKind() == OK_Ordinary);
11457 return E;
John McCall755d8492011-04-12 00:42:48 +000011458 }
11459
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011460 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11461 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011462
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011463 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011464
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011465 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011466 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011467 !(isa<CXXMethodDecl>(VD) &&
11468 cast<CXXMethodDecl>(VD)->isInstance()))
11469 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011470
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011471 return E;
John McCall755d8492011-04-12 00:42:48 +000011472 }
11473
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011474 ExprResult VisitMemberExpr(MemberExpr *E) {
11475 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011476 }
11477
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011478 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11479 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011480 }
11481 };
11482}
11483
11484/// Given a function expression of unknown-any type, try to rebuild it
11485/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011486static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11487 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11488 if (Result.isInvalid()) return ExprError();
11489 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011490}
11491
11492namespace {
John McCall379b5152011-04-11 07:02:50 +000011493 /// A visitor for rebuilding an expression of type __unknown_anytype
11494 /// into one which resolves the type directly on the referring
11495 /// expression. Strict preservation of the original source
11496 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011497 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011498 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011499
11500 Sema &S;
11501
11502 /// The current destination type.
11503 QualType DestType;
11504
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011505 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11506 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011507
John McCalla5fc4722011-04-09 22:50:59 +000011508 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011509 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011510 }
11511
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011512 ExprResult VisitExpr(Expr *E) {
11513 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11514 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011515 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011516 }
11517
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011518 ExprResult VisitCallExpr(CallExpr *E);
11519 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011520
John McCalla5fc4722011-04-09 22:50:59 +000011521 /// Rebuild an expression which simply semantically wraps another
11522 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011523 template <class T> ExprResult rebuildSugarExpr(T *E) {
11524 ExprResult SubResult = Visit(E->getSubExpr());
11525 if (SubResult.isInvalid()) return ExprError();
11526 Expr *SubExpr = SubResult.take();
11527 E->setSubExpr(SubExpr);
11528 E->setType(SubExpr->getType());
11529 E->setValueKind(SubExpr->getValueKind());
11530 assert(E->getObjectKind() == OK_Ordinary);
11531 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011532 }
John McCall1de4d4e2011-04-07 08:22:57 +000011533
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011534 ExprResult VisitParenExpr(ParenExpr *E) {
11535 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011536 }
11537
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011538 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11539 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011540 }
11541
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011542 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11543 const PointerType *Ptr = DestType->getAs<PointerType>();
11544 if (!Ptr) {
11545 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11546 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011547 return ExprError();
11548 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011549 assert(E->getValueKind() == VK_RValue);
11550 assert(E->getObjectKind() == OK_Ordinary);
11551 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011552
11553 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011554 DestType = Ptr->getPointeeType();
11555 ExprResult SubResult = Visit(E->getSubExpr());
11556 if (SubResult.isInvalid()) return ExprError();
11557 E->setSubExpr(SubResult.take());
11558 return E;
John McCall755d8492011-04-12 00:42:48 +000011559 }
11560
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011561 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011562
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011563 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011564
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011565 ExprResult VisitMemberExpr(MemberExpr *E) {
11566 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011567 }
John McCalla5fc4722011-04-09 22:50:59 +000011568
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011569 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11570 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011571 }
11572 };
11573}
11574
John McCall379b5152011-04-11 07:02:50 +000011575/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011576ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11577 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011578
11579 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011580 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011581 FK_FunctionPointer,
11582 FK_BlockPointer
11583 };
11584
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011585 FnKind Kind;
11586 QualType CalleeType = CalleeExpr->getType();
11587 if (CalleeType == S.Context.BoundMemberTy) {
11588 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11589 Kind = FK_MemberFunction;
11590 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11591 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11592 CalleeType = Ptr->getPointeeType();
11593 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011594 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011595 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11596 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011597 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011598 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011599
11600 // Verify that this is a legal result type of a function.
11601 if (DestType->isArrayType() || DestType->isFunctionType()) {
11602 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011603 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011604 diagID = diag::err_block_returning_array_function;
11605
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011606 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011607 << DestType->isFunctionType() << DestType;
11608 return ExprError();
11609 }
11610
11611 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011612 E->setType(DestType.getNonLValueExprType(S.Context));
11613 E->setValueKind(Expr::getValueKindForType(DestType));
11614 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011615
11616 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011617 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011618 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011619 Proto->arg_type_begin(),
11620 Proto->getNumArgs(),
11621 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011622 else
11623 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011624 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011625
11626 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011627 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011628 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011629 // Nothing to do.
11630 break;
11631
11632 case FK_FunctionPointer:
11633 DestType = S.Context.getPointerType(DestType);
11634 break;
11635
11636 case FK_BlockPointer:
11637 DestType = S.Context.getBlockPointerType(DestType);
11638 break;
11639 }
11640
11641 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011642 ExprResult CalleeResult = Visit(CalleeExpr);
11643 if (!CalleeResult.isUsable()) return ExprError();
11644 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011645
11646 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011647 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011648}
11649
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011650ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011651 // Verify that this is a legal result type of a call.
11652 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011653 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011654 << DestType->isFunctionType() << DestType;
11655 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011656 }
11657
John McCall48218c62011-07-13 17:56:40 +000011658 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011659 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11660 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11661 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011662 }
John McCall755d8492011-04-12 00:42:48 +000011663
John McCall379b5152011-04-11 07:02:50 +000011664 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011665 E->setType(DestType.getNonReferenceType());
11666 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011667
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011668 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011669}
11670
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011671ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011672 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011673 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011674 assert(E->getValueKind() == VK_RValue);
11675 assert(E->getObjectKind() == OK_Ordinary);
11676
11677 E->setType(DestType);
11678
11679 // Rebuild the sub-expression as the pointee (function) type.
11680 DestType = DestType->castAs<PointerType>()->getPointeeType();
11681
11682 ExprResult Result = Visit(E->getSubExpr());
11683 if (!Result.isUsable()) return ExprError();
11684
11685 E->setSubExpr(Result.take());
11686 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011687 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011688 assert(E->getValueKind() == VK_RValue);
11689 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011690
Sean Callanance9c8312012-03-06 21:34:12 +000011691 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011692
Sean Callanance9c8312012-03-06 21:34:12 +000011693 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011694
Sean Callanance9c8312012-03-06 21:34:12 +000011695 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11696 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011697
Sean Callanance9c8312012-03-06 21:34:12 +000011698 ExprResult Result = Visit(E->getSubExpr());
11699 if (!Result.isUsable()) return ExprError();
11700
11701 E->setSubExpr(Result.take());
11702 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011703 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011704 llvm_unreachable("Unhandled cast type!");
11705 }
John McCall379b5152011-04-11 07:02:50 +000011706}
11707
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011708ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11709 ExprValueKind ValueKind = VK_LValue;
11710 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011711
11712 // We know how to make this work for certain kinds of decls:
11713
11714 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011715 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11716 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11717 DestType = Ptr->getPointeeType();
11718 ExprResult Result = resolveDecl(E, VD);
11719 if (Result.isInvalid()) return ExprError();
11720 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011721 CK_FunctionToPointerDecay, VK_RValue);
11722 }
11723
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011724 if (!Type->isFunctionType()) {
11725 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11726 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011727 return ExprError();
11728 }
John McCall379b5152011-04-11 07:02:50 +000011729
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011730 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11731 if (MD->isInstance()) {
11732 ValueKind = VK_RValue;
11733 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011734 }
11735
John McCall379b5152011-04-11 07:02:50 +000011736 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011737 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011738 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011739
11740 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011741 } else if (isa<VarDecl>(VD)) {
11742 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11743 Type = RefTy->getPointeeType();
11744 } else if (Type->isFunctionType()) {
11745 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11746 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011747 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011748 }
11749
11750 // - nothing else
11751 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011752 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11753 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011754 return ExprError();
11755 }
11756
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011757 VD->setType(DestType);
11758 E->setType(Type);
11759 E->setValueKind(ValueKind);
11760 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011761}
11762
John McCall1de4d4e2011-04-07 08:22:57 +000011763/// Check a cast of an unknown-any type. We intentionally only
11764/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011765ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11766 Expr *CastExpr, CastKind &CastKind,
11767 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011768 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011769 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011770 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011771
Richard Trieuccd891a2011-09-09 01:45:06 +000011772 CastExpr = result.take();
11773 VK = CastExpr->getValueKind();
11774 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011775
Richard Trieuccd891a2011-09-09 01:45:06 +000011776 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011777}
11778
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011779ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11780 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11781}
11782
Richard Trieuccd891a2011-09-09 01:45:06 +000011783static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11784 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011785 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011786 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011787 E = E->IgnoreParenImpCasts();
11788 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11789 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011790 diagID = diag::err_uncasted_call_of_unknown_any;
11791 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011792 break;
John McCall379b5152011-04-11 07:02:50 +000011793 }
John McCall1de4d4e2011-04-07 08:22:57 +000011794 }
11795
John McCall379b5152011-04-11 07:02:50 +000011796 SourceLocation loc;
11797 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011798 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011799 loc = ref->getLocation();
11800 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011801 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011802 loc = mem->getMemberLoc();
11803 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011804 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011805 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011806 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011807 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011808 if (!d) {
11809 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11810 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11811 << orig->getSourceRange();
11812 return ExprError();
11813 }
John McCall379b5152011-04-11 07:02:50 +000011814 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011815 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11816 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011817 return ExprError();
11818 }
11819
11820 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011821
11822 // Never recoverable.
11823 return ExprError();
11824}
11825
John McCall2a984ca2010-10-12 00:20:44 +000011826/// Check for operands with placeholder types and complain if found.
11827/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011828ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011829 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11830 if (!placeholderType) return Owned(E);
11831
11832 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011833
John McCall1de4d4e2011-04-07 08:22:57 +000011834 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011835 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011836 // Try to resolve a single function template specialization.
11837 // This is obligatory.
11838 ExprResult result = Owned(E);
11839 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11840 return result;
11841
11842 // If that failed, try to recover with a call.
11843 } else {
11844 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11845 /*complain*/ true);
11846 return result;
11847 }
11848 }
John McCall1de4d4e2011-04-07 08:22:57 +000011849
John McCall864c0412011-04-26 20:42:42 +000011850 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011851 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011852 ExprResult result = Owned(E);
11853 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11854 /*complain*/ true);
11855 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011856 }
11857
11858 // ARC unbridged casts.
11859 case BuiltinType::ARCUnbridgedCast: {
11860 Expr *realCast = stripARCUnbridgedCast(E);
11861 diagnoseARCUnbridgedCast(realCast);
11862 return Owned(realCast);
11863 }
John McCall864c0412011-04-26 20:42:42 +000011864
John McCall1de4d4e2011-04-07 08:22:57 +000011865 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011866 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011867 return diagnoseUnknownAnyExpr(*this, E);
11868
John McCall3c3b7f92011-10-25 17:37:35 +000011869 // Pseudo-objects.
11870 case BuiltinType::PseudoObject:
11871 return checkPseudoObjectRValue(E);
11872
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011873 case BuiltinType::BuiltinFn:
11874 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11875 return ExprError();
11876
John McCalle0a22d02011-10-18 21:02:43 +000011877 // Everything else should be impossible.
11878#define BUILTIN_TYPE(Id, SingletonId) \
11879 case BuiltinType::Id:
11880#define PLACEHOLDER_TYPE(Id, SingletonId)
11881#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011882 break;
11883 }
11884
11885 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011886}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011887
Richard Trieuccd891a2011-09-09 01:45:06 +000011888bool Sema::CheckCaseExpression(Expr *E) {
11889 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011890 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011891 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11892 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011893 return false;
11894}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011895
11896/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11897ExprResult
11898Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11899 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11900 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000011901 QualType BoolT = Context.ObjCBuiltinBoolTy;
11902 if (!Context.getBOOLDecl()) {
11903 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11904 Sema::LookupOrdinaryName);
11905 if (LookupName(Result, getCurScope())) {
11906 NamedDecl *ND = Result.getFoundDecl();
11907 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11908 Context.setBOOLDecl(TD);
11909 }
11910 }
11911 if (Context.getBOOLDecl())
11912 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011913 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011914 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011915}