blob: 838d33150fcfc31e0edf8507b92bee1fc1e9c4f0 [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 }
Jordan Rose04bec392012-10-10 16:42:54 +000090
Fariborz Jahanianfd090882012-09-21 20:46:37 +000091 const ObjCPropertyDecl *ObjCPDecl = 0;
Jordan Rose04bec392012-10-10 16:42:54 +000092 if (Result == AR_Deprecated || Result == AR_Unavailable) {
93 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
94 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
95 AvailabilityResult PDeclResult = PD->getAvailability(0);
96 if (PDeclResult == Result)
97 ObjCPDecl = PD;
98 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +000099 }
Jordan Rose04bec392012-10-10 16:42:54 +0000100 }
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +0000101
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 switch (Result) {
103 case AR_Available:
104 case AR_NotYetIntroduced:
105 break;
106
107 case AR_Deprecated:
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000108 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000109 break;
110
111 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000112 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000113 if (Message.empty()) {
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000114 if (!UnknownObjCClass) {
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000115 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000116 if (ObjCPDecl)
117 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
118 << ObjCPDecl->getDeclName() << 1;
119 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000120 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000121 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000122 << D->getDeclName();
123 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000124 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000125 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000126 << D->getDeclName() << Message;
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000127 S.Diag(D->getLocation(), diag::note_unavailable_here)
128 << isa<FunctionDecl>(D) << false;
129 if (ObjCPDecl)
130 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
131 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000132 }
133 break;
134 }
135 return Result;
136}
137
Richard Smith6c4c36c2012-03-30 20:53:28 +0000138/// \brief Emit a note explaining that this function is deleted or unavailable.
139void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
141
Richard Smith5bdaac52012-04-02 20:59:25 +0000142 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
143 // If the method was explicitly defaulted, point at that declaration.
144 if (!Method->isImplicit())
145 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
146
147 // Try to diagnose why this special member function was implicitly
148 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000149 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000150 if (CSM != CXXInvalid)
151 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
152
153 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000154 }
155
156 Diag(Decl->getLocation(), diag::note_unavailable_here)
157 << 1 << Decl->isDeleted();
158}
159
Jordan Rose0eb3f452012-06-18 22:09:19 +0000160/// \brief Determine whether a FunctionDecl was ever declared with an
161/// explicit storage class.
162static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
163 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
164 E = D->redecls_end();
165 I != E; ++I) {
166 if (I->getStorageClassAsWritten() != SC_None)
167 return true;
168 }
169 return false;
170}
171
172/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000173/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000175/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000176/// in many cases it will not behave correctly. This is not enabled in C++ mode
177/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
178/// and so while there may still be user mistakes, most of the time we can't
179/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000180static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
181 const NamedDecl *D,
182 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000183 // This is disabled under C++; there are too many ways for this to fire in
184 // contexts where the warning is a false positive, or where it is technically
185 // correct but benign.
186 if (S.getLangOpts().CPlusPlus)
187 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000188
189 // Check if this is an inlined function or method.
190 FunctionDecl *Current = S.getCurFunctionDecl();
191 if (!Current)
192 return;
193 if (!Current->isInlined())
194 return;
195 if (Current->getLinkage() != ExternalLinkage)
196 return;
197
198 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000199 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000200 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000201
Jordan Rose05233272012-06-21 05:54:50 +0000202 // Downgrade from ExtWarn to Extension if
203 // (1) the supposedly external inline function is in the main file,
204 // and probably won't be included anywhere else.
205 // (2) the thing we're referencing is a pure function.
206 // (3) the thing we're referencing is another inline function.
207 // This last can give us false negatives, but it's better than warning on
208 // wrappers for simple C library functions.
209 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
210 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
211 if (!DowngradeWarning && UsedFn)
212 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
213
214 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
215 : diag::warn_internal_in_extern_inline)
216 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000217
218 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000219 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000220 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
221 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
222 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
223 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
224 }
225
226 S.Diag(D->getCanonicalDecl()->getLocation(),
227 diag::note_internal_decl_declared_here)
228 << D;
229}
230
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000231/// \brief Determine whether the use of this declaration is valid, and
232/// emit any corresponding diagnostics.
233///
234/// This routine diagnoses various problems with referencing
235/// declarations that can occur when using a declaration. For example,
236/// it might warn if a deprecated or unavailable declaration is being
237/// used, or produce an error (and return true) if a C++0x deleted
238/// function is being used.
239///
240/// \returns true if there was an error (this declaration cannot be
241/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000242///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000243bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000244 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000245 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000246 // If there were any diagnostics suppressed by template argument deduction,
247 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000249 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
250 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000251 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000252 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
253 Diag(Suppressed[I].first, Suppressed[I].second);
254
255 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000256 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000257 // entry from the table, because we want to avoid ever emitting these
258 // diagnostics again.
259 Suppressed.clear();
260 }
261 }
262
Richard Smith34b41d92011-02-20 03:19:35 +0000263 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000264 if (ParsingInitForAutoVars.count(D)) {
265 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
266 << D->getDeclName();
267 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000268 }
269
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000270 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000272 if (FD->isDeleted()) {
273 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000274 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000275 return true;
276 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000277 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000278 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000279
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000280 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000281
Jordan Rose0eb3f452012-06-18 22:09:19 +0000282 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000283
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000284 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000285}
286
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000287/// \brief Retrieve the message suffix that should be added to a
288/// diagnostic complaining about the given function being deleted or
289/// unavailable.
290std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
291 // FIXME: C++0x implicitly-deleted special member functions could be
292 // detected here so that we could improve diagnostics to say, e.g.,
293 // "base class 'A' had a deleted copy constructor".
294 if (FD->isDeleted())
295 return std::string();
296
297 std::string Message;
298 if (FD->getAvailability(&Message))
299 return ": " + Message;
300
301 return std::string();
302}
303
John McCall3323fad2011-09-09 07:56:05 +0000304/// DiagnoseSentinelCalls - This routine checks whether a call or
305/// message-send is to a declaration with the sentinel attribute, and
306/// if so, it checks that the requirements of the sentinel are
307/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000308void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000309 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000310 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000311 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000312 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000313
John McCall3323fad2011-09-09 07:56:05 +0000314 // The number of formal parameters of the declaration.
315 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
John McCall3323fad2011-09-09 07:56:05 +0000317 // The kind of declaration. This is also an index into a %select in
318 // the diagnostic.
319 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
320
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000321 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000322 numFormalParams = MD->param_size();
323 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000324 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000325 numFormalParams = FD->param_size();
326 calleeType = CT_Function;
327 } else if (isa<VarDecl>(D)) {
328 QualType type = cast<ValueDecl>(D)->getType();
329 const FunctionType *fn = 0;
330 if (const PointerType *ptr = type->getAs<PointerType>()) {
331 fn = ptr->getPointeeType()->getAs<FunctionType>();
332 if (!fn) return;
333 calleeType = CT_Function;
334 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
335 fn = ptr->getPointeeType()->castAs<FunctionType>();
336 calleeType = CT_Block;
337 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000338 return;
John McCall3323fad2011-09-09 07:56:05 +0000339 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000340
John McCall3323fad2011-09-09 07:56:05 +0000341 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
342 numFormalParams = proto->getNumArgs();
343 } else {
344 numFormalParams = 0;
345 }
346 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000347 return;
348 }
John McCall3323fad2011-09-09 07:56:05 +0000349
350 // "nullPos" is the number of formal parameters at the end which
351 // effectively count as part of the variadic arguments. This is
352 // useful if you would prefer to not have *any* formal parameters,
353 // but the language forces you to have at least one.
354 unsigned nullPos = attr->getNullPos();
355 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
356 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
357
358 // The number of arguments which should follow the sentinel.
359 unsigned numArgsAfterSentinel = attr->getSentinel();
360
361 // If there aren't enough arguments for all the formal parameters,
362 // the sentinel, and the args after the sentinel, complain.
363 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000364 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000365 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000366 return;
367 }
John McCall3323fad2011-09-09 07:56:05 +0000368
369 // Otherwise, find the sentinel expression.
370 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000371 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000372 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000373 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000374
John McCall3323fad2011-09-09 07:56:05 +0000375 // Pick a reasonable string to insert. Optimistically use 'nil' or
376 // 'NULL' if those are actually defined in the context. Only use
377 // 'nil' for ObjC methods, where it's much more likely that the
378 // variadic arguments form a list of object pointers.
379 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000380 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
381 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000382 if (calleeType == CT_Method &&
383 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000384 NullValue = "nil";
385 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
386 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000387 else
John McCall3323fad2011-09-09 07:56:05 +0000388 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000389
390 if (MissingNilLoc.isInvalid())
391 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
392 else
393 Diag(MissingNilLoc, diag::warn_missing_sentinel)
394 << calleeType
395 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000396 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000397}
398
Richard Trieuccd891a2011-09-09 01:45:06 +0000399SourceRange Sema::getExprRange(Expr *E) const {
400 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000401}
402
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403//===----------------------------------------------------------------------===//
404// Standard Promotions and Conversions
405//===----------------------------------------------------------------------===//
406
Chris Lattnere7a2e912008-07-25 21:10:04 +0000407/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000408ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000409 // Handle any placeholder expressions which made it here.
410 if (E->getType()->isPlaceholderType()) {
411 ExprResult result = CheckPlaceholderExpr(E);
412 if (result.isInvalid()) return ExprError();
413 E = result.take();
414 }
415
Chris Lattnere7a2e912008-07-25 21:10:04 +0000416 QualType Ty = E->getType();
417 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
418
Chris Lattnere7a2e912008-07-25 21:10:04 +0000419 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000420 E = ImpCastExprToType(E, Context.getPointerType(Ty),
421 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000422 else if (Ty->isArrayType()) {
423 // In C90 mode, arrays only promote to pointers if the array expression is
424 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
425 // type 'array of type' is converted to an expression that has type 'pointer
426 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
427 // that has type 'array of type' ...". The relevant change is "an lvalue"
428 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000429 //
430 // C++ 4.2p1:
431 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
432 // T" can be converted to an rvalue of type "pointer to T".
433 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000434 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000435 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
436 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000437 }
John Wiegley429bb272011-04-08 18:41:53 +0000438 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000439}
440
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000441static void CheckForNullPointerDereference(Sema &S, Expr *E) {
442 // Check to see if we are dereferencing a null pointer. If so,
443 // and if not volatile-qualified, this is undefined behavior that the
444 // optimizer will delete, so warn about it. People sometimes try to use this
445 // to get a deterministic trap and are surprised by clang's behavior. This
446 // only handles the pattern "*null", which is a very syntactic check.
447 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
448 if (UO->getOpcode() == UO_Deref &&
449 UO->getSubExpr()->IgnoreParenCasts()->
450 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
451 !UO->getType().isVolatileQualified()) {
452 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
453 S.PDiag(diag::warn_indirection_through_null)
454 << UO->getSubExpr()->getSourceRange());
455 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
456 S.PDiag(diag::note_indirection_through_null));
457 }
458}
459
John Wiegley429bb272011-04-08 18:41:53 +0000460ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000461 // Handle any placeholder expressions which made it here.
462 if (E->getType()->isPlaceholderType()) {
463 ExprResult result = CheckPlaceholderExpr(E);
464 if (result.isInvalid()) return ExprError();
465 E = result.take();
466 }
467
John McCall0ae287a2010-12-01 04:43:34 +0000468 // C++ [conv.lval]p1:
469 // A glvalue of a non-function, non-array type T can be
470 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000471 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000472
John McCall409fa9a2010-12-06 20:48:59 +0000473 QualType T = E->getType();
474 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000475
John McCall409fa9a2010-12-06 20:48:59 +0000476 // We don't want to throw lvalue-to-rvalue casts on top of
477 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000478 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000479 (E->getType() == Context.OverloadTy ||
480 T->isDependentType() ||
481 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000482 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000483
484 // The C standard is actually really unclear on this point, and
485 // DR106 tells us what the result should be but not why. It's
486 // generally best to say that void types just doesn't undergo
487 // lvalue-to-rvalue at all. Note that expressions of unqualified
488 // 'void' type are never l-values, but qualified void can be.
489 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000490 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000491
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000492 CheckForNullPointerDereference(*this, E);
493
John McCall409fa9a2010-12-06 20:48:59 +0000494 // C++ [conv.lval]p1:
495 // [...] If T is a non-class type, the type of the prvalue is the
496 // cv-unqualified version of T. Otherwise, the type of the
497 // rvalue is T.
498 //
499 // C99 6.3.2.1p2:
500 // If the lvalue has qualified type, the value has the unqualified
501 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000502 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000503 if (T.hasQualifiers())
504 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000505
Eli Friedmand2cce132012-02-02 23:15:15 +0000506 UpdateMarkingForLValueToRValue(E);
507
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000508 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
509 E, 0, VK_RValue));
510
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000511 // C11 6.3.2.1p2:
512 // ... if the lvalue has atomic type, the value has the non-atomic version
513 // of the type of the lvalue ...
514 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
515 T = Atomic->getValueType().getUnqualifiedType();
516 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
517 Res.get(), 0, VK_RValue));
518 }
519
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000520 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000521}
522
John Wiegley429bb272011-04-08 18:41:53 +0000523ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
524 ExprResult Res = DefaultFunctionArrayConversion(E);
525 if (Res.isInvalid())
526 return ExprError();
527 Res = DefaultLvalueConversion(Res.take());
528 if (Res.isInvalid())
529 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000530 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000531}
532
533
Chris Lattnere7a2e912008-07-25 21:10:04 +0000534/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000535/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000536/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000537/// apply if the array is an argument to the sizeof or address (&) operators.
538/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000539ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000540 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000541 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
542 if (Res.isInvalid())
543 return Owned(E);
544 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000545
John McCall0ae287a2010-12-01 04:43:34 +0000546 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000547 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000548
549 // Half FP is a bit different: it's a storage-only type, meaning that any
550 // "use" of it should be promoted to float.
551 if (Ty->isHalfType())
552 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
553
John McCall0ae287a2010-12-01 04:43:34 +0000554 // Try to perform integral promotions if the object has a theoretically
555 // promotable type.
556 if (Ty->isIntegralOrUnscopedEnumerationType()) {
557 // C99 6.3.1.1p2:
558 //
559 // The following may be used in an expression wherever an int or
560 // unsigned int may be used:
561 // - an object or expression with an integer type whose integer
562 // conversion rank is less than or equal to the rank of int
563 // and unsigned int.
564 // - A bit-field of type _Bool, int, signed int, or unsigned int.
565 //
566 // If an int can represent all values of the original type, the
567 // value is converted to an int; otherwise, it is converted to an
568 // unsigned int. These are called the integer promotions. All
569 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000570
John McCall0ae287a2010-12-01 04:43:34 +0000571 QualType PTy = Context.isPromotableBitField(E);
572 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000573 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
574 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000575 }
576 if (Ty->isPromotableIntegerType()) {
577 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000578 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
579 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000580 }
Eli Friedman04e83572009-08-20 04:21:42 +0000581 }
John Wiegley429bb272011-04-08 18:41:53 +0000582 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000583}
584
Chris Lattner05faf172008-07-25 22:25:12 +0000585/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000586/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000587/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000588ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
589 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000590 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000591
John Wiegley429bb272011-04-08 18:41:53 +0000592 ExprResult Res = UsualUnaryConversions(E);
593 if (Res.isInvalid())
594 return Owned(E);
595 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000596
Chris Lattner05faf172008-07-25 22:25:12 +0000597 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000598 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000599 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
600
John McCall96a914a2011-08-27 22:06:17 +0000601 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000602 // promotion, even on class types, but note:
603 // C++11 [conv.lval]p2:
604 // When an lvalue-to-rvalue conversion occurs in an unevaluated
605 // operand or a subexpression thereof the value contained in the
606 // referenced object is not accessed. Otherwise, if the glvalue
607 // has a class type, the conversion copy-initializes a temporary
608 // of type T from the glvalue and the result of the conversion
609 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000610 // FIXME: add some way to gate this entire thing for correctness in
611 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000612 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000613 ExprResult Temp = PerformCopyInitialization(
614 InitializedEntity::InitializeTemporary(E->getType()),
615 E->getExprLoc(),
616 Owned(E));
617 if (Temp.isInvalid())
618 return ExprError();
619 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000620 }
621
John Wiegley429bb272011-04-08 18:41:53 +0000622 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000623}
624
Richard Smith831421f2012-06-25 20:30:08 +0000625/// Determine the degree of POD-ness for an expression.
626/// Incomplete types are considered POD, since this check can be performed
627/// when we're in an unevaluated context.
628Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000629 if (Ty->isIncompleteType()) {
630 if (Ty->isObjCObjectType())
631 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000632 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000633 }
634
635 if (Ty.isCXX98PODType(Context))
636 return VAK_Valid;
637
Richard Smith831421f2012-06-25 20:30:08 +0000638 // C++0x [expr.call]p7:
639 // Passing a potentially-evaluated argument of class type (Clause 9)
640 // having a non-trivial copy constructor, a non-trivial move constructor,
641 // or a non-trivial destructor, with no corresponding parameter,
642 // is conditionally-supported with implementation-defined semantics.
Richard Smith831421f2012-06-25 20:30:08 +0000643 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
644 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
645 if (Record->hasTrivialCopyConstructor() &&
646 Record->hasTrivialMoveConstructor() &&
647 Record->hasTrivialDestructor())
648 return VAK_ValidInCXX11;
649
650 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
651 return VAK_Valid;
652 return VAK_Invalid;
653}
654
655bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
656 // Don't allow one to pass an Objective-C interface to a vararg.
657 const QualType & Ty = E->getType();
658
659 // Complain about passing non-POD types through varargs.
660 switch (isValidVarArgType(Ty)) {
661 case VAK_Valid:
662 break;
663 case VAK_ValidInCXX11:
664 DiagRuntimeBehavior(E->getLocStart(), 0,
665 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
666 << E->getType() << CT);
667 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000668 case VAK_Invalid: {
669 if (Ty->isObjCObjectType())
670 return DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
672 << Ty << CT);
673
Richard Smith831421f2012-06-25 20:30:08 +0000674 return DiagRuntimeBehavior(E->getLocStart(), 0,
675 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
676 << getLangOpts().CPlusPlus0x << Ty << CT);
677 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000678 }
Richard Smith831421f2012-06-25 20:30:08 +0000679 // c++ rules are enforced elsewhere.
680 return false;
681}
682
Chris Lattner312531a2009-04-12 08:11:20 +0000683/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000684/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000685ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000686 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000687 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000688 // Strip the unbridged-cast placeholder expression off, if applicable.
689 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
690 (CT == VariadicMethod ||
691 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
692 E = stripARCUnbridgedCast(E);
693
694 // Otherwise, do normal placeholder checking.
695 } else {
696 ExprResult ExprRes = CheckPlaceholderExpr(E);
697 if (ExprRes.isInvalid())
698 return ExprError();
699 E = ExprRes.take();
700 }
701 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000702
John McCall5acb0c92011-10-17 18:40:02 +0000703 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000704 if (ExprRes.isInvalid())
705 return ExprError();
706 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Richard Smith831421f2012-06-25 20:30:08 +0000708 // Diagnostics regarding non-POD argument types are
709 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000710 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000711 // Turn this into a trap.
712 CXXScopeSpec SS;
713 SourceLocation TemplateKWLoc;
714 UnqualifiedId Name;
715 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
716 E->getLocStart());
717 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
718 Name, true, false);
719 if (TrapFn.isInvalid())
720 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000721
Richard Smith831421f2012-06-25 20:30:08 +0000722 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
723 E->getLocStart(), MultiExprArg(),
724 E->getLocEnd());
725 if (Call.isInvalid())
726 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000727
Richard Smith831421f2012-06-25 20:30:08 +0000728 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
729 Call.get(), E);
730 if (Comma.isInvalid())
731 return ExprError();
732 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000733 }
Richard Smith831421f2012-06-25 20:30:08 +0000734
David Blaikie4e4d0842012-03-11 07:00:24 +0000735 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000736 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000737 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000738 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000739
John Wiegley429bb272011-04-08 18:41:53 +0000740 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000741}
742
Richard Trieu8289f492011-09-02 20:58:51 +0000743/// \brief Converts an integer to complex float type. Helper function of
744/// UsualArithmeticConversions()
745///
746/// \return false if the integer expression is an integer type and is
747/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000748static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
749 ExprResult &ComplexExpr,
750 QualType IntTy,
751 QualType ComplexTy,
752 bool SkipCast) {
753 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
754 if (SkipCast) return false;
755 if (IntTy->isIntegerType()) {
756 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
757 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
758 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000759 CK_FloatingRealToComplex);
760 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000761 assert(IntTy->isComplexIntegerType());
762 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000763 CK_IntegralComplexToFloatingComplex);
764 }
765 return false;
766}
767
768/// \brief Takes two complex float types and converts them to the same type.
769/// Helper function of UsualArithmeticConversions()
770static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000771handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
772 ExprResult &RHS, QualType LHSType,
773 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000774 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000775 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000776
777 if (order < 0) {
778 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
781 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000782 }
783 if (order > 0)
784 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000785 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
786 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000787}
788
789/// \brief Converts otherExpr to complex float and promotes complexExpr if
790/// necessary. Helper function of UsualArithmeticConversions()
791static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000792 ExprResult &ComplexExpr,
793 ExprResult &OtherExpr,
794 QualType ComplexTy,
795 QualType OtherTy,
796 bool ConvertComplexExpr,
797 bool ConvertOtherExpr) {
798 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000799
800 // If just the complexExpr is complex, the otherExpr needs to be converted,
801 // and the complexExpr might need to be promoted.
802 if (order > 0) { // complexExpr is wider
803 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000804 if (ConvertOtherExpr) {
805 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
806 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
807 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000808 CK_FloatingRealToComplex);
809 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000811 }
812
813 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000814 QualType result = (order == 0 ? ComplexTy :
815 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000816
817 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000818 if (ConvertOtherExpr)
819 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000820 CK_FloatingRealToComplex);
821
822 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000823 if (ConvertComplexExpr && order < 0)
824 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000825 CK_FloatingComplexCast);
826
827 return result;
828}
829
830/// \brief Handle arithmetic conversion with complex types. Helper function of
831/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000832static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
833 ExprResult &RHS, QualType LHSType,
834 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000835 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000836 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000837 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000838 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000839 return LHSType;
840 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000841 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000842 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000843
844 // This handles complex/complex, complex/float, or float/complex.
845 // When both operands are complex, the shorter operand is converted to the
846 // type of the longer, and that is the type of the result. This corresponds
847 // to what is done when combining two real floating-point operands.
848 // The fun begins when size promotion occur across type domains.
849 // From H&S 6.3.4: When one operand is complex and the other is a real
850 // floating-point type, the less precise type is converted, within it's
851 // real or complex domain, to the precision of the other type. For example,
852 // when combining a "long double" with a "double _Complex", the
853 // "double _Complex" is promoted to "long double _Complex".
854
Richard Trieucafd30b2011-09-06 18:25:09 +0000855 bool LHSComplexFloat = LHSType->isComplexType();
856 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000857
858 // If both are complex, just cast to the more precise type.
859 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000860 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
861 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000862 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000863
864 // If only one operand is complex, promote it if necessary and convert the
865 // other operand to complex.
866 if (LHSComplexFloat)
867 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000868 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000869 /*convertOtherExpr*/ true);
870
871 assert(RHSComplexFloat);
872 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000873 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000874 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000875}
876
877/// \brief Hande arithmetic conversion from integer to float. Helper function
878/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000879static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
880 ExprResult &IntExpr,
881 QualType FloatTy, QualType IntTy,
882 bool ConvertFloat, bool ConvertInt) {
883 if (IntTy->isIntegerType()) {
884 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000885 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000886 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000887 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000889 }
890
891 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000892 assert(IntTy->isComplexIntegerType());
893 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000894
895 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000896 if (ConvertInt)
897 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000898 CK_IntegralComplexToFloatingComplex);
899
900 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000901 if (ConvertFloat)
902 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000903 CK_FloatingRealToComplex);
904
905 return result;
906}
907
908/// \brief Handle arithmethic conversion with floating point types. Helper
909/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000910static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
911 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000912 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000913 bool LHSFloat = LHSType->isRealFloatingType();
914 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000915
916 // If we have two real floating types, convert the smaller operand
917 // to the bigger result.
918 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000919 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000920 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000921 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
922 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000923 }
924
925 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000926 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000927 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
928 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000929 }
930
931 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000932 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000933 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000934 /*convertInt=*/ true);
935 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000936 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000937 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000938 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000939}
940
941/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000942/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000943// FIXME: if the operands are (int, _Complex long), we currently
944// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000945static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
946 ExprResult &RHS, QualType LHSType,
947 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000948 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000949 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
950 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000951
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000952 if (LHSComplexInt && RHSComplexInt) {
953 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
954 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000955 assert(order && "inequal types with equal element ordering");
956 if (order > 0) {
957 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000958 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
959 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000960 }
961
Richard Trieuccd891a2011-09-09 01:45:06 +0000962 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000963 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
964 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000965 }
966
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000967 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000968 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000969 // FIXME: This needs to take integer ranks into account
970 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
971 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000972 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
973 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000974 }
975
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000976 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000977 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000978 // FIXME: This needs to take integer ranks into account
979 if (!IsCompAssign) {
980 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
981 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000982 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000983 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000984 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000985}
986
987/// \brief Handle integer arithmetic conversions. Helper function of
988/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000989static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
990 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000991 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000992 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000993 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
994 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
995 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
996 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000997 // Same signedness; use the higher-ranked type
998 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000999 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1000 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001001 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001002 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1003 return RHSType;
1004 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001005 // The unsigned type has greater than or equal rank to the
1006 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001007 if (RHSSigned) {
1008 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1009 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001010 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001011 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1012 return RHSType;
1013 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001014 // The two types are different widths; if we are here, that
1015 // means the signed type is larger than the unsigned type, so
1016 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001017 if (LHSSigned) {
1018 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1019 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001020 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001021 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1022 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001023 } else {
1024 // The signed type is higher-ranked than the unsigned type,
1025 // but isn't actually any bigger (like unsigned int and long
1026 // on most 32-bit systems). Use the unsigned type corresponding
1027 // to the signed type.
1028 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001029 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1030 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001031 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001032 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001033 return result;
1034 }
1035}
1036
Chris Lattnere7a2e912008-07-25 21:10:04 +00001037/// UsualArithmeticConversions - Performs various conversions that are common to
1038/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001039/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001040/// responsible for emitting appropriate error diagnostics.
1041/// FIXME: verify the conversion rules for "complex int" are consistent with
1042/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001043QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001044 bool IsCompAssign) {
1045 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001046 LHS = UsualUnaryConversions(LHS.take());
1047 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001048 return QualType();
1049 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001050
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001051 RHS = UsualUnaryConversions(RHS.take());
1052 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001053 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001054
Mike Stump1eb44332009-09-09 15:08:12 +00001055 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001056 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001057 QualType LHSType =
1058 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1059 QualType RHSType =
1060 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001061
Eli Friedman860a3192012-06-16 02:19:17 +00001062 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1063 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1064 LHSType = AtomicLHS->getValueType();
1065
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001066 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001067 if (LHSType == RHSType)
1068 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001069
1070 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1071 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001072 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001073 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001074
John McCallcf33b242010-11-13 08:17:45 +00001075 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001076 QualType LHSUnpromotedType = LHSType;
1077 if (LHSType->isPromotableIntegerType())
1078 LHSType = Context.getPromotedIntegerType(LHSType);
1079 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001080 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001081 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001082 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001083 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001084
John McCallcf33b242010-11-13 08:17:45 +00001085 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001086 if (LHSType == RHSType)
1087 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001088
1089 // At this point, we have two different arithmetic types.
1090
1091 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001092 if (LHSType->isComplexType() || RHSType->isComplexType())
1093 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001094 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001095
1096 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001097 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1098 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001099 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001100
1101 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001102 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001103 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001104 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001105
1106 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001107 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001108 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001109}
1110
Chris Lattnere7a2e912008-07-25 21:10:04 +00001111//===----------------------------------------------------------------------===//
1112// Semantic Analysis for various Expression Types
1113//===----------------------------------------------------------------------===//
1114
1115
Peter Collingbournef111d932011-04-15 00:35:48 +00001116ExprResult
1117Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1118 SourceLocation DefaultLoc,
1119 SourceLocation RParenLoc,
1120 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001121 MultiTypeArg ArgTypes,
1122 MultiExprArg ArgExprs) {
1123 unsigned NumAssocs = ArgTypes.size();
1124 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001125
Benjamin Kramer5354e772012-08-23 23:38:35 +00001126 ParsedType *ParsedTypes = ArgTypes.data();
1127 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001128
1129 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1130 for (unsigned i = 0; i < NumAssocs; ++i) {
1131 if (ParsedTypes[i])
1132 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1133 else
1134 Types[i] = 0;
1135 }
1136
1137 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1138 ControllingExpr, Types, Exprs,
1139 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001140 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001141 return ER;
1142}
1143
1144ExprResult
1145Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1146 SourceLocation DefaultLoc,
1147 SourceLocation RParenLoc,
1148 Expr *ControllingExpr,
1149 TypeSourceInfo **Types,
1150 Expr **Exprs,
1151 unsigned NumAssocs) {
1152 bool TypeErrorFound = false,
1153 IsResultDependent = ControllingExpr->isTypeDependent(),
1154 ContainsUnexpandedParameterPack
1155 = ControllingExpr->containsUnexpandedParameterPack();
1156
1157 for (unsigned i = 0; i < NumAssocs; ++i) {
1158 if (Exprs[i]->containsUnexpandedParameterPack())
1159 ContainsUnexpandedParameterPack = true;
1160
1161 if (Types[i]) {
1162 if (Types[i]->getType()->containsUnexpandedParameterPack())
1163 ContainsUnexpandedParameterPack = true;
1164
1165 if (Types[i]->getType()->isDependentType()) {
1166 IsResultDependent = true;
1167 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001168 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001169 // complete object type other than a variably modified type."
1170 unsigned D = 0;
1171 if (Types[i]->getType()->isIncompleteType())
1172 D = diag::err_assoc_type_incomplete;
1173 else if (!Types[i]->getType()->isObjectType())
1174 D = diag::err_assoc_type_nonobject;
1175 else if (Types[i]->getType()->isVariablyModifiedType())
1176 D = diag::err_assoc_type_variably_modified;
1177
1178 if (D != 0) {
1179 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1180 << Types[i]->getTypeLoc().getSourceRange()
1181 << Types[i]->getType();
1182 TypeErrorFound = true;
1183 }
1184
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001185 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001186 // selection shall specify compatible types."
1187 for (unsigned j = i+1; j < NumAssocs; ++j)
1188 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1189 Context.typesAreCompatible(Types[i]->getType(),
1190 Types[j]->getType())) {
1191 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1192 diag::err_assoc_compatible_types)
1193 << Types[j]->getTypeLoc().getSourceRange()
1194 << Types[j]->getType()
1195 << Types[i]->getType();
1196 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1197 diag::note_compat_assoc)
1198 << Types[i]->getTypeLoc().getSourceRange()
1199 << Types[i]->getType();
1200 TypeErrorFound = true;
1201 }
1202 }
1203 }
1204 }
1205 if (TypeErrorFound)
1206 return ExprError();
1207
1208 // If we determined that the generic selection is result-dependent, don't
1209 // try to compute the result expression.
1210 if (IsResultDependent)
1211 return Owned(new (Context) GenericSelectionExpr(
1212 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001213 llvm::makeArrayRef(Types, NumAssocs),
1214 llvm::makeArrayRef(Exprs, NumAssocs),
1215 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbournef111d932011-04-15 00:35:48 +00001216
Chris Lattner5f9e2722011-07-23 10:55:15 +00001217 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001218 unsigned DefaultIndex = -1U;
1219 for (unsigned i = 0; i < NumAssocs; ++i) {
1220 if (!Types[i])
1221 DefaultIndex = i;
1222 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1223 Types[i]->getType()))
1224 CompatIndices.push_back(i);
1225 }
1226
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001227 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001228 // type compatible with at most one of the types named in its generic
1229 // association list."
1230 if (CompatIndices.size() > 1) {
1231 // We strip parens here because the controlling expression is typically
1232 // parenthesized in macro definitions.
1233 ControllingExpr = ControllingExpr->IgnoreParens();
1234 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1235 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1236 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001237 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001238 E = CompatIndices.end(); I != E; ++I) {
1239 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1240 diag::note_compat_assoc)
1241 << Types[*I]->getTypeLoc().getSourceRange()
1242 << Types[*I]->getType();
1243 }
1244 return ExprError();
1245 }
1246
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001247 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001248 // its controlling expression shall have type compatible with exactly one of
1249 // the types named in its generic association list."
1250 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1251 // We strip parens here because the controlling expression is typically
1252 // parenthesized in macro definitions.
1253 ControllingExpr = ControllingExpr->IgnoreParens();
1254 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1255 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1256 return ExprError();
1257 }
1258
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001259 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001260 // type name that is compatible with the type of the controlling expression,
1261 // then the result expression of the generic selection is the expression
1262 // in that generic association. Otherwise, the result expression of the
1263 // generic selection is the expression in the default generic association."
1264 unsigned ResultIndex =
1265 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1266
1267 return Owned(new (Context) GenericSelectionExpr(
1268 Context, KeyLoc, ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001269 llvm::makeArrayRef(Types, NumAssocs),
1270 llvm::makeArrayRef(Exprs, NumAssocs),
1271 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbournef111d932011-04-15 00:35:48 +00001272 ResultIndex));
1273}
1274
Richard Smithdd66be72012-03-08 01:34:56 +00001275/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1276/// location of the token and the offset of the ud-suffix within it.
1277static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1278 unsigned Offset) {
1279 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001280 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001281}
1282
Richard Smith36f5cfe2012-03-09 08:00:36 +00001283/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1284/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1285static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1286 IdentifierInfo *UDSuffix,
1287 SourceLocation UDSuffixLoc,
1288 ArrayRef<Expr*> Args,
1289 SourceLocation LitEndLoc) {
1290 assert(Args.size() <= 2 && "too many arguments for literal operator");
1291
1292 QualType ArgTy[2];
1293 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1294 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1295 if (ArgTy[ArgIdx]->isArrayType())
1296 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1297 }
1298
1299 DeclarationName OpName =
1300 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1301 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1302 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1303
1304 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1305 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1306 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1307 return ExprError();
1308
1309 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1310}
1311
Steve Narofff69936d2007-09-16 03:34:24 +00001312/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001313/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1314/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1315/// multiple tokens. However, the common case is that StringToks points to one
1316/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001317///
John McCall60d7b3a2010-08-24 06:29:42 +00001318ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001319Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1320 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 assert(NumStringToks && "Must have at least one string!");
1322
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001323 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001325 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Chris Lattner5f9e2722011-07-23 10:55:15 +00001327 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 for (unsigned i = 0; i != NumStringToks; ++i)
1329 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001330
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001331 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001332 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001333 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001334 else if (Literal.isUTF16())
1335 StrTy = Context.Char16Ty;
1336 else if (Literal.isUTF32())
1337 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001338 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001339 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001340
Douglas Gregor5cee1192011-07-27 05:40:30 +00001341 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1342 if (Literal.isWide())
1343 Kind = StringLiteral::Wide;
1344 else if (Literal.isUTF8())
1345 Kind = StringLiteral::UTF8;
1346 else if (Literal.isUTF16())
1347 Kind = StringLiteral::UTF16;
1348 else if (Literal.isUTF32())
1349 Kind = StringLiteral::UTF32;
1350
Douglas Gregor77a52232008-09-12 00:47:35 +00001351 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001352 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001353 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001354
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001355 // Get an array type for the string, according to C99 6.4.5. This includes
1356 // the nul terminator character as well as the string length for pascal
1357 // strings.
1358 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001359 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001360 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001363 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1364 Kind, Literal.Pascal, StrTy,
1365 &StringTokLocs[0],
1366 StringTokLocs.size());
1367 if (Literal.getUDSuffix().empty())
1368 return Owned(Lit);
1369
1370 // We're building a user-defined literal.
1371 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001372 SourceLocation UDSuffixLoc =
1373 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1374 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001375
Richard Smith36f5cfe2012-03-09 08:00:36 +00001376 // Make sure we're allowed user-defined literals here.
1377 if (!UDLScope)
1378 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1379
Richard Smith9fcce652012-03-07 08:35:16 +00001380 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1381 // operator "" X (str, len)
1382 QualType SizeType = Context.getSizeType();
1383 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1384 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1385 StringTokLocs[0]);
1386 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001387 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1388 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001389}
1390
John McCall60d7b3a2010-08-24 06:29:42 +00001391ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001392Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001393 SourceLocation Loc,
1394 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001395 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001396 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001397}
1398
John McCall76a40212011-02-09 01:13:10 +00001399/// BuildDeclRefExpr - Build an expression that references a
1400/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001401ExprResult
John McCall76a40212011-02-09 01:13:10 +00001402Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001403 const DeclarationNameInfo &NameInfo,
1404 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001405 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001406 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1407 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1408 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1409 CalleeTarget = IdentifyCUDATarget(Callee);
1410 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1411 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1412 << CalleeTarget << D->getIdentifier() << CallerTarget;
1413 Diag(D->getLocation(), diag::note_previous_decl)
1414 << D->getIdentifier();
1415 return ExprError();
1416 }
1417 }
1418
John McCallf4b88a42012-03-10 09:33:50 +00001419 bool refersToEnclosingScope =
1420 (CurContext != D->getDeclContext() &&
1421 D->getDeclContext()->isFunctionOrMethod());
1422
Eli Friedman5f2987c2012-02-02 03:46:19 +00001423 DeclRefExpr *E = DeclRefExpr::Create(Context,
1424 SS ? SS->getWithLocInContext(Context)
1425 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001426 SourceLocation(),
1427 D, refersToEnclosingScope,
1428 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Eli Friedman5f2987c2012-02-02 03:46:19 +00001430 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001431
Jordan Rose7a270482012-09-28 22:21:35 +00001432 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1433 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1434 DiagnosticsEngine::Level Level =
1435 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1436 E->getLocStart());
1437 if (Level != DiagnosticsEngine::Ignored)
1438 getCurFunction()->recordUseOfWeak(E);
1439 }
1440
John McCall7eb0a9e2010-11-24 05:12:34 +00001441 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001442 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1443 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001444 E->setObjectKind(OK_BitField);
1445
1446 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001447}
1448
Abramo Bagnara25777432010-08-11 22:01:17 +00001449/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001450/// possibly a list of template arguments.
1451///
1452/// If this produces template arguments, it is permitted to call
1453/// DecomposeTemplateName.
1454///
1455/// This actually loses a lot of source location information for
1456/// non-standard name kinds; we should consider preserving that in
1457/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001458void
1459Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1460 TemplateArgumentListInfo &Buffer,
1461 DeclarationNameInfo &NameInfo,
1462 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001463 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1464 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1465 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1466
Benjamin Kramer5354e772012-08-23 23:38:35 +00001467 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001468 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001469 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001470
John McCall2b5289b2010-08-23 07:28:44 +00001471 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001472 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001473 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001474 TemplateArgs = &Buffer;
1475 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001476 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001477 TemplateArgs = 0;
1478 }
1479}
1480
John McCall578b69b2009-12-16 08:11:27 +00001481/// Diagnose an empty lookup.
1482///
1483/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001484bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001485 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001486 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001487 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001488 DeclarationName Name = R.getLookupName();
1489
John McCall578b69b2009-12-16 08:11:27 +00001490 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001491 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001492 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1493 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001494 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001495 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001496 diagnostic_suggest = diag::err_undeclared_use_suggest;
1497 }
John McCall578b69b2009-12-16 08:11:27 +00001498
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001499 // If the original lookup was an unqualified lookup, fake an
1500 // unqualified lookup. This is useful when (for example) the
1501 // original lookup would not have found something because it was a
1502 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001503 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1504 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001505 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001506 if (isa<CXXRecordDecl>(DC)) {
1507 LookupQualifiedName(R, DC);
1508
1509 if (!R.empty()) {
1510 // Don't give errors about ambiguities in this lookup.
1511 R.suppressDiagnostics();
1512
Francois Pichete6226ae2011-11-17 03:44:24 +00001513 // During a default argument instantiation the CurContext points
1514 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1515 // function parameter list, hence add an explicit check.
1516 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1517 ActiveTemplateInstantiations.back().Kind ==
1518 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001519 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1520 bool isInstance = CurMethod &&
1521 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001522 DC == CurMethod->getParent() && !isDefaultArgument;
1523
John McCall578b69b2009-12-16 08:11:27 +00001524
1525 // Give a code modification hint to insert 'this->'.
1526 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1527 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001528 if (getLangOpts().MicrosoftMode)
1529 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001530 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001531 Diag(R.getNameLoc(), diagnostic) << Name
1532 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001533 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1534 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001535
1536
1537 CXXMethodDecl *DepMethod;
1538 if (CurMethod->getTemplatedKind() ==
1539 FunctionDecl::TK_FunctionTemplateSpecialization)
1540 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1541 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1542 else
1543 DepMethod = cast<CXXMethodDecl>(
1544 CurMethod->getInstantiatedFromMemberFunction());
1545 assert(DepMethod && "No template pattern found");
1546
1547 QualType DepThisType = DepMethod->getThisType(Context);
1548 CheckCXXThisCapture(R.getNameLoc());
1549 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1550 R.getNameLoc(), DepThisType, false);
1551 TemplateArgumentListInfo TList;
1552 if (ULE->hasExplicitTemplateArgs())
1553 ULE->copyTemplateArgumentsInto(TList);
1554
1555 CXXScopeSpec SS;
1556 SS.Adopt(ULE->getQualifierLoc());
1557 CXXDependentScopeMemberExpr *DepExpr =
1558 CXXDependentScopeMemberExpr::Create(
1559 Context, DepThis, DepThisType, true, SourceLocation(),
1560 SS.getWithLocInContext(Context),
1561 ULE->getTemplateKeywordLoc(), 0,
1562 R.getLookupNameInfo(),
1563 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1564 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001565 } else {
John McCall578b69b2009-12-16 08:11:27 +00001566 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001567 }
John McCall578b69b2009-12-16 08:11:27 +00001568
1569 // Do we really want to note all of these?
1570 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1571 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1572
Francois Pichete6226ae2011-11-17 03:44:24 +00001573 // Return true if we are inside a default argument instantiation
1574 // and the found name refers to an instance member function, otherwise
1575 // the function calling DiagnoseEmptyLookup will try to create an
1576 // implicit member call and this is wrong for default argument.
1577 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1578 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1579 return true;
1580 }
1581
John McCall578b69b2009-12-16 08:11:27 +00001582 // Tell the callee to try to recover.
1583 return false;
1584 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001585
1586 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001587 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001588
1589 // In Microsoft mode, if we are performing lookup from within a friend
1590 // function definition declared at class scope then we must set
1591 // DC to the lexical parent to be able to search into the parent
1592 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001593 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001594 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1595 DC->getLexicalParent()->isRecord())
1596 DC = DC->getLexicalParent();
1597 else
1598 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001599 }
1600
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001601 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001602 TypoCorrection Corrected;
1603 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001604 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001605 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1606 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001607 R.setLookupName(Corrected.getCorrection());
1608
Hans Wennborg701d1e72011-07-12 08:45:31 +00001609 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001610 if (Corrected.isOverloaded()) {
1611 OverloadCandidateSet OCS(R.getNameLoc());
1612 OverloadCandidateSet::iterator Best;
1613 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1614 CDEnd = Corrected.end();
1615 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001616 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001617 dyn_cast<FunctionTemplateDecl>(*CD))
1618 AddTemplateOverloadCandidate(
1619 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001620 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001621 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1622 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1623 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001624 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001625 }
1626 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1627 case OR_Success:
1628 ND = Best->Function;
1629 break;
1630 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001631 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001632 }
1633 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001634 R.addDecl(ND);
1635 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001636 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001637 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1638 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001639 else
1640 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001641 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001642 << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00001643 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1644 CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001645 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001646 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001647 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001648
1649 // Tell the callee to try to recover.
1650 return false;
1651 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001652
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001653 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001654 // FIXME: If we ended up with a typo for a type name or
1655 // Objective-C class name, we're in trouble because the parser
1656 // is in the wrong place to recover. Suggest the typo
1657 // correction, but don't make it a fix-it since we're not going
1658 // to recover well anyway.
1659 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001660 Diag(R.getNameLoc(), diagnostic_suggest)
1661 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001662 else
1663 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001664 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001665 << SS.getRange();
1666
1667 // Don't try to recover; it won't work.
1668 return true;
1669 }
1670 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001671 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001672 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001673 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001674 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001675 else
Douglas Gregord203a162010-01-01 00:15:04 +00001676 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001677 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001678 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001679 return true;
1680 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001681 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001682 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001683
1684 // Emit a special diagnostic for failed member lookups.
1685 // FIXME: computing the declaration context might fail here (?)
1686 if (!SS.isEmpty()) {
1687 Diag(R.getNameLoc(), diag::err_no_member)
1688 << Name << computeDeclContext(SS, false)
1689 << SS.getRange();
1690 return true;
1691 }
1692
John McCall578b69b2009-12-16 08:11:27 +00001693 // Give up, we can't recover.
1694 Diag(R.getNameLoc(), diagnostic) << Name;
1695 return true;
1696}
1697
John McCall60d7b3a2010-08-24 06:29:42 +00001698ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001699 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001700 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001701 UnqualifiedId &Id,
1702 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001703 bool IsAddressOfOperand,
1704 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001705 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001706 "cannot be direct & operand and have a trailing lparen");
1707
1708 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001709 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001710
John McCall129e2df2009-11-30 22:42:35 +00001711 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001712
1713 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001714 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001715 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001716 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001717
Abramo Bagnara25777432010-08-11 22:01:17 +00001718 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001719 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001720 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001721
John McCallf7a1a742009-11-24 19:00:30 +00001722 // C++ [temp.dep.expr]p3:
1723 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001724 // -- an identifier that was declared with a dependent type,
1725 // (note: handled after lookup)
1726 // -- a template-id that is dependent,
1727 // (note: handled in BuildTemplateIdExpr)
1728 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001729 // -- a nested-name-specifier that contains a class-name that
1730 // names a dependent type.
1731 // Determine whether this is a member of an unknown specialization;
1732 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001733 bool DependentID = false;
1734 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1735 Name.getCXXNameType()->isDependentType()) {
1736 DependentID = true;
1737 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001738 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001739 if (RequireCompleteDeclContext(SS, DC))
1740 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001741 } else {
1742 DependentID = true;
1743 }
1744 }
1745
Chris Lattner337e5502011-02-18 01:27:55 +00001746 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001747 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1748 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001749
John McCallf7a1a742009-11-24 19:00:30 +00001750 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001751 LookupResult R(*this, NameInfo,
1752 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1753 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001754 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001755 // Lookup the template name again to correctly establish the context in
1756 // which it was found. This is really unfortunate as we already did the
1757 // lookup to determine that it was a template name in the first place. If
1758 // this becomes a performance hit, we can work harder to preserve those
1759 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001760 bool MemberOfUnknownSpecialization;
1761 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1762 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001763
1764 if (MemberOfUnknownSpecialization ||
1765 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001766 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1767 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001768 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001769 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001770 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001772 // If the result might be in a dependent base class, this is a dependent
1773 // id-expression.
1774 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001775 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1776 IsAddressOfOperand, TemplateArgs);
1777
John McCallf7a1a742009-11-24 19:00:30 +00001778 // If this reference is in an Objective-C method, then we need to do
1779 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001780 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001781 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001782 if (E.isInvalid())
1783 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Chris Lattner337e5502011-02-18 01:27:55 +00001785 if (Expr *Ex = E.takeAs<Expr>())
1786 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001787 }
Chris Lattner8a934232008-03-31 00:36:02 +00001788 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001789
John McCallf7a1a742009-11-24 19:00:30 +00001790 if (R.isAmbiguous())
1791 return ExprError();
1792
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001793 // Determine whether this name might be a candidate for
1794 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001795 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001796
John McCallf7a1a742009-11-24 19:00:30 +00001797 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001799 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001800 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001801 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1802 if (D) R.addDecl(D);
1803 }
1804
1805 // If this name wasn't predeclared and if this is not a function
1806 // call, diagnose the problem.
1807 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001808
1809 // In Microsoft mode, if we are inside a template class member function
1810 // and we can't resolve an identifier then assume the identifier is type
1811 // dependent. The goal is to postpone name lookup to instantiation time
1812 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001813 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001814 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001815 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1816 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001817
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001818 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001819 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001820 return ExprError();
1821
1822 assert(!R.empty() &&
1823 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001824
1825 // If we found an Objective-C instance variable, let
1826 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001827 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001828 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1829 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001830 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001831 // In a hopelessly buggy code, Objective-C instance variable
1832 // lookup fails and no expression will be built to reference it.
1833 if (!E.isInvalid() && !E.get())
1834 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001835 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001836 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001837 }
1838 }
Mike Stump1eb44332009-09-09 15:08:12 +00001839
John McCallf7a1a742009-11-24 19:00:30 +00001840 // This is guaranteed from this point on.
1841 assert(!R.empty() || ADL);
1842
John McCallaa81e162009-12-01 22:10:20 +00001843 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001844 // C++ [class.mfct.non-static]p3:
1845 // When an id-expression that is not part of a class member access
1846 // syntax and not used to form a pointer to member is used in the
1847 // body of a non-static member function of class X, if name lookup
1848 // resolves the name in the id-expression to a non-static non-type
1849 // member of some class C, the id-expression is transformed into a
1850 // class member access expression using (*this) as the
1851 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001852 //
1853 // But we don't actually need to do this for '&' operands if R
1854 // resolved to a function or overloaded function set, because the
1855 // expression is ill-formed if it actually works out to be a
1856 // non-static member function:
1857 //
1858 // C++ [expr.ref]p4:
1859 // Otherwise, if E1.E2 refers to a non-static member function. . .
1860 // [t]he expression can be used only as the left-hand operand of a
1861 // member function call.
1862 //
1863 // There are other safeguards against such uses, but it's important
1864 // to get this right here so that we don't end up making a
1865 // spuriously dependent expression if we're inside a dependent
1866 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001867 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001868 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001869 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001870 MightBeImplicitMember = true;
1871 else if (!SS.isEmpty())
1872 MightBeImplicitMember = false;
1873 else if (R.isOverloadedResult())
1874 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001875 else if (R.isUnresolvableResult())
1876 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001877 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001878 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1879 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001880
1881 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001882 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1883 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001884 }
1885
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001886 if (TemplateArgs || TemplateKWLoc.isValid())
1887 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001888
John McCallf7a1a742009-11-24 19:00:30 +00001889 return BuildDeclarationNameExpr(SS, R, ADL);
1890}
1891
John McCall129e2df2009-11-30 22:42:35 +00001892/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1893/// declaration name, generally during template instantiation.
1894/// There's a large number of things which don't need to be done along
1895/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001896ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001897Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Richard Smithefeeccf2012-10-21 03:28:35 +00001898 const DeclarationNameInfo &NameInfo,
1899 bool IsAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001900 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001901 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001902 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1903 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001904
John McCall77bb1aa2010-05-01 00:40:08 +00001905 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001906 return ExprError();
1907
Abramo Bagnara25777432010-08-11 22:01:17 +00001908 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001909 LookupQualifiedName(R, DC);
1910
1911 if (R.isAmbiguous())
1912 return ExprError();
1913
1914 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001915 Diag(NameInfo.getLoc(), diag::err_no_member)
1916 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001917 return ExprError();
1918 }
1919
Richard Smithefeeccf2012-10-21 03:28:35 +00001920 // Defend against this resolving to an implicit member access. We usually
1921 // won't get here if this might be a legitimate a class member (we end up in
1922 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1923 // a pointer-to-member or in an unevaluated context in C++11.
1924 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1925 return BuildPossibleImplicitMemberExpr(SS,
1926 /*TemplateKWLoc=*/SourceLocation(),
1927 R, /*TemplateArgs=*/0);
1928
1929 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCallf7a1a742009-11-24 19:00:30 +00001930}
1931
1932/// LookupInObjCMethod - The parser has read a name in, and Sema has
1933/// detected that we're currently inside an ObjC method. Perform some
1934/// additional lookup.
1935///
1936/// Ideally, most of this would be done by lookup, but there's
1937/// actually quite a lot of extra work involved.
1938///
1939/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001940ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001941Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001942 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001943 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001944 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001945
John McCallf7a1a742009-11-24 19:00:30 +00001946 // There are two cases to handle here. 1) scoped lookup could have failed,
1947 // in which case we should look for an ivar. 2) scoped lookup could have
1948 // found a decl, but that decl is outside the current instance method (i.e.
1949 // a global variable). In these two cases, we do a lookup for an ivar with
1950 // this name, if the lookup sucedes, we replace it our current decl.
1951
1952 // If we're in a class method, we don't normally want to look for
1953 // ivars. But if we don't find anything else, and there's an
1954 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001955 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001956
1957 bool LookForIvars;
1958 if (Lookup.empty())
1959 LookForIvars = true;
1960 else if (IsClassMethod)
1961 LookForIvars = false;
1962 else
1963 LookForIvars = (Lookup.isSingleResult() &&
1964 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001965 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001966 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001967 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001968 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001969 ObjCIvarDecl *IV = 0;
1970 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001971 // Diagnose using an ivar in a class method.
1972 if (IsClassMethod)
1973 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1974 << IV->getDeclName());
1975
1976 // If we're referencing an invalid decl, just return this as a silent
1977 // error node. The error diagnostic was already emitted on the decl.
1978 if (IV->isInvalidDecl())
1979 return ExprError();
1980
1981 // Check if referencing a field with __attribute__((deprecated)).
1982 if (DiagnoseUseOfDecl(IV, Loc))
1983 return ExprError();
1984
1985 // Diagnose the use of an ivar outside of the declaring class.
1986 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001987 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001988 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001989 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1990
1991 // FIXME: This should use a new expr for a direct reference, don't
1992 // turn this into Self->ivar, just return a BareIVarExpr or something.
1993 IdentifierInfo &II = Context.Idents.get("self");
1994 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001995 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001996 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001997 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001998 SourceLocation TemplateKWLoc;
1999 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002000 SelfName, false, false);
2001 if (SelfExpr.isInvalid())
2002 return ExprError();
2003
John Wiegley429bb272011-04-08 18:41:53 +00002004 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2005 if (SelfExpr.isInvalid())
2006 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002007
Eli Friedman5f2987c2012-02-02 03:46:19 +00002008 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002009
2010 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2011 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
2012 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00002013
2014 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2015 Loc,
2016 SelfExpr.take(),
2017 true, true);
2018
2019 if (getLangOpts().ObjCAutoRefCount) {
2020 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2021 DiagnosticsEngine::Level Level =
2022 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2023 if (Level != DiagnosticsEngine::Ignored)
2024 getCurFunction()->recordUseOfWeak(Result);
2025 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002026 if (CurContext->isClosure())
2027 Diag(Loc, diag::warn_implicitly_retains_self)
2028 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002029 }
2030
2031 return Owned(Result);
John McCallf7a1a742009-11-24 19:00:30 +00002032 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002033 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002034 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002035 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2036 ObjCInterfaceDecl *ClassDeclared;
2037 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2038 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002039 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002040 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2041 }
John McCallf7a1a742009-11-24 19:00:30 +00002042 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002043 } else if (Lookup.isSingleResult() &&
2044 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2045 // If accessing a stand-alone ivar in a class method, this is an error.
2046 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2047 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2048 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002049 }
2050
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002051 if (Lookup.empty() && II && AllowBuiltinCreation) {
2052 // FIXME. Consolidate this with similar code in LookupName.
2053 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002054 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002055 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2056 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2057 S, Lookup.isForRedeclaration(),
2058 Lookup.getNameLoc());
2059 if (D) Lookup.addDecl(D);
2060 }
2061 }
2062 }
John McCallf7a1a742009-11-24 19:00:30 +00002063 // Sentinel value saying that we didn't do anything special.
2064 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002065}
John McCallba135432009-11-21 08:51:07 +00002066
John McCall6bb80172010-03-30 21:47:33 +00002067/// \brief Cast a base object to a member's actual type.
2068///
2069/// Logically this happens in three phases:
2070///
2071/// * First we cast from the base type to the naming class.
2072/// The naming class is the class into which we were looking
2073/// when we found the member; it's the qualifier type if a
2074/// qualifier was provided, and otherwise it's the base type.
2075///
2076/// * Next we cast from the naming class to the declaring class.
2077/// If the member we found was brought into a class's scope by
2078/// a using declaration, this is that class; otherwise it's
2079/// the class declaring the member.
2080///
2081/// * Finally we cast from the declaring class to the "true"
2082/// declaring class of the member. This conversion does not
2083/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002084ExprResult
2085Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002086 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002087 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002088 NamedDecl *Member) {
2089 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2090 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002091 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002092
Douglas Gregor5fccd362010-03-03 23:55:11 +00002093 QualType DestRecordType;
2094 QualType DestType;
2095 QualType FromRecordType;
2096 QualType FromType = From->getType();
2097 bool PointerConversions = false;
2098 if (isa<FieldDecl>(Member)) {
2099 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002100
Douglas Gregor5fccd362010-03-03 23:55:11 +00002101 if (FromType->getAs<PointerType>()) {
2102 DestType = Context.getPointerType(DestRecordType);
2103 FromRecordType = FromType->getPointeeType();
2104 PointerConversions = true;
2105 } else {
2106 DestType = DestRecordType;
2107 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002108 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002109 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2110 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002111 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002112
Douglas Gregor5fccd362010-03-03 23:55:11 +00002113 DestType = Method->getThisType(Context);
2114 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002115
Douglas Gregor5fccd362010-03-03 23:55:11 +00002116 if (FromType->getAs<PointerType>()) {
2117 FromRecordType = FromType->getPointeeType();
2118 PointerConversions = true;
2119 } else {
2120 FromRecordType = FromType;
2121 DestType = DestRecordType;
2122 }
2123 } else {
2124 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002125 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002126 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002127
Douglas Gregor5fccd362010-03-03 23:55:11 +00002128 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002129 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002130
Douglas Gregor5fccd362010-03-03 23:55:11 +00002131 // If the unqualified types are the same, no conversion is necessary.
2132 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002133 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002134
John McCall6bb80172010-03-30 21:47:33 +00002135 SourceRange FromRange = From->getSourceRange();
2136 SourceLocation FromLoc = FromRange.getBegin();
2137
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002138 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002139
Douglas Gregor5fccd362010-03-03 23:55:11 +00002140 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002141 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002142 // class name.
2143 //
2144 // If the member was a qualified name and the qualified referred to a
2145 // specific base subobject type, we'll cast to that intermediate type
2146 // first and then to the object in which the member is declared. That allows
2147 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2148 //
2149 // class Base { public: int x; };
2150 // class Derived1 : public Base { };
2151 // class Derived2 : public Base { };
2152 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2153 //
2154 // void VeryDerived::f() {
2155 // x = 17; // error: ambiguous base subobjects
2156 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2157 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002158 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002159 QualType QType = QualType(Qualifier->getAsType(), 0);
2160 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2161 assert(QType->isRecordType() && "lookup done with non-record type");
2162
2163 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2164
2165 // In C++98, the qualifier type doesn't actually have to be a base
2166 // type of the object type, in which case we just ignore it.
2167 // Otherwise build the appropriate casts.
2168 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002169 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002170 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002171 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002172 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002173
Douglas Gregor5fccd362010-03-03 23:55:11 +00002174 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002175 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002176 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2177 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002178
2179 FromType = QType;
2180 FromRecordType = QRecordType;
2181
2182 // If the qualifier type was the same as the destination type,
2183 // we're done.
2184 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002185 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002186 }
2187 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002188
John McCall6bb80172010-03-30 21:47:33 +00002189 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002190
John McCall6bb80172010-03-30 21:47:33 +00002191 // If we actually found the member through a using declaration, cast
2192 // down to the using declaration's type.
2193 //
2194 // Pointer equality is fine here because only one declaration of a
2195 // class ever has member declarations.
2196 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2197 assert(isa<UsingShadowDecl>(FoundDecl));
2198 QualType URecordType = Context.getTypeDeclType(
2199 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2200
2201 // We only need to do this if the naming-class to declaring-class
2202 // conversion is non-trivial.
2203 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2204 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002205 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002206 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002207 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002208 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002209
John McCall6bb80172010-03-30 21:47:33 +00002210 QualType UType = URecordType;
2211 if (PointerConversions)
2212 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002213 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2214 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002215 FromType = UType;
2216 FromRecordType = URecordType;
2217 }
2218
2219 // We don't do access control for the conversion from the
2220 // declaring class to the true declaring class.
2221 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002222 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002223
John McCallf871d0c2010-08-07 06:22:56 +00002224 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002225 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2226 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002227 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002228 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002229
John Wiegley429bb272011-04-08 18:41:53 +00002230 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2231 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002232}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002233
John McCallf7a1a742009-11-24 19:00:30 +00002234bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002235 const LookupResult &R,
2236 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002237 // Only when used directly as the postfix-expression of a call.
2238 if (!HasTrailingLParen)
2239 return false;
2240
2241 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002242 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002243 return false;
2244
2245 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002246 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002247 return false;
2248
2249 // Turn off ADL when we find certain kinds of declarations during
2250 // normal lookup:
2251 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2252 NamedDecl *D = *I;
2253
2254 // C++0x [basic.lookup.argdep]p3:
2255 // -- a declaration of a class member
2256 // Since using decls preserve this property, we check this on the
2257 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002258 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002259 return false;
2260
2261 // C++0x [basic.lookup.argdep]p3:
2262 // -- a block-scope function declaration that is not a
2263 // using-declaration
2264 // NOTE: we also trigger this for function templates (in fact, we
2265 // don't check the decl type at all, since all other decl types
2266 // turn off ADL anyway).
2267 if (isa<UsingShadowDecl>(D))
2268 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2269 else if (D->getDeclContext()->isFunctionOrMethod())
2270 return false;
2271
2272 // C++0x [basic.lookup.argdep]p3:
2273 // -- a declaration that is neither a function or a function
2274 // template
2275 // And also for builtin functions.
2276 if (isa<FunctionDecl>(D)) {
2277 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2278
2279 // But also builtin functions.
2280 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2281 return false;
2282 } else if (!isa<FunctionTemplateDecl>(D))
2283 return false;
2284 }
2285
2286 return true;
2287}
2288
2289
John McCallba135432009-11-21 08:51:07 +00002290/// Diagnoses obvious problems with the use of the given declaration
2291/// as an expression. This is only actually called for lookups that
2292/// were not overloaded, and it doesn't promise that the declaration
2293/// will in fact be used.
2294static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002295 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002296 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2297 return true;
2298 }
2299
2300 if (isa<ObjCInterfaceDecl>(D)) {
2301 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2302 return true;
2303 }
2304
2305 if (isa<NamespaceDecl>(D)) {
2306 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2307 return true;
2308 }
2309
2310 return false;
2311}
2312
John McCall60d7b3a2010-08-24 06:29:42 +00002313ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002314Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002315 LookupResult &R,
2316 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002317 // If this is a single, fully-resolved result and we don't need ADL,
2318 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002319 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002320 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2321 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002322
2323 // We only need to check the declaration if there's exactly one
2324 // result, because in the overloaded case the results can only be
2325 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002326 if (R.isSingleResult() &&
2327 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002328 return ExprError();
2329
John McCallc373d482010-01-27 01:50:18 +00002330 // Otherwise, just build an unresolved lookup expression. Suppress
2331 // any lookup-related diagnostics; we'll hash these out later, when
2332 // we've picked a target.
2333 R.suppressDiagnostics();
2334
John McCallba135432009-11-21 08:51:07 +00002335 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002336 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002337 SS.getWithLocInContext(Context),
2338 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002339 NeedsADL, R.isOverloadedResult(),
2340 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002341
2342 return Owned(ULE);
2343}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002344
John McCallba135432009-11-21 08:51:07 +00002345/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002346ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002347Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002348 const DeclarationNameInfo &NameInfo,
2349 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002350 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002351 assert(!isa<FunctionTemplateDecl>(D) &&
2352 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002353
Abramo Bagnara25777432010-08-11 22:01:17 +00002354 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002355 if (CheckDeclInExpr(*this, Loc, D))
2356 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002357
Douglas Gregor9af2f522009-12-01 16:58:18 +00002358 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2359 // Specifically diagnose references to class templates that are missing
2360 // a template argument list.
2361 Diag(Loc, diag::err_template_decl_ref)
2362 << Template << SS.getRange();
2363 Diag(Template->getLocation(), diag::note_template_decl_here);
2364 return ExprError();
2365 }
2366
2367 // Make sure that we're referring to a value.
2368 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2369 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002370 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002371 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002372 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002373 return ExprError();
2374 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002375
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002376 // Check whether this declaration can be used. Note that we suppress
2377 // this check when we're going to perform argument-dependent lookup
2378 // on this function name, because this might not be the function
2379 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002380 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002381 return ExprError();
2382
Steve Naroffdd972f22008-09-05 22:11:13 +00002383 // Only create DeclRefExpr's for valid Decl's.
2384 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002385 return ExprError();
2386
John McCall5808ce42011-02-03 08:15:49 +00002387 // Handle members of anonymous structs and unions. If we got here,
2388 // and the reference is to a class member indirect field, then this
2389 // must be the subject of a pointer-to-member expression.
2390 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2391 if (!indirectField->isCXXClassMember())
2392 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2393 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002394
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002395 {
John McCall76a40212011-02-09 01:13:10 +00002396 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002397 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002398
2399 switch (D->getKind()) {
2400 // Ignore all the non-ValueDecl kinds.
2401#define ABSTRACT_DECL(kind)
2402#define VALUE(type, base)
2403#define DECL(type, base) \
2404 case Decl::type:
2405#include "clang/AST/DeclNodes.inc"
2406 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002407
2408 // These shouldn't make it here.
2409 case Decl::ObjCAtDefsField:
2410 case Decl::ObjCIvar:
2411 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002412
2413 // Enum constants are always r-values and never references.
2414 // Unresolved using declarations are dependent.
2415 case Decl::EnumConstant:
2416 case Decl::UnresolvedUsingValue:
2417 valueKind = VK_RValue;
2418 break;
2419
2420 // Fields and indirect fields that got here must be for
2421 // pointer-to-member expressions; we just call them l-values for
2422 // internal consistency, because this subexpression doesn't really
2423 // exist in the high-level semantics.
2424 case Decl::Field:
2425 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002426 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002427 "building reference to field in C?");
2428
2429 // These can't have reference type in well-formed programs, but
2430 // for internal consistency we do this anyway.
2431 type = type.getNonReferenceType();
2432 valueKind = VK_LValue;
2433 break;
2434
2435 // Non-type template parameters are either l-values or r-values
2436 // depending on the type.
2437 case Decl::NonTypeTemplateParm: {
2438 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2439 type = reftype->getPointeeType();
2440 valueKind = VK_LValue; // even if the parameter is an r-value reference
2441 break;
2442 }
2443
2444 // For non-references, we need to strip qualifiers just in case
2445 // the template parameter was declared as 'const int' or whatever.
2446 valueKind = VK_RValue;
2447 type = type.getUnqualifiedType();
2448 break;
2449 }
2450
2451 case Decl::Var:
2452 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002453 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002454 !type.hasQualifiers() &&
2455 type->isVoidType()) {
2456 valueKind = VK_RValue;
2457 break;
2458 }
2459 // fallthrough
2460
2461 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002462 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002463 // These are always l-values.
2464 valueKind = VK_LValue;
2465 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002466
Douglas Gregor68932842012-02-18 05:51:20 +00002467 // FIXME: Does the addition of const really only apply in
2468 // potentially-evaluated contexts? Since the variable isn't actually
2469 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002470 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002471 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2472 if (!CapturedType.isNull())
2473 type = CapturedType;
2474 }
2475
John McCall76a40212011-02-09 01:13:10 +00002476 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002477 }
2478
John McCall76a40212011-02-09 01:13:10 +00002479 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002480 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2481 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2482 type = Context.BuiltinFnTy;
2483 valueKind = VK_RValue;
2484 break;
2485 }
2486 }
2487
John McCall755d8492011-04-12 00:42:48 +00002488 const FunctionType *fty = type->castAs<FunctionType>();
2489
2490 // If we're referring to a function with an __unknown_anytype
2491 // result type, make the entire expression __unknown_anytype.
2492 if (fty->getResultType() == Context.UnknownAnyTy) {
2493 type = Context.UnknownAnyTy;
2494 valueKind = VK_RValue;
2495 break;
2496 }
2497
John McCall76a40212011-02-09 01:13:10 +00002498 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002499 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002500 valueKind = VK_LValue;
2501 break;
2502 }
2503
2504 // C99 DR 316 says that, if a function type comes from a
2505 // function definition (without a prototype), that type is only
2506 // used for checking compatibility. Therefore, when referencing
2507 // the function, we pretend that we don't have the full function
2508 // type.
John McCall755d8492011-04-12 00:42:48 +00002509 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2510 isa<FunctionProtoType>(fty))
2511 type = Context.getFunctionNoProtoType(fty->getResultType(),
2512 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002513
2514 // Functions are r-values in C.
2515 valueKind = VK_RValue;
2516 break;
2517 }
2518
2519 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002520 // If we're referring to a method with an __unknown_anytype
2521 // result type, make the entire expression __unknown_anytype.
2522 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002523 if (const FunctionProtoType *proto
2524 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002525 if (proto->getResultType() == Context.UnknownAnyTy) {
2526 type = Context.UnknownAnyTy;
2527 valueKind = VK_RValue;
2528 break;
2529 }
2530
John McCall76a40212011-02-09 01:13:10 +00002531 // C++ methods are l-values if static, r-values if non-static.
2532 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2533 valueKind = VK_LValue;
2534 break;
2535 }
2536 // fallthrough
2537
2538 case Decl::CXXConversion:
2539 case Decl::CXXDestructor:
2540 case Decl::CXXConstructor:
2541 valueKind = VK_RValue;
2542 break;
2543 }
2544
2545 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2546 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002547}
2548
John McCall755d8492011-04-12 00:42:48 +00002549ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002550 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002551
Reid Spencer5f016e22007-07-11 17:01:13 +00002552 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002553 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002554 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2555 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002556 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002557 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002559
Chris Lattnerfa28b302008-01-12 08:14:25 +00002560 // Pre-defined identifiers are of type char[x], where x is the length of the
2561 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Anders Carlsson3a082d82009-09-08 18:24:21 +00002563 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002564 if (!currentDecl && getCurBlock())
2565 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002566 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002567 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002568 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002569 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002570
Anders Carlsson773f3972009-09-11 01:22:35 +00002571 QualType ResTy;
2572 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2573 ResTy = Context.DependentTy;
2574 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002575 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002576
Anders Carlsson773f3972009-09-11 01:22:35 +00002577 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002578 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002579 ResTy = Context.WCharTy.withConst();
2580 else
2581 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002582 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2583 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002584 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002585}
2586
Richard Smith36f5cfe2012-03-09 08:00:36 +00002587ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002588 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002589 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002590 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002591 if (Invalid)
2592 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002593
Benjamin Kramerddeea562010-02-27 13:44:12 +00002594 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002595 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002597 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002598
Chris Lattnere8337df2009-12-30 21:19:39 +00002599 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002600 if (Literal.isWide())
2601 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002602 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002603 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002604 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002605 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002606 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002607 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002608 else
2609 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002610
Douglas Gregor5cee1192011-07-27 05:40:30 +00002611 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2612 if (Literal.isWide())
2613 Kind = CharacterLiteral::Wide;
2614 else if (Literal.isUTF16())
2615 Kind = CharacterLiteral::UTF16;
2616 else if (Literal.isUTF32())
2617 Kind = CharacterLiteral::UTF32;
2618
Richard Smithdd66be72012-03-08 01:34:56 +00002619 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2620 Tok.getLocation());
2621
2622 if (Literal.getUDSuffix().empty())
2623 return Owned(Lit);
2624
2625 // We're building a user-defined literal.
2626 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2627 SourceLocation UDSuffixLoc =
2628 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2629
Richard Smith36f5cfe2012-03-09 08:00:36 +00002630 // Make sure we're allowed user-defined literals here.
2631 if (!UDLScope)
2632 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2633
Richard Smithdd66be72012-03-08 01:34:56 +00002634 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2635 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002636 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2637 llvm::makeArrayRef(&Lit, 1),
2638 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002639}
2640
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002641ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2642 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2643 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2644 Context.IntTy, Loc));
2645}
2646
Richard Smithb453ad32012-03-08 08:45:32 +00002647static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2648 QualType Ty, SourceLocation Loc) {
2649 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2650
2651 using llvm::APFloat;
2652 APFloat Val(Format);
2653
2654 APFloat::opStatus result = Literal.GetFloatValue(Val);
2655
2656 // Overflow is always an error, but underflow is only an error if
2657 // we underflowed to zero (APFloat reports denormals as underflow).
2658 if ((result & APFloat::opOverflow) ||
2659 ((result & APFloat::opUnderflow) && Val.isZero())) {
2660 unsigned diagnostic;
2661 SmallString<20> buffer;
2662 if (result & APFloat::opOverflow) {
2663 diagnostic = diag::warn_float_overflow;
2664 APFloat::getLargest(Format).toString(buffer);
2665 } else {
2666 diagnostic = diag::warn_float_underflow;
2667 APFloat::getSmallest(Format).toString(buffer);
2668 }
2669
2670 S.Diag(Loc, diagnostic)
2671 << Ty
2672 << StringRef(buffer.data(), buffer.size());
2673 }
2674
2675 bool isExact = (result == APFloat::opOK);
2676 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2677}
2678
Richard Smith36f5cfe2012-03-09 08:00:36 +00002679ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002680 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002681 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002683 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002684 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 }
Ted Kremenek28396602009-01-13 23:19:12 +00002686
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002687 SmallString<128> SpellingBuffer;
2688 // NumericLiteralParser wants to overread by one character. Add padding to
2689 // the buffer in case the token is copied to the buffer. If getSpelling()
2690 // returns a StringRef to the memory buffer, it should have a null char at
2691 // the EOF, so it is also safe.
2692 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002693
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002695 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002696 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002697 if (Invalid)
2698 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002699
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002700 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002702 return ExprError();
2703
Richard Smithb453ad32012-03-08 08:45:32 +00002704 if (Literal.hasUDSuffix()) {
2705 // We're building a user-defined literal.
2706 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2707 SourceLocation UDSuffixLoc =
2708 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2709
Richard Smith36f5cfe2012-03-09 08:00:36 +00002710 // Make sure we're allowed user-defined literals here.
2711 if (!UDLScope)
2712 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002713
Richard Smith36f5cfe2012-03-09 08:00:36 +00002714 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002715 if (Literal.isFloatingLiteral()) {
2716 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2717 // long double, the literal is treated as a call of the form
2718 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002719 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002720 } else {
2721 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2722 // unsigned long long, the literal is treated as a call of the form
2723 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002724 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002725 }
2726
Richard Smith36f5cfe2012-03-09 08:00:36 +00002727 DeclarationName OpName =
2728 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2729 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2730 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2731
2732 // Perform literal operator lookup to determine if we're building a raw
2733 // literal or a cooked one.
2734 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2735 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2736 /*AllowRawAndTemplate*/true)) {
2737 case LOLR_Error:
2738 return ExprError();
2739
2740 case LOLR_Cooked: {
2741 Expr *Lit;
2742 if (Literal.isFloatingLiteral()) {
2743 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2744 } else {
2745 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2746 if (Literal.GetIntegerValue(ResultVal))
2747 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2748 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2749 Tok.getLocation());
2750 }
2751 return BuildLiteralOperatorCall(R, OpNameInfo,
2752 llvm::makeArrayRef(&Lit, 1),
2753 Tok.getLocation());
2754 }
2755
2756 case LOLR_Raw: {
2757 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2758 // literal is treated as a call of the form
2759 // operator "" X ("n")
2760 SourceLocation TokLoc = Tok.getLocation();
2761 unsigned Length = Literal.getUDSuffixOffset();
2762 QualType StrTy = Context.getConstantArrayType(
2763 Context.CharTy, llvm::APInt(32, Length + 1),
2764 ArrayType::Normal, 0);
2765 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002766 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00002767 /*Pascal*/false, StrTy, &TokLoc, 1);
2768 return BuildLiteralOperatorCall(R, OpNameInfo,
2769 llvm::makeArrayRef(&Lit, 1), TokLoc);
2770 }
2771
2772 case LOLR_Template:
2773 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2774 // template), L is treated as a call fo the form
2775 // operator "" X <'c1', 'c2', ... 'ck'>()
2776 // where n is the source character sequence c1 c2 ... ck.
2777 TemplateArgumentListInfo ExplicitArgs;
2778 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2779 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2780 llvm::APSInt Value(CharBits, CharIsUnsigned);
2781 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00002782 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002783 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002784 TemplateArgumentLocInfo ArgInfo;
2785 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2786 }
2787 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2788 Tok.getLocation(), &ExplicitArgs);
2789 }
2790
2791 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002792 }
2793
Chris Lattner5d661452007-08-26 03:42:43 +00002794 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002795
Chris Lattner5d661452007-08-26 03:42:43 +00002796 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002797 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002798 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002799 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002800 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002801 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002802 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002803 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002804
Richard Smithb453ad32012-03-08 08:45:32 +00002805 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002806
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002807 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002808 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002809 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002810 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002811 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002812 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002813 }
2814 }
Chris Lattner5d661452007-08-26 03:42:43 +00002815 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002816 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002817 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002818 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002819
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00002820 // 'long long' is a C99 or C++11 feature.
2821 if (!getLangOpts().C99 && Literal.isLongLong) {
2822 if (getLangOpts().CPlusPlus)
2823 Diag(Tok.getLocation(),
2824 getLangOpts().CPlusPlus0x ?
2825 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2826 else
2827 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2828 }
Neil Boothb9449512007-08-29 22:00:19 +00002829
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002831 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2832 // The microsoft literal suffix extensions support 128-bit literals, which
2833 // may be wider than [u]intmax_t.
2834 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2835 MaxWidth = 128;
2836 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002837
Reid Spencer5f016e22007-07-11 17:01:13 +00002838 if (Literal.GetIntegerValue(ResultVal)) {
2839 // If this value didn't fit into uintmax_t, warn and force to ull.
2840 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002841 Ty = Context.UnsignedLongLongTy;
2842 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002843 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 } else {
2845 // If this value fits into a ULL, try to figure out what else it fits into
2846 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002847
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2849 // be an unsigned int.
2850 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2851
2852 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002853 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002854 if (!Literal.isLong && !Literal.isLongLong) {
2855 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002856 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002857
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 // Does it fit in a unsigned int?
2859 if (ResultVal.isIntN(IntSize)) {
2860 // Does it fit in a signed int?
2861 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002862 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002864 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002865 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002866 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002868
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002870 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002871 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002872
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 // Does it fit in a unsigned long?
2874 if (ResultVal.isIntN(LongSize)) {
2875 // Does it fit in a signed long?
2876 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002877 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002879 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002880 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002882 }
2883
Stephen Canonb9e05f12012-05-03 22:49:43 +00002884 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002885 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002886 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002887
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 // Does it fit in a unsigned long long?
2889 if (ResultVal.isIntN(LongLongSize)) {
2890 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002891 // To be compatible with MSVC, hex integer literals ending with the
2892 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002893 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002894 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002895 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002897 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002898 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 }
2900 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002901
2902 // If it doesn't fit in unsigned long long, and we're using Microsoft
2903 // extensions, then its a 128-bit integer literal.
2904 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2905 if (Literal.isUnsigned)
2906 Ty = Context.UnsignedInt128Ty;
2907 else
2908 Ty = Context.Int128Ty;
2909 Width = 128;
2910 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002911
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 // If we still couldn't decide a type, we probably have something that
2913 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002914 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002916 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002917 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002918 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002919
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002920 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002921 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002922 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002923 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002924 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002925
Chris Lattner5d661452007-08-26 03:42:43 +00002926 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2927 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002928 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002929 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002930
2931 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002932}
2933
Richard Trieuccd891a2011-09-09 01:45:06 +00002934ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002935 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002936 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002937}
2938
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002939static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2940 SourceLocation Loc,
2941 SourceRange ArgRange) {
2942 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2943 // scalar or vector data type argument..."
2944 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2945 // type (C99 6.2.5p18) or void.
2946 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2947 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2948 << T << ArgRange;
2949 return true;
2950 }
2951
2952 assert((T->isVoidType() || !T->isIncompleteType()) &&
2953 "Scalar types should always be complete");
2954 return false;
2955}
2956
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002957static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2958 SourceLocation Loc,
2959 SourceRange ArgRange,
2960 UnaryExprOrTypeTrait TraitKind) {
2961 // C99 6.5.3.4p1:
2962 if (T->isFunctionType()) {
2963 // alignof(function) is allowed as an extension.
2964 if (TraitKind == UETT_SizeOf)
2965 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2966 return false;
2967 }
2968
2969 // Allow sizeof(void)/alignof(void) as an extension.
2970 if (T->isVoidType()) {
2971 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2972 return false;
2973 }
2974
2975 return true;
2976}
2977
2978static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2979 SourceLocation Loc,
2980 SourceRange ArgRange,
2981 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002982 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2983 // runtime doesn't allow it.
2984 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002985 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2986 << T << (TraitKind == UETT_SizeOf)
2987 << ArgRange;
2988 return true;
2989 }
2990
2991 return false;
2992}
2993
Chandler Carruth9d342d02011-05-26 08:53:10 +00002994/// \brief Check the constrains on expression operands to unary type expression
2995/// and type traits.
2996///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002997/// Completes any types necessary and validates the constraints on the operand
2998/// expression. The logic mostly mirrors the type-based overload, but may modify
2999/// the expression as it completes the type for that expression through template
3000/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00003001bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003002 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003003 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003004
3005 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3006 // the result is the size of the referenced type."
3007 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3008 // result shall be the alignment of the referenced type."
3009 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3010 ExprTy = Ref->getPointeeType();
3011
3012 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003013 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3014 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003015
3016 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003017 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3018 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003019 return false;
3020
Richard Trieuccd891a2011-09-09 01:45:06 +00003021 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00003022 diag::err_sizeof_alignof_incomplete_type,
3023 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003024 return true;
3025
3026 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003027 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003028 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3029 ExprTy = Ref->getPointeeType();
3030
Richard Trieuccd891a2011-09-09 01:45:06 +00003031 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3032 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003033 return true;
3034
Nico Webercf739922011-06-15 02:47:03 +00003035 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003036 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003037 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3038 QualType OType = PVD->getOriginalType();
3039 QualType Type = PVD->getType();
3040 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003041 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003042 << Type << OType;
3043 Diag(PVD->getLocation(), diag::note_declared_at);
3044 }
3045 }
3046 }
3047 }
3048
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003049 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003050}
3051
3052/// \brief Check the constraints on operands to unary expression and type
3053/// traits.
3054///
3055/// This will complete any types necessary, and validate the various constraints
3056/// on those operands.
3057///
Reid Spencer5f016e22007-07-11 17:01:13 +00003058/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003059/// C99 6.3.2.1p[2-4] all state:
3060/// Except when it is the operand of the sizeof operator ...
3061///
3062/// C++ [expr.sizeof]p4
3063/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3064/// standard conversions are not applied to the operand of sizeof.
3065///
3066/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003067bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003068 SourceLocation OpLoc,
3069 SourceRange ExprRange,
3070 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003071 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003072 return false;
3073
Sebastian Redl5d484e82009-11-23 17:18:46 +00003074 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3075 // the result is the size of the referenced type."
3076 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3077 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003078 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3079 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003080
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003081 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003082 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003083
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003084 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003085 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003086 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003087 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Richard Trieuccd891a2011-09-09 01:45:06 +00003089 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003090 diag::err_sizeof_alignof_incomplete_type,
3091 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003092 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003093
Richard Trieuccd891a2011-09-09 01:45:06 +00003094 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003095 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003096 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Chris Lattner1efaa952009-04-24 00:30:45 +00003098 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003099}
3100
Chandler Carruth9d342d02011-05-26 08:53:10 +00003101static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003102 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003103
Mike Stump1eb44332009-09-09 15:08:12 +00003104 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003105 if (isa<DeclRefExpr>(E))
3106 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003107
3108 // Cannot know anything else if the expression is dependent.
3109 if (E->isTypeDependent())
3110 return false;
3111
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003112 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003113 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3114 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003115 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003116 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003117
3118 // Alignment of a field access is always okay, so long as it isn't a
3119 // bit-field.
3120 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003121 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003122 return false;
3123
Chandler Carruth9d342d02011-05-26 08:53:10 +00003124 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003125}
3126
Chandler Carruth9d342d02011-05-26 08:53:10 +00003127bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003128 E = E->IgnoreParens();
3129
3130 // Cannot know anything else if the expression is dependent.
3131 if (E->isTypeDependent())
3132 return false;
3133
Chandler Carruth9d342d02011-05-26 08:53:10 +00003134 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003135}
3136
Douglas Gregorba498172009-03-13 21:01:28 +00003137/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003138ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003139Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3140 SourceLocation OpLoc,
3141 UnaryExprOrTypeTrait ExprKind,
3142 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003143 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003144 return ExprError();
3145
John McCalla93c9342009-12-07 02:54:59 +00003146 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003147
Douglas Gregorba498172009-03-13 21:01:28 +00003148 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003149 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003150 return ExprError();
3151
3152 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003153 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3154 Context.getSizeType(),
3155 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003156}
3157
3158/// \brief Build a sizeof or alignof expression given an expression
3159/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003160ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003161Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3162 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003163 ExprResult PE = CheckPlaceholderExpr(E);
3164 if (PE.isInvalid())
3165 return ExprError();
3166
3167 E = PE.get();
3168
Douglas Gregorba498172009-03-13 21:01:28 +00003169 // Verify that the operand is valid.
3170 bool isInvalid = false;
3171 if (E->isTypeDependent()) {
3172 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003173 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003174 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003175 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003176 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003177 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003178 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003179 isInvalid = true;
3180 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003181 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003182 }
3183
3184 if (isInvalid)
3185 return ExprError();
3186
Eli Friedman71b8fb52012-01-21 01:01:51 +00003187 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3188 PE = TranformToPotentiallyEvaluated(E);
3189 if (PE.isInvalid()) return ExprError();
3190 E = PE.take();
3191 }
3192
Douglas Gregorba498172009-03-13 21:01:28 +00003193 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003194 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003195 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003196 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003197}
3198
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003199/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3200/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003201/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003202ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003203Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003204 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003205 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003206 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003207 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003208
Richard Trieuccd891a2011-09-09 01:45:06 +00003209 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003210 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003211 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003212 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003213 }
Sebastian Redl05189992008-11-11 17:56:53 +00003214
Douglas Gregorba498172009-03-13 21:01:28 +00003215 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003216 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003217 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003218}
3219
John Wiegley429bb272011-04-08 18:41:53 +00003220static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003221 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003222 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003223 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003224
John McCallf6a16482010-12-04 03:47:34 +00003225 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003226 if (V.get()->getObjectKind() != OK_Ordinary) {
3227 V = S.DefaultLvalueConversion(V.take());
3228 if (V.isInvalid())
3229 return QualType();
3230 }
John McCallf6a16482010-12-04 03:47:34 +00003231
Chris Lattnercc26ed72007-08-26 05:39:26 +00003232 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003233 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003234 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Chris Lattnercc26ed72007-08-26 05:39:26 +00003236 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003237 if (V.get()->getType()->isArithmeticType())
3238 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003239
John McCall2cd11fe2010-10-12 02:09:17 +00003240 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003241 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003242 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003243 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003244 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003245 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003246 }
3247
Chris Lattnercc26ed72007-08-26 05:39:26 +00003248 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003249 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003250 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003251 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003252}
3253
3254
Reid Spencer5f016e22007-07-11 17:01:13 +00003255
John McCall60d7b3a2010-08-24 06:29:42 +00003256ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003257Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003258 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003259 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003260 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003261 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003262 case tok::plusplus: Opc = UO_PostInc; break;
3263 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003264 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003265
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003266 // Since this might is a postfix expression, get rid of ParenListExprs.
3267 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3268 if (Result.isInvalid()) return ExprError();
3269 Input = Result.take();
3270
John McCall9ae2f072010-08-23 23:25:46 +00003271 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003272}
3273
John McCall1503f0d2012-07-31 05:14:30 +00003274/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3275///
3276/// \return true on error
3277static bool checkArithmeticOnObjCPointer(Sema &S,
3278 SourceLocation opLoc,
3279 Expr *op) {
3280 assert(op->getType()->isObjCObjectPointerType());
3281 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3282 return false;
3283
3284 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3285 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3286 << op->getSourceRange();
3287 return true;
3288}
3289
John McCall60d7b3a2010-08-24 06:29:42 +00003290ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003291Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3292 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003293 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003294 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003295 if (Result.isInvalid()) return ExprError();
3296 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003297
John McCall9ae2f072010-08-23 23:25:46 +00003298 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003299
David Blaikie4e4d0842012-03-11 07:00:24 +00003300 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003301 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003302 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003303 Context.DependentTy,
3304 VK_LValue, OK_Ordinary,
3305 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003306 }
3307
David Blaikie4e4d0842012-03-11 07:00:24 +00003308 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003309 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003310 LHSExp->getType()->isEnumeralType() ||
3311 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003312 RHSExp->getType()->isEnumeralType()) &&
3313 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003314 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003315 }
3316
John McCall9ae2f072010-08-23 23:25:46 +00003317 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003318}
3319
John McCall60d7b3a2010-08-24 06:29:42 +00003320ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003321Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003322 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003323 Expr *LHSExp = Base;
3324 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003325
Chris Lattner12d9ff62007-07-16 00:14:47 +00003326 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003327 if (!LHSExp->getType()->getAs<VectorType>()) {
3328 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3329 if (Result.isInvalid())
3330 return ExprError();
3331 LHSExp = Result.take();
3332 }
3333 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3334 if (Result.isInvalid())
3335 return ExprError();
3336 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003337
Chris Lattner12d9ff62007-07-16 00:14:47 +00003338 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003339 ExprValueKind VK = VK_LValue;
3340 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003341
Reid Spencer5f016e22007-07-11 17:01:13 +00003342 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003343 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003344 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003345 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003346 Expr *BaseExpr, *IndexExpr;
3347 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003348 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3349 BaseExpr = LHSExp;
3350 IndexExpr = RHSExp;
3351 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003352 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003353 BaseExpr = LHSExp;
3354 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003355 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003356 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003357 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003358 BaseExpr = LHSExp;
3359 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003360
3361 // Use custom logic if this should be the pseudo-object subscript
3362 // expression.
3363 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3364 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3365
Steve Naroff14108da2009-07-10 23:34:53 +00003366 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003367 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3368 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3369 << ResultType << BaseExpr->getSourceRange();
3370 return ExprError();
3371 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003372 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3373 // Handle the uncommon case of "123[Ptr]".
3374 BaseExpr = RHSExp;
3375 IndexExpr = LHSExp;
3376 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003377 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003378 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003379 // Handle the uncommon case of "123[Ptr]".
3380 BaseExpr = RHSExp;
3381 IndexExpr = LHSExp;
3382 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003383 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3384 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3385 << ResultType << BaseExpr->getSourceRange();
3386 return ExprError();
3387 }
John McCall183700f2009-09-21 23:43:11 +00003388 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003389 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003390 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003391 VK = LHSExp->getValueKind();
3392 if (VK != VK_RValue)
3393 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003394
Chris Lattner12d9ff62007-07-16 00:14:47 +00003395 // FIXME: need to deal with const...
3396 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003397 } else if (LHSTy->isArrayType()) {
3398 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003399 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003400 // wasn't promoted because of the C90 rule that doesn't
3401 // allow promoting non-lvalue arrays. Warn, then
3402 // force the promotion here.
3403 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3404 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003405 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3406 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003407 LHSTy = LHSExp->getType();
3408
3409 BaseExpr = LHSExp;
3410 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003411 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003412 } else if (RHSTy->isArrayType()) {
3413 // Same as previous, except for 123[f().a] case
3414 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3415 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003416 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3417 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003418 RHSTy = RHSExp->getType();
3419
3420 BaseExpr = RHSExp;
3421 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003422 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003423 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003424 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3425 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003427 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003428 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003429 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3430 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003431
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003432 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003433 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3434 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003435 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3436
Douglas Gregore7450f52009-03-24 19:52:54 +00003437 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003438 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3439 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003440 // incomplete types are not object types.
3441 if (ResultType->isFunctionType()) {
3442 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3443 << ResultType << BaseExpr->getSourceRange();
3444 return ExprError();
3445 }
Mike Stump1eb44332009-09-09 15:08:12 +00003446
David Blaikie4e4d0842012-03-11 07:00:24 +00003447 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003448 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003449 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3450 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003451
3452 // C forbids expressions of unqualified void type from being l-values.
3453 // See IsCForbiddenLValueType.
3454 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003455 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003456 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003457 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003458 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003459
John McCall09431682010-11-18 19:01:18 +00003460 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003461 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003462
Mike Stumpeed9cac2009-02-19 03:04:26 +00003463 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003464 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003465}
3466
John McCall60d7b3a2010-08-24 06:29:42 +00003467ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003468 FunctionDecl *FD,
3469 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003470 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003471 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003472 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003473 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003474 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003475 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003476 return ExprError();
3477 }
3478
3479 if (Param->hasUninstantiatedDefaultArg()) {
3480 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003481
Richard Smithadb1d4c2012-07-22 23:45:10 +00003482 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3483 Param);
3484
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003485 // Instantiate the expression.
3486 MultiLevelTemplateArgumentList ArgList
3487 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003488
Nico Weber08e41a62010-11-29 18:19:25 +00003489 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003490 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003491 InstantiatingTemplate Inst(*this, CallLoc, Param,
3492 ArrayRef<TemplateArgument>(Innermost.first,
3493 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003494 if (Inst)
3495 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003496
Nico Weber08e41a62010-11-29 18:19:25 +00003497 ExprResult Result;
3498 {
3499 // C++ [dcl.fct.default]p5:
3500 // The names in the [default argument] expression are bound, and
3501 // the semantic constraints are checked, at the point where the
3502 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003503 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003504 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003505 Result = SubstExpr(UninstExpr, ArgList);
3506 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003507 if (Result.isInvalid())
3508 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003510 // Check the expression as an initializer for the parameter.
3511 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003512 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003513 InitializationKind Kind
3514 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003515 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003516 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003517
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003518 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003519 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003520 if (Result.isInvalid())
3521 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003522
David Blaikiec1c07252012-04-30 18:21:31 +00003523 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003524 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003525 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003526 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003527 }
3528
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003529 // If the default expression creates temporaries, we need to
3530 // push them to the current stack of expression temporaries so they'll
3531 // be properly destroyed.
3532 // FIXME: We should really be rebuilding the default argument with new
3533 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003534 // We don't need to do that with block decls, though, because
3535 // blocks in default argument expression can never capture anything.
3536 if (isa<ExprWithCleanups>(Param->getInit())) {
3537 // Set the "needs cleanups" bit regardless of whether there are
3538 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003539 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003540
3541 // Append all the objects to the cleanup list. Right now, this
3542 // should always be a no-op, because blocks in default argument
3543 // expressions should never be able to capture anything.
3544 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3545 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003546 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003547
3548 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003549 // Just mark all of the declarations in this potentially-evaluated expression
3550 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003551 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3552 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003553 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003554}
3555
Richard Smith831421f2012-06-25 20:30:08 +00003556
3557Sema::VariadicCallType
3558Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3559 Expr *Fn) {
3560 if (Proto && Proto->isVariadic()) {
3561 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3562 return VariadicConstructor;
3563 else if (Fn && Fn->getType()->isBlockPointerType())
3564 return VariadicBlock;
3565 else if (FDecl) {
3566 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3567 if (Method->isInstance())
3568 return VariadicMethod;
3569 }
3570 return VariadicFunction;
3571 }
3572 return VariadicDoesNotApply;
3573}
3574
Douglas Gregor88a35142008-12-22 05:46:06 +00003575/// ConvertArgumentsForCall - Converts the arguments specified in
3576/// Args/NumArgs to the parameter types of the function FDecl with
3577/// function prototype Proto. Call is the call expression itself, and
3578/// Fn is the function expression. For a C++ member function, this
3579/// routine does not attempt to convert the object argument. Returns
3580/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003581bool
3582Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003583 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003584 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003585 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003586 SourceLocation RParenLoc,
3587 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003588 // Bail out early if calling a builtin with custom typechecking.
3589 // We don't need to do this in the
3590 if (FDecl)
3591 if (unsigned ID = FDecl->getBuiltinID())
3592 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3593 return false;
3594
Mike Stumpeed9cac2009-02-19 03:04:26 +00003595 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003596 // assignment, to the types of the corresponding parameter, ...
3597 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003598 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003599 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003600 unsigned FnKind = Fn->getType()->isBlockPointerType()
3601 ? 1 /* block */
3602 : (IsExecConfig ? 3 /* kernel function (exec config) */
3603 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003604
Douglas Gregor88a35142008-12-22 05:46:06 +00003605 // If too few arguments are available (and we don't have default
3606 // arguments for the remaining parameters), don't make the call.
3607 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003608 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003609 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3610 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3611 ? diag::err_typecheck_call_too_few_args_one
3612 : diag::err_typecheck_call_too_few_args_at_least_one)
3613 << FnKind
3614 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3615 else
3616 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3617 ? diag::err_typecheck_call_too_few_args
3618 : diag::err_typecheck_call_too_few_args_at_least)
3619 << FnKind
3620 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003621
3622 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003623 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003624 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3625 << FDecl;
3626
3627 return true;
3628 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003629 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003630 }
3631
3632 // If too many are passed and not variadic, error on the extras and drop
3633 // them.
3634 if (NumArgs > NumArgsInProto) {
3635 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003636 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3637 Diag(Args[NumArgsInProto]->getLocStart(),
3638 MinArgs == NumArgsInProto
3639 ? diag::err_typecheck_call_too_many_args_one
3640 : diag::err_typecheck_call_too_many_args_at_most_one)
3641 << FnKind
3642 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3643 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3644 Args[NumArgs-1]->getLocEnd());
3645 else
3646 Diag(Args[NumArgsInProto]->getLocStart(),
3647 MinArgs == NumArgsInProto
3648 ? diag::err_typecheck_call_too_many_args
3649 : diag::err_typecheck_call_too_many_args_at_most)
3650 << FnKind
3651 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3652 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3653 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003654
3655 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003656 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003657 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3658 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003659
Douglas Gregor88a35142008-12-22 05:46:06 +00003660 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003661 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003662 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003663 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003664 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003665 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003666 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3667
Daniel Dunbar96a00142012-03-09 18:35:03 +00003668 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003669 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003670 if (Invalid)
3671 return true;
3672 unsigned TotalNumArgs = AllArgs.size();
3673 for (unsigned i = 0; i < TotalNumArgs; ++i)
3674 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003675
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003676 return false;
3677}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003678
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003679bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3680 FunctionDecl *FDecl,
3681 const FunctionProtoType *Proto,
3682 unsigned FirstProtoArg,
3683 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003684 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003685 VariadicCallType CallType,
3686 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003687 unsigned NumArgsInProto = Proto->getNumArgs();
3688 unsigned NumArgsToCheck = NumArgs;
3689 bool Invalid = false;
3690 if (NumArgs != NumArgsInProto)
3691 // Use default arguments for missing arguments
3692 NumArgsToCheck = NumArgsInProto;
3693 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003694 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003695 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003696 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003697
Douglas Gregor88a35142008-12-22 05:46:06 +00003698 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003699 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003700 if (ArgIx < NumArgs) {
3701 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003702
Daniel Dunbar96a00142012-03-09 18:35:03 +00003703 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003704 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003705 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003706 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003707
Douglas Gregora188ff22009-12-22 16:09:06 +00003708 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003709 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003710 if (FDecl && i < FDecl->getNumParams())
3711 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003712
John McCall5acb0c92011-10-17 18:40:02 +00003713 // Strip the unbridged-cast placeholder expression off, if applicable.
3714 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3715 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3716 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3717 Arg = stripARCUnbridgedCast(Arg);
3718
Douglas Gregora188ff22009-12-22 16:09:06 +00003719 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003720 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003721 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3722 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003723 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003724 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003725 Owned(Arg),
3726 /*TopLevelOfInitList=*/false,
3727 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003728 if (ArgE.isInvalid())
3729 return true;
3730
3731 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003732 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003733 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003734
John McCall60d7b3a2010-08-24 06:29:42 +00003735 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003736 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003737 if (ArgExpr.isInvalid())
3738 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003739
Anders Carlsson56c5e332009-08-25 03:49:14 +00003740 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003741 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003742
3743 // Check for array bounds violations for each argument to the call. This
3744 // check only triggers warnings when the argument isn't a more complex Expr
3745 // with its own checking, such as a BinaryOperator.
3746 CheckArrayAccess(Arg);
3747
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003748 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3749 CheckStaticArrayArgument(CallLoc, Param, Arg);
3750
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003751 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003752 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003753
Douglas Gregor88a35142008-12-22 05:46:06 +00003754 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003755 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003756 // Assume that extern "C" functions with variadic arguments that
3757 // return __unknown_anytype aren't *really* variadic.
3758 if (Proto->getResultType() == Context.UnknownAnyTy &&
3759 FDecl && FDecl->isExternC()) {
3760 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3761 ExprResult arg;
3762 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3763 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3764 else
3765 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3766 Invalid |= arg.isInvalid();
3767 AllArgs.push_back(arg.take());
3768 }
3769
3770 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3771 } else {
3772 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003773 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3774 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003775 Invalid |= Arg.isInvalid();
3776 AllArgs.push_back(Arg.take());
3777 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003778 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003779
3780 // Check for array bounds violations.
3781 for (unsigned i = ArgIx; i != NumArgs; ++i)
3782 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003783 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003784 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003785}
3786
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003787static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3788 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3789 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3790 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3791 << ATL->getLocalSourceRange();
3792}
3793
3794/// CheckStaticArrayArgument - If the given argument corresponds to a static
3795/// array parameter, check that it is non-null, and that if it is formed by
3796/// array-to-pointer decay, the underlying array is sufficiently large.
3797///
3798/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3799/// array type derivation, then for each call to the function, the value of the
3800/// corresponding actual argument shall provide access to the first element of
3801/// an array with at least as many elements as specified by the size expression.
3802void
3803Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3804 ParmVarDecl *Param,
3805 const Expr *ArgExpr) {
3806 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003807 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003808 return;
3809
3810 QualType OrigTy = Param->getOriginalType();
3811
3812 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3813 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3814 return;
3815
3816 if (ArgExpr->isNullPointerConstant(Context,
3817 Expr::NPC_NeverValueDependent)) {
3818 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3819 DiagnoseCalleeStaticArrayParam(*this, Param);
3820 return;
3821 }
3822
3823 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3824 if (!CAT)
3825 return;
3826
3827 const ConstantArrayType *ArgCAT =
3828 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3829 if (!ArgCAT)
3830 return;
3831
3832 if (ArgCAT->getSize().ult(CAT->getSize())) {
3833 Diag(CallLoc, diag::warn_static_array_too_small)
3834 << ArgExpr->getSourceRange()
3835 << (unsigned) ArgCAT->getSize().getZExtValue()
3836 << (unsigned) CAT->getSize().getZExtValue();
3837 DiagnoseCalleeStaticArrayParam(*this, Param);
3838 }
3839}
3840
John McCall755d8492011-04-12 00:42:48 +00003841/// Given a function expression of unknown-any type, try to rebuild it
3842/// to have a function type.
3843static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3844
Steve Narofff69936d2007-09-16 03:34:24 +00003845/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003846/// This provides the location of the left/right parens and a list of comma
3847/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003848ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003849Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003850 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003851 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003852 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003853 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003854 if (Result.isInvalid()) return ExprError();
3855 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003856
David Blaikie4e4d0842012-03-11 07:00:24 +00003857 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003858 // If this is a pseudo-destructor expression, build the call immediately.
3859 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003860 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003861 // Pseudo-destructor calls should not have any arguments.
3862 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003863 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003864 SourceRange(ArgExprs[0]->getLocStart(),
3865 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003868 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3869 Context.VoidTy, VK_RValue,
3870 RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003871 }
Mike Stump1eb44332009-09-09 15:08:12 +00003872
Douglas Gregor17330012009-02-04 15:01:18 +00003873 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003874 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003875 // FIXME: Will need to cache the results of name lookup (including ADL) in
3876 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003877 bool Dependent = false;
3878 if (Fn->isTypeDependent())
3879 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003880 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00003881 Dependent = true;
3882
Peter Collingbournee08ce652011-02-09 21:07:24 +00003883 if (Dependent) {
3884 if (ExecConfig) {
3885 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003886 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003887 Context.DependentTy, VK_RValue, RParenLoc));
3888 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003889 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003890 Context.DependentTy, VK_RValue,
3891 RParenLoc));
3892 }
3893 }
Douglas Gregor17330012009-02-04 15:01:18 +00003894
3895 // Determine whether this is a call to an object (C++ [over.call.object]).
3896 if (Fn->getType()->isRecordType())
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003897 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3898 ArgExprs.data(),
3899 ArgExprs.size(), RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003900
John McCall755d8492011-04-12 00:42:48 +00003901 if (Fn->getType() == Context.UnknownAnyTy) {
3902 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3903 if (result.isInvalid()) return ExprError();
3904 Fn = result.take();
3905 }
3906
John McCall864c0412011-04-26 20:42:42 +00003907 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003908 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3909 ArgExprs.size(), RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003910 }
John McCall864c0412011-04-26 20:42:42 +00003911 }
John McCall129e2df2009-11-30 22:42:35 +00003912
John McCall864c0412011-04-26 20:42:42 +00003913 // Check for overloaded calls. This can happen even in C due to extensions.
3914 if (Fn->getType() == Context.OverloadTy) {
3915 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3916
Douglas Gregoree697e62011-10-13 18:10:35 +00003917 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003918 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003919 OverloadExpr *ovl = find.Expression;
3920 if (isa<UnresolvedLookupExpr>(ovl)) {
3921 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003922 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3923 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00003924 } else {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003925 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3926 ArgExprs.size(), RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003927 }
3928 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003929 }
3930
Douglas Gregorfa047642009-02-04 00:32:51 +00003931 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003932 if (Fn->getType() == Context.UnknownAnyTy) {
3933 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3934 if (result.isInvalid()) return ExprError();
3935 Fn = result.take();
3936 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003937
Eli Friedmanefa42f72009-12-26 03:35:45 +00003938 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003939
John McCall3b4294e2009-12-16 12:17:52 +00003940 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003941 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3942 if (UnOp->getOpcode() == UO_AddrOf)
3943 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3944
John McCall3b4294e2009-12-16 12:17:52 +00003945 if (isa<DeclRefExpr>(NakedFn))
3946 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003947 else if (isa<MemberExpr>(NakedFn))
3948 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003949
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003950 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3951 ArgExprs.size(), RParenLoc, ExecConfig,
3952 IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003953}
3954
3955ExprResult
3956Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003957 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003958 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3959 if (!ConfigDecl)
3960 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3961 << "cudaConfigureCall");
3962 QualType ConfigQTy = ConfigDecl->getType();
3963
3964 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003965 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003966 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003967
Peter Collingbourne1f240762011-10-02 23:49:29 +00003968 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3969 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003970}
3971
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003972/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3973///
3974/// __builtin_astype( value, dst type )
3975///
Richard Trieuccd891a2011-09-09 01:45:06 +00003976ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003977 SourceLocation BuiltinLoc,
3978 SourceLocation RParenLoc) {
3979 ExprValueKind VK = VK_RValue;
3980 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003981 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3982 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003983 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3984 return ExprError(Diag(BuiltinLoc,
3985 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003986 << DstTy
3987 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003988 << E->getSourceRange());
3989 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003990 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003991}
3992
John McCall3b4294e2009-12-16 12:17:52 +00003993/// BuildResolvedCallExpr - Build a call to a resolved expression,
3994/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003995/// unary-convert to an expression of function-pointer or
3996/// block-pointer type.
3997///
3998/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003999ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004000Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4001 SourceLocation LParenLoc,
4002 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004003 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004004 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00004005 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004006 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00004007
Chris Lattner04421082008-04-08 04:40:51 +00004008 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004009 // We special-case function promotion here because we only allow promoting
4010 // builtin functions to function pointers in the callee of a call.
4011 ExprResult Result;
4012 if (BuiltinID &&
4013 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4014 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4015 CK_BuiltinFnToFnPtr).take();
4016 } else {
4017 Result = UsualUnaryConversions(Fn);
4018 }
John Wiegley429bb272011-04-08 18:41:53 +00004019 if (Result.isInvalid())
4020 return ExprError();
4021 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004022
Chris Lattner925e60d2007-12-28 05:29:59 +00004023 // Make the call expr early, before semantic checks. This guarantees cleanup
4024 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004025 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004026 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004027 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4028 cast<CallExpr>(Config),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004029 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004030 Context.BoolTy,
4031 VK_RValue,
4032 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004033 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00004034 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004035 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbournee08ce652011-02-09 21:07:24 +00004036 Context.BoolTy,
4037 VK_RValue,
4038 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004039
John McCall8e10f3b2011-02-26 05:39:39 +00004040 // Bail out early if calling a builtin with custom typechecking.
4041 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4042 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4043
John McCall1de4d4e2011-04-07 08:22:57 +00004044 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004045 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004046 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004047 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4048 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004049 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004050 if (FuncT == 0)
4051 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4052 << Fn->getType() << Fn->getSourceRange());
4053 } else if (const BlockPointerType *BPT =
4054 Fn->getType()->getAs<BlockPointerType>()) {
4055 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4056 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004057 // Handle calls to expressions of unknown-any type.
4058 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004059 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004060 if (rewrite.isInvalid()) return ExprError();
4061 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00004062 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004063 goto retry;
4064 }
4065
Sebastian Redl0eb23302009-01-19 00:08:26 +00004066 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4067 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004068 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004069
David Blaikie4e4d0842012-03-11 07:00:24 +00004070 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004071 if (Config) {
4072 // CUDA: Kernel calls must be to global functions
4073 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4074 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4075 << FDecl->getName() << Fn->getSourceRange());
4076
4077 // CUDA: Kernel function must have 'void' return type
4078 if (!FuncT->getResultType()->isVoidType())
4079 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4080 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004081 } else {
4082 // CUDA: Calls to global functions must be configured
4083 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4084 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4085 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004086 }
4087 }
4088
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004089 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004090 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004091 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004092 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004093 return ExprError();
4094
Chris Lattner925e60d2007-12-28 05:29:59 +00004095 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004096 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004097 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004098
Richard Smith831421f2012-06-25 20:30:08 +00004099 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4100 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004101 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004102 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004103 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004104 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004105 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004106
Douglas Gregor74734d52009-04-02 15:37:10 +00004107 if (FDecl) {
4108 // Check if we have too few/too many template arguments, based
4109 // on our knowledge of the function definition.
4110 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004111 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004112 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004113 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004114 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4115 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004116 }
Douglas Gregor46542412010-10-25 20:39:23 +00004117
4118 // If the function we're calling isn't a function prototype, but we have
4119 // a function prototype from a prior declaratiom, use that prototype.
4120 if (!FDecl->hasPrototype())
4121 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004122 }
4123
Steve Naroffb291ab62007-08-28 23:30:39 +00004124 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004125 for (unsigned i = 0; i != NumArgs; i++) {
4126 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004127
4128 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004129 InitializedEntity Entity
4130 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004131 Proto->getArgType(i),
4132 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004133 ExprResult ArgE = PerformCopyInitialization(Entity,
4134 SourceLocation(),
4135 Owned(Arg));
4136 if (ArgE.isInvalid())
4137 return true;
4138
4139 Arg = ArgE.takeAs<Expr>();
4140
4141 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004142 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4143
4144 if (ArgE.isInvalid())
4145 return true;
4146
4147 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004148 }
4149
Daniel Dunbar96a00142012-03-09 18:35:03 +00004150 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004151 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004152 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004153 return ExprError();
4154
Chris Lattner925e60d2007-12-28 05:29:59 +00004155 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004156 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004157 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004158
Douglas Gregor88a35142008-12-22 05:46:06 +00004159 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4160 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004161 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4162 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004163
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004164 // Check for sentinels
4165 if (NDecl)
4166 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Chris Lattner59907c42007-08-10 20:18:51 +00004168 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004169 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004170 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004171 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004172
John McCall8e10f3b2011-02-26 05:39:39 +00004173 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004174 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004175 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004176 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004177 return ExprError();
4178 }
Chris Lattner59907c42007-08-10 20:18:51 +00004179
John McCall9ae2f072010-08-23 23:25:46 +00004180 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004181}
4182
John McCall60d7b3a2010-08-24 06:29:42 +00004183ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004184Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004185 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004186 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004187 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004188 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004189
4190 TypeSourceInfo *TInfo;
4191 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4192 if (!TInfo)
4193 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4194
John McCall9ae2f072010-08-23 23:25:46 +00004195 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004196}
4197
John McCall60d7b3a2010-08-24 06:29:42 +00004198ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004199Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004200 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004201 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004202
Eli Friedman6223c222008-05-20 05:22:08 +00004203 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004204 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004205 diag::err_illegal_decl_array_incomplete_type,
4206 SourceRange(LParenLoc,
4207 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004208 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004209 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004210 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004211 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004212 } else if (!literalType->isDependentType() &&
4213 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004214 diag::err_typecheck_decl_incomplete_type,
4215 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004216 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004217
Douglas Gregor99a2e602009-12-16 01:38:02 +00004218 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004219 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004220 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004221 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004222 SourceRange(LParenLoc, RParenLoc),
4223 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004224 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004225 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4226 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004227 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004228 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004229 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004230
Chris Lattner371f2582008-12-04 23:50:19 +00004231 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004232 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004233 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004234 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004235 }
Eli Friedman08544622009-12-22 02:35:53 +00004236
John McCallf89e55a2010-11-18 06:31:45 +00004237 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004238 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004239
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004240 return MaybeBindToTemporary(
4241 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004242 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004243}
4244
John McCall60d7b3a2010-08-24 06:29:42 +00004245ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004246Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004247 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00004248 // Immediately handle non-overload placeholders. Overloads can be
4249 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004250 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4251 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4252 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00004253
4254 // Ignore failures; dropping the entire initializer list because
4255 // of one failure would be terrible for indexing/etc.
4256 if (result.isInvalid()) continue;
4257
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004258 InitArgList[I] = result.take();
John McCall3c3b7f92011-10-25 17:37:35 +00004259 }
4260 }
4261
Steve Naroff08d92e42007-09-15 18:49:24 +00004262 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004263 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004264
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004265 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4266 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004267 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004268 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004269}
4270
John McCalldc05b112011-09-10 01:16:55 +00004271/// Do an explicit extend of the given block pointer if we're in ARC.
4272static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4273 assert(E.get()->getType()->isBlockPointerType());
4274 assert(E.get()->isRValue());
4275
4276 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004277 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004278
4279 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004280 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004281 /*base path*/ 0, VK_RValue);
4282 S.ExprNeedsCleanups = true;
4283}
4284
4285/// Prepare a conversion of the given expression to an ObjC object
4286/// pointer type.
4287CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4288 QualType type = E.get()->getType();
4289 if (type->isObjCObjectPointerType()) {
4290 return CK_BitCast;
4291 } else if (type->isBlockPointerType()) {
4292 maybeExtendBlockObject(*this, E);
4293 return CK_BlockPointerToObjCPointerCast;
4294 } else {
4295 assert(type->isPointerType());
4296 return CK_CPointerToObjCPointerCast;
4297 }
4298}
4299
John McCallf3ea8cf2010-11-14 08:17:51 +00004300/// Prepares for a scalar cast, performing all the necessary stages
4301/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004302CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004303 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4304 // Also, callers should have filtered out the invalid cases with
4305 // pointers. Everything else should be possible.
4306
John Wiegley429bb272011-04-08 18:41:53 +00004307 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004308 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004309 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004310
John McCall1d9b3b22011-09-09 05:25:32 +00004311 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004312 case Type::STK_MemberPointer:
4313 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004314
John McCall1d9b3b22011-09-09 05:25:32 +00004315 case Type::STK_CPointer:
4316 case Type::STK_BlockPointer:
4317 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004318 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004319 case Type::STK_CPointer:
4320 return CK_BitCast;
4321 case Type::STK_BlockPointer:
4322 return (SrcKind == Type::STK_BlockPointer
4323 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4324 case Type::STK_ObjCObjectPointer:
4325 if (SrcKind == Type::STK_ObjCObjectPointer)
4326 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004327 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004328 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004329 maybeExtendBlockObject(*this, Src);
4330 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004331 case Type::STK_Bool:
4332 return CK_PointerToBoolean;
4333 case Type::STK_Integral:
4334 return CK_PointerToIntegral;
4335 case Type::STK_Floating:
4336 case Type::STK_FloatingComplex:
4337 case Type::STK_IntegralComplex:
4338 case Type::STK_MemberPointer:
4339 llvm_unreachable("illegal cast from pointer");
4340 }
David Blaikie7530c032012-01-17 06:56:22 +00004341 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004342
John McCalldaa8e4e2010-11-15 09:13:47 +00004343 case Type::STK_Bool: // casting from bool is like casting from an integer
4344 case Type::STK_Integral:
4345 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004346 case Type::STK_CPointer:
4347 case Type::STK_ObjCObjectPointer:
4348 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004349 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004350 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004351 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004352 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004353 case Type::STK_Bool:
4354 return CK_IntegralToBoolean;
4355 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004356 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004357 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004358 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004359 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004360 Src = ImpCastExprToType(Src.take(),
4361 DestTy->castAs<ComplexType>()->getElementType(),
4362 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004363 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004364 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004365 Src = ImpCastExprToType(Src.take(),
4366 DestTy->castAs<ComplexType>()->getElementType(),
4367 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004368 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004369 case Type::STK_MemberPointer:
4370 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004371 }
David Blaikie7530c032012-01-17 06:56:22 +00004372 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004373
John McCalldaa8e4e2010-11-15 09:13:47 +00004374 case Type::STK_Floating:
4375 switch (DestTy->getScalarTypeKind()) {
4376 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004377 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004378 case Type::STK_Bool:
4379 return CK_FloatingToBoolean;
4380 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004381 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004382 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004383 Src = ImpCastExprToType(Src.take(),
4384 DestTy->castAs<ComplexType>()->getElementType(),
4385 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004386 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004387 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004388 Src = ImpCastExprToType(Src.take(),
4389 DestTy->castAs<ComplexType>()->getElementType(),
4390 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004391 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004392 case Type::STK_CPointer:
4393 case Type::STK_ObjCObjectPointer:
4394 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004395 llvm_unreachable("valid float->pointer cast?");
4396 case Type::STK_MemberPointer:
4397 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004398 }
David Blaikie7530c032012-01-17 06:56:22 +00004399 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004400
John McCalldaa8e4e2010-11-15 09:13:47 +00004401 case Type::STK_FloatingComplex:
4402 switch (DestTy->getScalarTypeKind()) {
4403 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004404 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004405 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004406 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004407 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004408 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4409 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004410 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004411 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004412 return CK_FloatingCast;
4413 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004414 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004415 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004416 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004417 Src = ImpCastExprToType(Src.take(),
4418 SrcTy->castAs<ComplexType>()->getElementType(),
4419 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004420 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004421 case Type::STK_CPointer:
4422 case Type::STK_ObjCObjectPointer:
4423 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004424 llvm_unreachable("valid complex float->pointer cast?");
4425 case Type::STK_MemberPointer:
4426 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004427 }
David Blaikie7530c032012-01-17 06:56:22 +00004428 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004429
John McCalldaa8e4e2010-11-15 09:13:47 +00004430 case Type::STK_IntegralComplex:
4431 switch (DestTy->getScalarTypeKind()) {
4432 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004433 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004434 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004435 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004436 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004437 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4438 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004439 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004440 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004441 return CK_IntegralCast;
4442 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004443 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004444 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004445 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004446 Src = ImpCastExprToType(Src.take(),
4447 SrcTy->castAs<ComplexType>()->getElementType(),
4448 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004449 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004450 case Type::STK_CPointer:
4451 case Type::STK_ObjCObjectPointer:
4452 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004453 llvm_unreachable("valid complex int->pointer cast?");
4454 case Type::STK_MemberPointer:
4455 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004456 }
David Blaikie7530c032012-01-17 06:56:22 +00004457 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004458 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004459
John McCallf3ea8cf2010-11-14 08:17:51 +00004460 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004461}
4462
Anders Carlssonc3516322009-10-16 02:48:28 +00004463bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004464 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004465 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004466
Anders Carlssona64db8f2007-11-27 05:51:55 +00004467 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004468 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004469 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004470 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004471 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004472 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004473 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004474 } else
4475 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004476 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004477 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004478
John McCall2de56d12010-08-25 11:45:40 +00004479 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004480 return false;
4481}
4482
John Wiegley429bb272011-04-08 18:41:53 +00004483ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4484 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004485 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004486
Anders Carlsson16a89042009-10-16 05:23:41 +00004487 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004488
Nate Begeman9b10da62009-06-27 22:05:55 +00004489 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4490 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004491 // In OpenCL, casts between vectors of different types are not allowed.
4492 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004493 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004494 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004495 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004496 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004497 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004498 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004499 return ExprError();
4500 }
John McCall2de56d12010-08-25 11:45:40 +00004501 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004502 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004503 }
4504
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004505 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004506 // conversion will take place first from scalar to elt type, and then
4507 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004508 if (SrcTy->isPointerType())
4509 return Diag(R.getBegin(),
4510 diag::err_invalid_conversion_between_vector_and_scalar)
4511 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004512
4513 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004514 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004515 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004516 if (CastExprRes.isInvalid())
4517 return ExprError();
4518 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004519
John McCall2de56d12010-08-25 11:45:40 +00004520 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004521 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004522}
4523
John McCall60d7b3a2010-08-24 06:29:42 +00004524ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004525Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4526 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004527 SourceLocation RParenLoc, Expr *CastExpr) {
4528 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004529 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004530
Richard Trieuccd891a2011-09-09 01:45:06 +00004531 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004532 if (D.isInvalidType())
4533 return ExprError();
4534
David Blaikie4e4d0842012-03-11 07:00:24 +00004535 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004536 // Check that there are no default arguments (C++ only).
4537 CheckExtraCXXDefaultArguments(D);
4538 }
4539
John McCalle82247a2011-10-01 05:17:03 +00004540 checkUnusedDeclAttributes(D);
4541
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004542 QualType castType = castTInfo->getType();
4543 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004544
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004545 bool isVectorLiteral = false;
4546
4547 // Check for an altivec or OpenCL literal,
4548 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004549 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4550 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004551 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004552 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004553 if (PLE && PLE->getNumExprs() == 0) {
4554 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4555 return ExprError();
4556 }
4557 if (PE || PLE->getNumExprs() == 1) {
4558 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4559 if (!E->getType()->isVectorType())
4560 isVectorLiteral = true;
4561 }
4562 else
4563 isVectorLiteral = true;
4564 }
4565
4566 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4567 // then handle it as such.
4568 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004569 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004570
Nate Begeman2ef13e52009-08-10 23:49:36 +00004571 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004572 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4573 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004574 if (isa<ParenListExpr>(CastExpr)) {
4575 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004576 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004577 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004578 }
John McCallb042fdf2010-01-15 18:56:44 +00004579
Richard Trieuccd891a2011-09-09 01:45:06 +00004580 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004581}
4582
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004583ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4584 SourceLocation RParenLoc, Expr *E,
4585 TypeSourceInfo *TInfo) {
4586 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4587 "Expected paren or paren list expression");
4588
4589 Expr **exprs;
4590 unsigned numExprs;
4591 Expr *subExpr;
4592 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4593 exprs = PE->getExprs();
4594 numExprs = PE->getNumExprs();
4595 } else {
4596 subExpr = cast<ParenExpr>(E)->getSubExpr();
4597 exprs = &subExpr;
4598 numExprs = 1;
4599 }
4600
4601 QualType Ty = TInfo->getType();
4602 assert(Ty->isVectorType() && "Expected vector type");
4603
Chris Lattner5f9e2722011-07-23 10:55:15 +00004604 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004605 const VectorType *VTy = Ty->getAs<VectorType>();
4606 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4607
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004608 // '(...)' form of vector initialization in AltiVec: the number of
4609 // initializers must be one or must match the size of the vector.
4610 // If a single value is specified in the initializer then it will be
4611 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004612 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004613 // The number of initializers must be one or must match the size of the
4614 // vector. If a single value is specified in the initializer then it will
4615 // be replicated to all the components of the vector
4616 if (numExprs == 1) {
4617 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004618 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4619 if (Literal.isInvalid())
4620 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004621 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004622 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004623 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4624 }
4625 else if (numExprs < numElems) {
4626 Diag(E->getExprLoc(),
4627 diag::err_incorrect_number_of_vector_initializers);
4628 return ExprError();
4629 }
4630 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004631 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004632 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004633 else {
4634 // For OpenCL, when the number of initializers is a single value,
4635 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004636 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004637 VTy->getVectorKind() == VectorType::GenericVector &&
4638 numExprs == 1) {
4639 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004640 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4641 if (Literal.isInvalid())
4642 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004643 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004644 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004645 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4646 }
4647
Benjamin Kramer14c59822012-02-14 12:06:21 +00004648 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004649 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004650 // FIXME: This means that pretty-printing the final AST will produce curly
4651 // braces instead of the original commas.
4652 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004653 initExprs, RParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004654 initE->setType(Ty);
4655 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4656}
4657
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004658/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4659/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004660ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004661Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4662 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004663 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004664 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004665
John McCall60d7b3a2010-08-24 06:29:42 +00004666 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004667
Nate Begeman2ef13e52009-08-10 23:49:36 +00004668 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004669 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4670 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004671
John McCall9ae2f072010-08-23 23:25:46 +00004672 if (Result.isInvalid()) return ExprError();
4673
4674 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004675}
4676
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004677ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4678 SourceLocation R,
4679 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004680 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4681 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004682 return Owned(expr);
4683}
4684
Chandler Carruth82214a82011-02-18 23:54:50 +00004685/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004686/// constant and the other is not a pointer. Returns true if a diagnostic is
4687/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004688bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004689 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004690 Expr *NullExpr = LHSExpr;
4691 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004692 Expr::NullPointerConstantKind NullKind =
4693 NullExpr->isNullPointerConstant(Context,
4694 Expr::NPC_ValueDependentIsNotNull);
4695
4696 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004697 NullExpr = RHSExpr;
4698 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004699 NullKind =
4700 NullExpr->isNullPointerConstant(Context,
4701 Expr::NPC_ValueDependentIsNotNull);
4702 }
4703
4704 if (NullKind == Expr::NPCK_NotNull)
4705 return false;
4706
David Blaikie50800fc2012-08-08 17:33:31 +00004707 if (NullKind == Expr::NPCK_ZeroExpression)
4708 return false;
4709
4710 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004711 // In this case, check to make sure that we got here from a "NULL"
4712 // string in the source code.
4713 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004714 SourceLocation loc = NullExpr->getExprLoc();
4715 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004716 return false;
4717 }
4718
4719 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4720 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4721 << NonPointerExpr->getType() << DiagType
4722 << NonPointerExpr->getSourceRange();
4723 return true;
4724}
4725
Richard Trieu26f96072011-09-02 01:51:02 +00004726/// \brief Return false if the condition expression is valid, true otherwise.
4727static bool checkCondition(Sema &S, Expr *Cond) {
4728 QualType CondTy = Cond->getType();
4729
4730 // C99 6.5.15p2
4731 if (CondTy->isScalarType()) return false;
4732
4733 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004734 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004735 return false;
4736
4737 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004738 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004739 diag::err_typecheck_cond_expect_scalar :
4740 diag::err_typecheck_cond_expect_scalar_or_vector)
4741 << CondTy;
4742 return true;
4743}
4744
4745/// \brief Return false if the two expressions can be converted to a vector,
4746/// true otherwise
4747static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4748 ExprResult &RHS,
4749 QualType CondTy) {
4750 // Both operands should be of scalar type.
4751 if (!LHS.get()->getType()->isScalarType()) {
4752 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4753 << CondTy;
4754 return true;
4755 }
4756 if (!RHS.get()->getType()->isScalarType()) {
4757 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4758 << CondTy;
4759 return true;
4760 }
4761
4762 // Implicity convert these scalars to the type of the condition.
4763 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4764 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4765 return false;
4766}
4767
4768/// \brief Handle when one or both operands are void type.
4769static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4770 ExprResult &RHS) {
4771 Expr *LHSExpr = LHS.get();
4772 Expr *RHSExpr = RHS.get();
4773
4774 if (!LHSExpr->getType()->isVoidType())
4775 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4776 << RHSExpr->getSourceRange();
4777 if (!RHSExpr->getType()->isVoidType())
4778 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4779 << LHSExpr->getSourceRange();
4780 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4781 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4782 return S.Context.VoidTy;
4783}
4784
4785/// \brief Return false if the NullExpr can be promoted to PointerTy,
4786/// true otherwise.
4787static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4788 QualType PointerTy) {
4789 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4790 !NullExpr.get()->isNullPointerConstant(S.Context,
4791 Expr::NPC_ValueDependentIsNull))
4792 return true;
4793
4794 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4795 return false;
4796}
4797
4798/// \brief Checks compatibility between two pointers and return the resulting
4799/// type.
4800static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4801 ExprResult &RHS,
4802 SourceLocation Loc) {
4803 QualType LHSTy = LHS.get()->getType();
4804 QualType RHSTy = RHS.get()->getType();
4805
4806 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4807 // Two identical pointers types are always compatible.
4808 return LHSTy;
4809 }
4810
4811 QualType lhptee, rhptee;
4812
4813 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004814 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4815 lhptee = LHSBTy->getPointeeType();
4816 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004817 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004818 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4819 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004820 }
4821
Eli Friedmanae916a12012-04-05 22:30:04 +00004822 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4823 // differently qualified versions of compatible types, the result type is
4824 // a pointer to an appropriately qualified version of the composite
4825 // type.
4826
4827 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4828 // clause doesn't make sense for our extensions. E.g. address space 2 should
4829 // be incompatible with address space 3: they may live on different devices or
4830 // anything.
4831 Qualifiers lhQual = lhptee.getQualifiers();
4832 Qualifiers rhQual = rhptee.getQualifiers();
4833
4834 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4835 lhQual.removeCVRQualifiers();
4836 rhQual.removeCVRQualifiers();
4837
4838 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4839 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4840
4841 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4842
4843 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004844 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4845 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4846 << RHS.get()->getSourceRange();
4847 // In this situation, we assume void* type. No especially good
4848 // reason, but this is what gcc does, and we do have to pick
4849 // to get a consistent AST.
4850 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4851 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4852 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4853 return incompatTy;
4854 }
4855
4856 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004857 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4858 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004859
Eli Friedmanae916a12012-04-05 22:30:04 +00004860 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4861 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4862 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004863}
4864
4865/// \brief Return the resulting type when the operands are both block pointers.
4866static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4867 ExprResult &LHS,
4868 ExprResult &RHS,
4869 SourceLocation Loc) {
4870 QualType LHSTy = LHS.get()->getType();
4871 QualType RHSTy = RHS.get()->getType();
4872
4873 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4874 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4875 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4876 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4877 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4878 return destType;
4879 }
4880 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4881 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4882 << RHS.get()->getSourceRange();
4883 return QualType();
4884 }
4885
4886 // We have 2 block pointer types.
4887 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4888}
4889
4890/// \brief Return the resulting type when the operands are both pointers.
4891static QualType
4892checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4893 ExprResult &RHS,
4894 SourceLocation Loc) {
4895 // get the pointer types
4896 QualType LHSTy = LHS.get()->getType();
4897 QualType RHSTy = RHS.get()->getType();
4898
4899 // get the "pointed to" types
4900 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4901 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4902
4903 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4904 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4905 // Figure out necessary qualifiers (C99 6.5.15p6)
4906 QualType destPointee
4907 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4908 QualType destType = S.Context.getPointerType(destPointee);
4909 // Add qualifiers if necessary.
4910 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4911 // Promote to void*.
4912 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4913 return destType;
4914 }
4915 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4916 QualType destPointee
4917 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4918 QualType destType = S.Context.getPointerType(destPointee);
4919 // Add qualifiers if necessary.
4920 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4921 // Promote to void*.
4922 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4923 return destType;
4924 }
4925
4926 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4927}
4928
4929/// \brief Return false if the first expression is not an integer and the second
4930/// expression is not a pointer, true otherwise.
4931static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4932 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004933 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004934 if (!PointerExpr->getType()->isPointerType() ||
4935 !Int.get()->getType()->isIntegerType())
4936 return false;
4937
Richard Trieuccd891a2011-09-09 01:45:06 +00004938 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4939 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004940
4941 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4942 << Expr1->getType() << Expr2->getType()
4943 << Expr1->getSourceRange() << Expr2->getSourceRange();
4944 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4945 CK_IntegralToPointer);
4946 return true;
4947}
4948
Richard Trieu33fc7572011-09-06 20:06:39 +00004949/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4950/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004951/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004952QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4953 ExprResult &RHS, ExprValueKind &VK,
4954 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004955 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004956
Richard Trieu33fc7572011-09-06 20:06:39 +00004957 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4958 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004959 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004960
Richard Trieu33fc7572011-09-06 20:06:39 +00004961 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4962 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004963 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004964
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004965 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004966 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004967 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004968
4969 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004970 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004971
John Wiegley429bb272011-04-08 18:41:53 +00004972 Cond = UsualUnaryConversions(Cond.take());
4973 if (Cond.isInvalid())
4974 return QualType();
4975 LHS = UsualUnaryConversions(LHS.take());
4976 if (LHS.isInvalid())
4977 return QualType();
4978 RHS = UsualUnaryConversions(RHS.take());
4979 if (RHS.isInvalid())
4980 return QualType();
4981
4982 QualType CondTy = Cond.get()->getType();
4983 QualType LHSTy = LHS.get()->getType();
4984 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004985
Reid Spencer5f016e22007-07-11 17:01:13 +00004986 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004987 if (checkCondition(*this, Cond.get()))
4988 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004989
Chris Lattner70d67a92008-01-06 22:42:25 +00004990 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004991 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004992 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004993
Nate Begeman6155d732010-09-20 22:41:17 +00004994 // OpenCL: If the condition is a vector, and both operands are scalar,
4995 // attempt to implicity convert them to the vector type to act like the
4996 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004997 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004998 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004999 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00005000
Chris Lattner70d67a92008-01-06 22:42:25 +00005001 // If both operands have arithmetic type, do the usual arithmetic conversions
5002 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005003 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5004 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005005 if (LHS.isInvalid() || RHS.isInvalid())
5006 return QualType();
5007 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005008 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005009
Chris Lattner70d67a92008-01-06 22:42:25 +00005010 // If both operands are the same structure or union type, the result is that
5011 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005012 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5013 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005014 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005015 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005016 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005017 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005018 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005019 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005020
Chris Lattner70d67a92008-01-06 22:42:25 +00005021 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005022 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005023 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00005024 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00005025 }
Richard Trieu26f96072011-09-02 01:51:02 +00005026
Steve Naroffb6d54e52008-01-08 01:11:38 +00005027 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5028 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00005029 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5030 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005031
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005032 // All objective-c pointer type analysis is done here.
5033 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5034 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005035 if (LHS.isInvalid() || RHS.isInvalid())
5036 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005037 if (!compositeType.isNull())
5038 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005039
5040
Steve Naroff7154a772009-07-01 14:36:47 +00005041 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00005042 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5043 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5044 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005045
Steve Naroff7154a772009-07-01 14:36:47 +00005046 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00005047 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5048 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5049 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005050
John McCall404cd162010-11-13 01:35:44 +00005051 // GCC compatibility: soften pointer/integer mismatch. Note that
5052 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00005053 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5054 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00005055 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005056 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5057 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00005058 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005059
Chandler Carruth82214a82011-02-18 23:54:50 +00005060 // Emit a better diagnostic if one of the expressions is a null pointer
5061 // constant and the other is not a pointer type. In this case, the user most
5062 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005063 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005064 return QualType();
5065
Chris Lattner70d67a92008-01-06 22:42:25 +00005066 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005067 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00005068 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5069 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005070 return QualType();
5071}
5072
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005073/// FindCompositeObjCPointerType - Helper method to find composite type of
5074/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005075QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005076 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005077 QualType LHSTy = LHS.get()->getType();
5078 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005079
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005080 // Handle things like Class and struct objc_class*. Here we case the result
5081 // to the pseudo-builtin, because that will be implicitly cast back to the
5082 // redefinition type if an attempt is made to access its fields.
5083 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005084 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005085 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005086 return LHSTy;
5087 }
5088 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005089 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005090 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005091 return RHSTy;
5092 }
5093 // And the same for struct objc_object* / id
5094 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005095 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005096 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005097 return LHSTy;
5098 }
5099 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005100 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005101 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005102 return RHSTy;
5103 }
5104 // And the same for struct objc_selector* / SEL
5105 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005106 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005107 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005108 return LHSTy;
5109 }
5110 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005111 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005112 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005113 return RHSTy;
5114 }
5115 // Check constraints for Objective-C object pointers types.
5116 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005117
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005118 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5119 // Two identical object pointer types are always compatible.
5120 return LHSTy;
5121 }
John McCall1d9b3b22011-09-09 05:25:32 +00005122 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5123 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005124 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005125
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005126 // If both operands are interfaces and either operand can be
5127 // assigned to the other, use that type as the composite
5128 // type. This allows
5129 // xxx ? (A*) a : (B*) b
5130 // where B is a subclass of A.
5131 //
5132 // Additionally, as for assignment, if either type is 'id'
5133 // allow silent coercion. Finally, if the types are
5134 // incompatible then make sure to use 'id' as the composite
5135 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005136
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005137 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5138 // It could return the composite type.
5139 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5140 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5141 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5142 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5143 } else if ((LHSTy->isObjCQualifiedIdType() ||
5144 RHSTy->isObjCQualifiedIdType()) &&
5145 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5146 // Need to handle "id<xx>" explicitly.
5147 // GCC allows qualified id and any Objective-C type to devolve to
5148 // id. Currently localizing to here until clear this should be
5149 // part of ObjCQualifiedIdTypesAreCompatible.
5150 compositeType = Context.getObjCIdType();
5151 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5152 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005153 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005154 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5155 ;
5156 else {
5157 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5158 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005159 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005160 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005161 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5162 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005163 return incompatTy;
5164 }
5165 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005166 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5167 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005168 return compositeType;
5169 }
5170 // Check Objective-C object pointer types and 'void *'
5171 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005172 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005173 // ARC forbids the implicit conversion of object pointers to 'void *',
5174 // so these types are not compatible.
5175 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5176 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5177 LHS = RHS = true;
5178 return QualType();
5179 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005180 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5181 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5182 QualType destPointee
5183 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5184 QualType destType = Context.getPointerType(destPointee);
5185 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005186 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005187 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005188 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005189 return destType;
5190 }
5191 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005192 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005193 // ARC forbids the implicit conversion of object pointers to 'void *',
5194 // so these types are not compatible.
5195 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5196 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5197 LHS = RHS = true;
5198 return QualType();
5199 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005200 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5201 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5202 QualType destPointee
5203 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5204 QualType destType = Context.getPointerType(destPointee);
5205 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005206 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005207 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005208 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005209 return destType;
5210 }
5211 return QualType();
5212}
5213
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005214/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005215/// ParenRange in parentheses.
5216static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005217 const PartialDiagnostic &Note,
5218 SourceRange ParenRange) {
5219 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5220 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5221 EndLoc.isValid()) {
5222 Self.Diag(Loc, Note)
5223 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5224 << FixItHint::CreateInsertion(EndLoc, ")");
5225 } else {
5226 // We can't display the parentheses, so just show the bare note.
5227 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005228 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005229}
5230
5231static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5232 return Opc >= BO_Mul && Opc <= BO_Shr;
5233}
5234
Hans Wennborg2f072b42011-06-09 17:06:51 +00005235/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5236/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005237/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5238/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005239static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005240 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005241 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5242 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005243 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005244 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005245
5246 // Built-in binary operator.
5247 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5248 if (IsArithmeticOp(OP->getOpcode())) {
5249 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005250 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005251 return true;
5252 }
5253 }
5254
5255 // Overloaded operator.
5256 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5257 if (Call->getNumArgs() != 2)
5258 return false;
5259
5260 // Make sure this is really a binary operator that is safe to pass into
5261 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5262 OverloadedOperatorKind OO = Call->getOperator();
5263 if (OO < OO_Plus || OO > OO_Arrow)
5264 return false;
5265
5266 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5267 if (IsArithmeticOp(OpKind)) {
5268 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005269 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005270 return true;
5271 }
5272 }
5273
5274 return false;
5275}
5276
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005277static bool IsLogicOp(BinaryOperatorKind Opc) {
5278 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5279}
5280
Hans Wennborg2f072b42011-06-09 17:06:51 +00005281/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5282/// or is a logical expression such as (x==y) which has int type, but is
5283/// commonly interpreted as boolean.
5284static bool ExprLooksBoolean(Expr *E) {
5285 E = E->IgnoreParenImpCasts();
5286
5287 if (E->getType()->isBooleanType())
5288 return true;
5289 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5290 return IsLogicOp(OP->getOpcode());
5291 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5292 return OP->getOpcode() == UO_LNot;
5293
5294 return false;
5295}
5296
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005297/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5298/// and binary operator are mixed in a way that suggests the programmer assumed
5299/// the conditional operator has higher precedence, for example:
5300/// "int x = a + someBinaryCondition ? 1 : 2".
5301static void DiagnoseConditionalPrecedence(Sema &Self,
5302 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005303 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005304 Expr *LHSExpr,
5305 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005306 BinaryOperatorKind CondOpcode;
5307 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005308
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005309 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005310 return;
5311 if (!ExprLooksBoolean(CondRHS))
5312 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005313
Hans Wennborg2f072b42011-06-09 17:06:51 +00005314 // The condition is an arithmetic binary expression, with a right-
5315 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005316
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005317 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005318 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005319 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005320
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005321 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00005322 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005323 << BinaryOperator::getOpcodeStr(CondOpcode),
5324 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005325
5326 SuggestParentheses(Self, OpLoc,
5327 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005328 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005329}
5330
Steve Narofff69936d2007-09-16 03:34:24 +00005331/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005332/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005333ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005334 SourceLocation ColonLoc,
5335 Expr *CondExpr, Expr *LHSExpr,
5336 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005337 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5338 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005339 OpaqueValueExpr *opaqueValue = 0;
5340 Expr *commonExpr = 0;
5341 if (LHSExpr == 0) {
5342 commonExpr = CondExpr;
5343
5344 // We usually want to apply unary conversions *before* saving, except
5345 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005346 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005347 && !commonExpr->isTypeDependent()
5348 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5349 && commonExpr->isGLValue()
5350 && commonExpr->isOrdinaryOrBitFieldObject()
5351 && RHSExpr->isOrdinaryOrBitFieldObject()
5352 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005353 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5354 if (commonRes.isInvalid())
5355 return ExprError();
5356 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005357 }
5358
5359 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5360 commonExpr->getType(),
5361 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005362 commonExpr->getObjectKind(),
5363 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005364 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005365 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005366
John McCallf89e55a2010-11-18 06:31:45 +00005367 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005368 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005369 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5370 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005371 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005372 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5373 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005374 return ExprError();
5375
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005376 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5377 RHS.get());
5378
John McCall56ca35d2011-02-17 10:25:35 +00005379 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005380 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5381 LHS.take(), ColonLoc,
5382 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005383
5384 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005385 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005386 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5387 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005388}
5389
John McCalle4be87e2011-01-31 23:13:11 +00005390// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005391// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005392// routine is it effectively iqnores the qualifiers on the top level pointee.
5393// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5394// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005395static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005396checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5397 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5398 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005399
Reid Spencer5f016e22007-07-11 17:01:13 +00005400 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005401 const Type *lhptee, *rhptee;
5402 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005403 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5404 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005405
John McCalle4be87e2011-01-31 23:13:11 +00005406 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005407
5408 // C99 6.5.16.1p1: This following citation is common to constraints
5409 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5410 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005411 Qualifiers lq;
5412
John McCallf85e1932011-06-15 23:02:42 +00005413 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5414 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5415 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5416 // Ignore lifetime for further calculation.
5417 lhq.removeObjCLifetime();
5418 rhq.removeObjCLifetime();
5419 }
5420
John McCall86c05f32011-02-01 00:10:29 +00005421 if (!lhq.compatiblyIncludes(rhq)) {
5422 // Treat address-space mismatches as fatal. TODO: address subspaces
5423 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5424 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5425
John McCallf85e1932011-06-15 23:02:42 +00005426 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005427 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005428 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005429 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005430 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005431 && (lhptee->isVoidType() || rhptee->isVoidType()))
5432 ; // keep old
5433
John McCallf85e1932011-06-15 23:02:42 +00005434 // Treat lifetime mismatches as fatal.
5435 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5436 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5437
John McCall86c05f32011-02-01 00:10:29 +00005438 // For GCC compatibility, other qualifier mismatches are treated
5439 // as still compatible in C.
5440 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5441 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005442
Mike Stumpeed9cac2009-02-19 03:04:26 +00005443 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5444 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005445 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005446 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005447 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005448 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005449
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005450 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005451 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005452 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005453 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005454
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005455 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005456 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005457 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005458
5459 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005460 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005461 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005462 }
John McCall86c05f32011-02-01 00:10:29 +00005463
Mike Stumpeed9cac2009-02-19 03:04:26 +00005464 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005465 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005466 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5467 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005468 // Check if the pointee types are compatible ignoring the sign.
5469 // We explicitly check for char so that we catch "char" vs
5470 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005471 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005472 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005473 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005474 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005475
Chris Lattner6a2b9262009-10-17 20:33:28 +00005476 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005477 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005478 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005479 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005480
John McCall86c05f32011-02-01 00:10:29 +00005481 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005482 // Types are compatible ignoring the sign. Qualifier incompatibility
5483 // takes priority over sign incompatibility because the sign
5484 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005485 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005486 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005487
John McCalle4be87e2011-01-31 23:13:11 +00005488 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005489 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005490
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005491 // If we are a multi-level pointer, it's possible that our issue is simply
5492 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5493 // the eventual target type is the same and the pointers have the same
5494 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005495 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005496 do {
John McCall86c05f32011-02-01 00:10:29 +00005497 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5498 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005499 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005500
John McCall86c05f32011-02-01 00:10:29 +00005501 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005502 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005503 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005504
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005505 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005506 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005507 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005508 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005509 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5510 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005511 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005512}
5513
John McCalle4be87e2011-01-31 23:13:11 +00005514/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005515/// block pointer types are compatible or whether a block and normal pointer
5516/// are compatible. It is more restrict than comparing two function pointer
5517// types.
John McCalle4be87e2011-01-31 23:13:11 +00005518static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005519checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5520 QualType RHSType) {
5521 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5522 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005523
Steve Naroff1c7d0672008-09-04 15:10:53 +00005524 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005525
Steve Naroff1c7d0672008-09-04 15:10:53 +00005526 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005527 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5528 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005529
John McCalle4be87e2011-01-31 23:13:11 +00005530 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005531 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005532 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005533
John McCalle4be87e2011-01-31 23:13:11 +00005534 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005535
Steve Naroff1c7d0672008-09-04 15:10:53 +00005536 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005537 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5538 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005539
Richard Trieu1da27a12011-09-06 20:21:22 +00005540 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005541 return Sema::IncompatibleBlockPointer;
5542
Steve Naroff1c7d0672008-09-04 15:10:53 +00005543 return ConvTy;
5544}
5545
John McCalle4be87e2011-01-31 23:13:11 +00005546/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005547/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005548static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005549checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5550 QualType RHSType) {
5551 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5552 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005553
Richard Trieu1da27a12011-09-06 20:21:22 +00005554 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005555 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005556 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5557 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005558 return Sema::IncompatiblePointer;
5559 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005560 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005561 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005562 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5563 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005564 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005565 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005566 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005567 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5568 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005569
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005570 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5571 // make an exception for id<P>
5572 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005573 return Sema::CompatiblePointerDiscardsQualifiers;
5574
Richard Trieu1da27a12011-09-06 20:21:22 +00005575 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005576 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005577 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005578 return Sema::IncompatibleObjCQualifiedId;
5579 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005580}
5581
John McCall1c23e912010-11-16 02:32:08 +00005582Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005583Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005584 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005585 // Fake up an opaque expression. We don't actually care about what
5586 // cast operations are required, so if CheckAssignmentConstraints
5587 // adds casts to this they'll be wasted, but fortunately that doesn't
5588 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005589 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5590 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005591 CastKind K = CK_Invalid;
5592
Richard Trieu1da27a12011-09-06 20:21:22 +00005593 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005594}
5595
Mike Stumpeed9cac2009-02-19 03:04:26 +00005596/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5597/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005598/// pointers. Here are some objectionable examples that GCC considers warnings:
5599///
5600/// int a, *pint;
5601/// short *pshort;
5602/// struct foo *pfoo;
5603///
5604/// pint = pshort; // warning: assignment from incompatible pointer type
5605/// a = pint; // warning: assignment makes integer from pointer without a cast
5606/// pint = a; // warning: assignment makes pointer from integer without a cast
5607/// pint = pfoo; // warning: assignment from incompatible pointer type
5608///
5609/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005610/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005611///
John McCalldaa8e4e2010-11-15 09:13:47 +00005612/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005613Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005614Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005615 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005616 QualType RHSType = RHS.get()->getType();
5617 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005618
Chris Lattnerfc144e22008-01-04 23:18:45 +00005619 // Get canonical types. We're not formatting these types, just comparing
5620 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005621 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5622 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005623
Eli Friedmanb001de72011-10-06 23:00:33 +00005624
John McCallb6cfa242011-01-31 22:28:28 +00005625 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005626 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005627 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005628 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005629 }
5630
Eli Friedman860a3192012-06-16 02:19:17 +00005631 // If we have an atomic type, try a non-atomic assignment, then just add an
5632 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005633 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005634 Sema::AssignConvertType result =
5635 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5636 if (result != Compatible)
5637 return result;
5638 if (Kind != CK_NoOp)
5639 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5640 Kind = CK_NonAtomicToAtomic;
5641 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005642 }
5643
Douglas Gregor9d293df2008-10-28 00:22:11 +00005644 // If the left-hand side is a reference type, then we are in a
5645 // (rare!) case where we've allowed the use of references in C,
5646 // e.g., as a parameter type in a built-in function. In this case,
5647 // just make sure that the type referenced is compatible with the
5648 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005649 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005650 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005651 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5652 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005653 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005654 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005655 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005656 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005657 }
John McCallb6cfa242011-01-31 22:28:28 +00005658
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005659 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5660 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005661 if (LHSType->isExtVectorType()) {
5662 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005663 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005664 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005665 // CK_VectorSplat does T -> vector T, so first cast to the
5666 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005667 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5668 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005669 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005670 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005671 }
5672 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005673 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005674 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005675 }
Mike Stump1eb44332009-09-09 15:08:12 +00005676
John McCallb6cfa242011-01-31 22:28:28 +00005677 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005678 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5679 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005680 // Allow assignments of an AltiVec vector type to an equivalent GCC
5681 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005682 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005683 Kind = CK_BitCast;
5684 return Compatible;
5685 }
5686
Douglas Gregor255210e2010-08-06 10:14:59 +00005687 // If we are allowing lax vector conversions, and LHS and RHS are both
5688 // vectors, the total size only needs to be the same. This is a bitcast;
5689 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005690 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005691 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005692 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005693 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005694 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005695 }
5696 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005697 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005698
John McCallb6cfa242011-01-31 22:28:28 +00005699 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005700 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005701 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005702 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005703 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005704 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005705
John McCallb6cfa242011-01-31 22:28:28 +00005706 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005707 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005708 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005709 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005710 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005711 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005712 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005713
John McCallb6cfa242011-01-31 22:28:28 +00005714 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005715 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005716 Kind = CK_IntegralToPointer; // FIXME: null?
5717 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005718 }
John McCallb6cfa242011-01-31 22:28:28 +00005719
5720 // C pointers are not compatible with ObjC object pointers,
5721 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005722 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005723 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005724 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005725 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005726 return Compatible;
5727 }
5728
5729 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005730 if (RHSType->isObjCClassType() &&
5731 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005732 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005733 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005734 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005735 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005736
John McCallb6cfa242011-01-31 22:28:28 +00005737 Kind = CK_BitCast;
5738 return IncompatiblePointer;
5739 }
5740
5741 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005742 if (RHSType->getAs<BlockPointerType>()) {
5743 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005744 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005745 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005746 }
Steve Naroffb4406862008-09-29 18:10:17 +00005747 }
John McCallb6cfa242011-01-31 22:28:28 +00005748
Steve Naroff1c7d0672008-09-04 15:10:53 +00005749 return Incompatible;
5750 }
5751
John McCallb6cfa242011-01-31 22:28:28 +00005752 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005753 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005754 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005755 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005756 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005757 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005758 }
5759
5760 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005761 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005762 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005763 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005764 }
5765
John McCallb6cfa242011-01-31 22:28:28 +00005766 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005767 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005768 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005769 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005770 }
Steve Naroffb4406862008-09-29 18:10:17 +00005771
John McCallb6cfa242011-01-31 22:28:28 +00005772 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005773 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005774 if (RHSPT->getPointeeType()->isVoidType()) {
5775 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005776 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005777 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005778
Chris Lattnerfc144e22008-01-04 23:18:45 +00005779 return Incompatible;
5780 }
5781
John McCallb6cfa242011-01-31 22:28:28 +00005782 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005783 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005784 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005785 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005786 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005787 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005788 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005789 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005790 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005791 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005792 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005793 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005794 }
5795
5796 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005797 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005798 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005799 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005800 }
5801
John McCallb6cfa242011-01-31 22:28:28 +00005802 // In general, C pointers are not compatible with ObjC object pointers,
5803 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005804 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005805 Kind = CK_CPointerToObjCPointerCast;
5806
John McCallb6cfa242011-01-31 22:28:28 +00005807 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005808 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005809 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005810 }
5811
5812 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005813 if (LHSType->isObjCClassType() &&
5814 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005815 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005816 return Compatible;
5817 }
5818
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005819 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005820 }
John McCallb6cfa242011-01-31 22:28:28 +00005821
5822 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005823 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005824 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005825 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005826 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005827 }
5828
Steve Naroff14108da2009-07-10 23:34:53 +00005829 return Incompatible;
5830 }
John McCallb6cfa242011-01-31 22:28:28 +00005831
5832 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005833 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005834 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005835 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005836 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005837 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005838 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005839
John McCallb6cfa242011-01-31 22:28:28 +00005840 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005841 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005842 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005843 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005844 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005845
Chris Lattnerfc144e22008-01-04 23:18:45 +00005846 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005847 }
John McCallb6cfa242011-01-31 22:28:28 +00005848
5849 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005850 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005851 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005852 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005853 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005854 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005855 }
Steve Naroff14108da2009-07-10 23:34:53 +00005856
John McCallb6cfa242011-01-31 22:28:28 +00005857 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005858 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005859 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005860 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005861 }
5862
Steve Naroff14108da2009-07-10 23:34:53 +00005863 return Incompatible;
5864 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005865
John McCallb6cfa242011-01-31 22:28:28 +00005866 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005867 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5868 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005869 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005870 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005871 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005872 }
John McCallb6cfa242011-01-31 22:28:28 +00005873
Reid Spencer5f016e22007-07-11 17:01:13 +00005874 return Incompatible;
5875}
5876
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005877/// \brief Constructs a transparent union from an expression that is
5878/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005879static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5880 ExprResult &EResult, QualType UnionType,
5881 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005882 // Build an initializer list that designates the appropriate member
5883 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005884 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005885 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005886 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005887 Initializer->setType(UnionType);
5888 Initializer->setInitializedFieldInUnion(Field);
5889
5890 // Build a compound literal constructing a value of the transparent
5891 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005892 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005893 EResult = S.Owned(
5894 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5895 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005896}
5897
5898Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005899Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005900 ExprResult &RHS) {
5901 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005902
Mike Stump1eb44332009-09-09 15:08:12 +00005903 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005904 // transparent_union GCC extension.
5905 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005906 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005907 return Incompatible;
5908
5909 // The field to initialize within the transparent union.
5910 RecordDecl *UD = UT->getDecl();
5911 FieldDecl *InitField = 0;
5912 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005913 for (RecordDecl::field_iterator it = UD->field_begin(),
5914 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005915 it != itend; ++it) {
5916 if (it->getType()->isPointerType()) {
5917 // If the transparent union contains a pointer type, we allow:
5918 // 1) void pointer
5919 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005920 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005921 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005922 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005923 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005924 break;
5925 }
Mike Stump1eb44332009-09-09 15:08:12 +00005926
Richard Trieuf7720da2011-09-06 20:40:12 +00005927 if (RHS.get()->isNullPointerConstant(Context,
5928 Expr::NPC_ValueDependentIsNull)) {
5929 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5930 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005931 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005932 break;
5933 }
5934 }
5935
John McCalldaa8e4e2010-11-15 09:13:47 +00005936 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005937 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005938 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005939 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005940 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005941 break;
5942 }
5943 }
5944
5945 if (!InitField)
5946 return Incompatible;
5947
Richard Trieuf7720da2011-09-06 20:40:12 +00005948 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005949 return Compatible;
5950}
5951
Chris Lattner5cf216b2008-01-04 18:04:52 +00005952Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005953Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5954 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005955 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005956 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005957 // C++ 5.17p3: If the left operand is not of class type, the
5958 // expression is implicitly converted (C++ 4) to the
5959 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005960 ExprResult Res;
5961 if (Diagnose) {
5962 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5963 AA_Assigning);
5964 } else {
5965 ImplicitConversionSequence ICS =
5966 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5967 /*SuppressUserConversions=*/false,
5968 /*AllowExplicit=*/false,
5969 /*InOverloadResolution=*/false,
5970 /*CStyle=*/false,
5971 /*AllowObjCWritebackConversion=*/false);
5972 if (ICS.isFailure())
5973 return Incompatible;
5974 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5975 ICS, AA_Assigning);
5976 }
John Wiegley429bb272011-04-08 18:41:53 +00005977 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005978 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005979 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005980 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005981 !CheckObjCARCUnavailableWeakConversion(LHSType,
5982 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005983 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005984 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005985 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005986 }
5987
5988 // FIXME: Currently, we fall through and treat C++ classes like C
5989 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005990 // FIXME: We also fall through for atomics; not sure what should
5991 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005992 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005993
Steve Naroff529a4ad2007-11-27 17:58:44 +00005994 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5995 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005996 if ((LHSType->isPointerType() ||
5997 LHSType->isObjCObjectPointerType() ||
5998 LHSType->isBlockPointerType())
5999 && RHS.get()->isNullPointerConstant(Context,
6000 Expr::NPC_ValueDependentIsNull)) {
6001 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006002 return Compatible;
6003 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006004
Chris Lattner943140e2007-10-16 02:55:40 +00006005 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006006 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006007 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006008 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006009 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006010 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00006011 if (!LHSType->isReferenceType()) {
6012 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6013 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006014 return Incompatible;
6015 }
Steve Narofff1120de2007-08-24 22:33:52 +00006016
John McCalldaa8e4e2010-11-15 09:13:47 +00006017 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006018 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00006019 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006020
Steve Narofff1120de2007-08-24 22:33:52 +00006021 // C99 6.5.16.1p2: The value of the right operand is converted to the
6022 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006023 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6024 // so that we can use references in built-in functions even in C.
6025 // The getNonReferenceType() call makes sure that the resulting expression
6026 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00006027 if (result != Incompatible && RHS.get()->getType() != LHSType)
6028 RHS = ImpCastExprToType(RHS.take(),
6029 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006030 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006031}
6032
Richard Trieuf7720da2011-09-06 20:40:12 +00006033QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6034 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006035 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00006036 << LHS.get()->getType() << RHS.get()->getType()
6037 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006038 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006039}
6040
Richard Trieu08062aa2011-09-06 21:01:04 +00006041QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006042 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00006043 if (!IsCompAssign) {
6044 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6045 if (LHS.isInvalid())
6046 return QualType();
6047 }
6048 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6049 if (RHS.isInvalid())
6050 return QualType();
6051
Mike Stumpeed9cac2009-02-19 03:04:26 +00006052 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006053 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00006054 QualType LHSType =
6055 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6056 QualType RHSType =
6057 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006058
Nate Begemanbe2341d2008-07-14 18:02:46 +00006059 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00006060 if (LHSType == RHSType)
6061 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006062
Douglas Gregor255210e2010-08-06 10:14:59 +00006063 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00006064 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6065 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6066 if (LHSType->isExtVectorType()) {
6067 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6068 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006069 }
6070
Richard Trieuccd891a2011-09-09 01:45:06 +00006071 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00006072 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6073 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00006074 }
6075
David Blaikie4e4d0842012-03-11 07:00:24 +00006076 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006077 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006078 // If we are allowing lax vector conversions, and LHS and RHS are both
6079 // vectors, the total size only needs to be the same. This is a
6080 // bitcast; no bits are changed but the result type is different.
6081 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006082 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6083 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006084 }
6085
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006086 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6087 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6088 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006089 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006090 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006091 std::swap(RHS, LHS);
6092 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006093 }
Mike Stump1eb44332009-09-09 15:08:12 +00006094
Nate Begemandde25982009-06-28 19:12:57 +00006095 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006096 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006097 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006098 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6099 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006100 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006101 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006102 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006103 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6104 if (swapped) std::swap(RHS, LHS);
6105 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006106 }
6107 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006108 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6109 RHSType->isRealFloatingType()) {
6110 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006111 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006112 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006113 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006114 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6115 if (swapped) std::swap(RHS, LHS);
6116 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006117 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006118 }
6119 }
Mike Stump1eb44332009-09-09 15:08:12 +00006120
Nate Begemandde25982009-06-28 19:12:57 +00006121 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006122 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006123 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006124 << LHS.get()->getType() << RHS.get()->getType()
6125 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006126 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006127}
6128
Richard Trieu481037f2011-09-16 00:53:10 +00006129// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6130// expression. These are mainly cases where the null pointer is used as an
6131// integer instead of a pointer.
6132static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6133 SourceLocation Loc, bool IsCompare) {
6134 // The canonical way to check for a GNU null is with isNullPointerConstant,
6135 // but we use a bit of a hack here for speed; this is a relatively
6136 // hot path, and isNullPointerConstant is slow.
6137 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6138 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6139
6140 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6141
6142 // Avoid analyzing cases where the result will either be invalid (and
6143 // diagnosed as such) or entirely valid and not something to warn about.
6144 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6145 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6146 return;
6147
6148 // Comparison operations would not make sense with a null pointer no matter
6149 // what the other expression is.
6150 if (!IsCompare) {
6151 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6152 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6153 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6154 return;
6155 }
6156
6157 // The rest of the operations only make sense with a null pointer
6158 // if the other expression is a pointer.
6159 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6160 NonNullType->canDecayToPointerType())
6161 return;
6162
6163 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6164 << LHSNull /* LHS is NULL */ << NonNullType
6165 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6166}
6167
Richard Trieu08062aa2011-09-06 21:01:04 +00006168QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006169 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006170 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006171 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6172
Richard Trieu08062aa2011-09-06 21:01:04 +00006173 if (LHS.get()->getType()->isVectorType() ||
6174 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006175 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006176
Richard Trieuccd891a2011-09-09 01:45:06 +00006177 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006178 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006179 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006180
David Chisnall7a7ee302012-01-16 17:27:18 +00006181
Eli Friedman860a3192012-06-16 02:19:17 +00006182 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006183 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006184
Chris Lattner7ef655a2010-01-12 21:23:57 +00006185 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006186 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006187 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006188 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006189 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6190 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006191
Chris Lattner7ef655a2010-01-12 21:23:57 +00006192 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006193}
6194
Chris Lattner7ef655a2010-01-12 21:23:57 +00006195QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006196 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006197 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6198
Richard Trieu08062aa2011-09-06 21:01:04 +00006199 if (LHS.get()->getType()->isVectorType() ||
6200 RHS.get()->getType()->isVectorType()) {
6201 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6202 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006203 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006204 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006205 }
Steve Naroff90045e82007-07-13 23:32:42 +00006206
Richard Trieuccd891a2011-09-09 01:45:06 +00006207 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006208 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006209 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006210
Eli Friedman860a3192012-06-16 02:19:17 +00006211 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006212 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006213
Chris Lattner7ef655a2010-01-12 21:23:57 +00006214 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006215 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006216 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006217 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6218 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006219
Chris Lattner7ef655a2010-01-12 21:23:57 +00006220 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006221}
6222
Chandler Carruth13b21be2011-06-27 08:02:19 +00006223/// \brief Diagnose invalid arithmetic on two void pointers.
6224static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006225 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006226 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006227 ? diag::err_typecheck_pointer_arith_void_type
6228 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006229 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6230 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006231}
6232
6233/// \brief Diagnose invalid arithmetic on a void pointer.
6234static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6235 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006236 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006237 ? diag::err_typecheck_pointer_arith_void_type
6238 : diag::ext_gnu_void_ptr)
6239 << 0 /* one pointer */ << Pointer->getSourceRange();
6240}
6241
6242/// \brief Diagnose invalid arithmetic on two function pointers.
6243static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6244 Expr *LHS, Expr *RHS) {
6245 assert(LHS->getType()->isAnyPointerType());
6246 assert(RHS->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 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6251 // We only show the second type if it differs from the first.
6252 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6253 RHS->getType())
6254 << RHS->getType()->getPointeeType()
6255 << LHS->getSourceRange() << RHS->getSourceRange();
6256}
6257
6258/// \brief Diagnose invalid arithmetic on a function pointer.
6259static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6260 Expr *Pointer) {
6261 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006262 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006263 ? diag::err_typecheck_pointer_arith_function_type
6264 : diag::ext_gnu_ptr_func_arith)
6265 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6266 << 0 /* one pointer, so only one type */
6267 << Pointer->getSourceRange();
6268}
6269
Richard Trieud9f19342011-09-12 18:08:02 +00006270/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006271///
6272/// \returns True if pointer has incomplete type
6273static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6274 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006275 assert(Operand->getType()->isAnyPointerType() &&
6276 !Operand->getType()->isDependentType());
6277 QualType PointeeTy = Operand->getType()->getPointeeType();
6278 return S.RequireCompleteType(Loc, PointeeTy,
6279 diag::err_typecheck_arithmetic_incomplete_type,
6280 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006281}
6282
Chandler Carruth13b21be2011-06-27 08:02:19 +00006283/// \brief Check the validity of an arithmetic pointer operand.
6284///
6285/// If the operand has pointer type, this code will check for pointer types
6286/// which are invalid in arithmetic operations. These will be diagnosed
6287/// appropriately, including whether or not the use is supported as an
6288/// extension.
6289///
6290/// \returns True when the operand is valid to use (even if as an extension).
6291static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6292 Expr *Operand) {
6293 if (!Operand->getType()->isAnyPointerType()) return true;
6294
6295 QualType PointeeTy = Operand->getType()->getPointeeType();
6296 if (PointeeTy->isVoidType()) {
6297 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006298 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006299 }
6300 if (PointeeTy->isFunctionType()) {
6301 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006302 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006303 }
6304
Richard Trieu097ecd22011-09-02 02:15:37 +00006305 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006306
6307 return true;
6308}
6309
6310/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6311/// operands.
6312///
6313/// This routine will diagnose any invalid arithmetic on pointer operands much
6314/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6315/// for emitting a single diagnostic even for operations where both LHS and RHS
6316/// are (potentially problematic) pointers.
6317///
6318/// \returns True when the operand is valid to use (even if as an extension).
6319static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006320 Expr *LHSExpr, Expr *RHSExpr) {
6321 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6322 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006323 if (!isLHSPointer && !isRHSPointer) return true;
6324
6325 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006326 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6327 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006328
6329 // Check for arithmetic on pointers to incomplete types.
6330 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6331 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6332 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006333 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6334 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6335 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006336
David Blaikie4e4d0842012-03-11 07:00:24 +00006337 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006338 }
6339
6340 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6341 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6342 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006343 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6344 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6345 RHSExpr);
6346 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006347
David Blaikie4e4d0842012-03-11 07:00:24 +00006348 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006349 }
6350
John McCall1503f0d2012-07-31 05:14:30 +00006351 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6352 return false;
6353 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6354 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006355
Chandler Carruth13b21be2011-06-27 08:02:19 +00006356 return true;
6357}
6358
Nico Weber1cb2d742012-03-02 22:01:22 +00006359/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6360/// literal.
6361static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6362 Expr *LHSExpr, Expr *RHSExpr) {
6363 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6364 Expr* IndexExpr = RHSExpr;
6365 if (!StrExpr) {
6366 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6367 IndexExpr = LHSExpr;
6368 }
6369
6370 bool IsStringPlusInt = StrExpr &&
6371 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6372 if (!IsStringPlusInt)
6373 return;
6374
6375 llvm::APSInt index;
6376 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6377 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6378 if (index.isNonNegative() &&
6379 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6380 index.isUnsigned()))
6381 return;
6382 }
6383
6384 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6385 Self.Diag(OpLoc, diag::warn_string_plus_int)
6386 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6387
6388 // Only print a fixit for "str" + int, not for int + "str".
6389 if (IndexExpr == RHSExpr) {
6390 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6391 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6392 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6393 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6394 << FixItHint::CreateInsertion(EndLoc, "]");
6395 } else
6396 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6397}
6398
Richard Trieud9f19342011-09-12 18:08:02 +00006399/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006400static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006401 Expr *LHSExpr, Expr *RHSExpr) {
6402 assert(LHSExpr->getType()->isAnyPointerType());
6403 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006404 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006405 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6406 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006407}
6408
Chris Lattner7ef655a2010-01-12 21:23:57 +00006409QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006410 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6411 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006412 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6413
Richard Trieudef75842011-09-06 21:13:51 +00006414 if (LHS.get()->getType()->isVectorType() ||
6415 RHS.get()->getType()->isVectorType()) {
6416 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006417 if (CompLHSTy) *CompLHSTy = compType;
6418 return compType;
6419 }
Steve Naroff49b45262007-07-13 16:58:59 +00006420
Richard Trieudef75842011-09-06 21:13:51 +00006421 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6422 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006423 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006424
Nico Weber1cb2d742012-03-02 22:01:22 +00006425 // Diagnose "string literal" '+' int.
6426 if (Opc == BO_Add)
6427 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6428
Reid Spencer5f016e22007-07-11 17:01:13 +00006429 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006430 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006431 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006432 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006433 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006434
John McCall1503f0d2012-07-31 05:14:30 +00006435 // Type-checking. Ultimately the pointer's going to be in PExp;
6436 // note that we bias towards the LHS being the pointer.
6437 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006438
John McCall1503f0d2012-07-31 05:14:30 +00006439 bool isObjCPointer;
6440 if (PExp->getType()->isPointerType()) {
6441 isObjCPointer = false;
6442 } else if (PExp->getType()->isObjCObjectPointerType()) {
6443 isObjCPointer = true;
6444 } else {
6445 std::swap(PExp, IExp);
6446 if (PExp->getType()->isPointerType()) {
6447 isObjCPointer = false;
6448 } else if (PExp->getType()->isObjCObjectPointerType()) {
6449 isObjCPointer = true;
6450 } else {
6451 return InvalidOperands(Loc, LHS, RHS);
6452 }
6453 }
6454 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006455
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006456 if (!IExp->getType()->isIntegerType())
6457 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006458
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006459 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6460 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006461
John McCall1503f0d2012-07-31 05:14:30 +00006462 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006463 return QualType();
6464
6465 // Check array bounds for pointer arithemtic
6466 CheckArrayAccess(PExp, IExp);
6467
6468 if (CompLHSTy) {
6469 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6470 if (LHSTy.isNull()) {
6471 LHSTy = LHS.get()->getType();
6472 if (LHSTy->isPromotableIntegerType())
6473 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006474 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006475 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006476 }
6477
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006478 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006479}
6480
Chris Lattnereca7be62008-04-07 05:30:13 +00006481// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006482QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006483 SourceLocation Loc,
6484 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006485 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6486
Richard Trieudef75842011-09-06 21:13:51 +00006487 if (LHS.get()->getType()->isVectorType() ||
6488 RHS.get()->getType()->isVectorType()) {
6489 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006490 if (CompLHSTy) *CompLHSTy = compType;
6491 return compType;
6492 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006493
Richard Trieudef75842011-09-06 21:13:51 +00006494 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6495 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006496 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006497
Chris Lattner6e4ab612007-12-09 21:53:25 +00006498 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006499
Chris Lattner6e4ab612007-12-09 21:53:25 +00006500 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006501 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006502 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006503 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006504 }
Mike Stump1eb44332009-09-09 15:08:12 +00006505
Chris Lattner6e4ab612007-12-09 21:53:25 +00006506 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006507 if (LHS.get()->getType()->isAnyPointerType()) {
6508 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006509
Chris Lattnerb5f15622009-04-24 23:50:08 +00006510 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006511 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6512 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006513 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006514
Chris Lattner6e4ab612007-12-09 21:53:25 +00006515 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006516 if (RHS.get()->getType()->isIntegerType()) {
6517 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006518 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006519
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006520 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006521 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6522 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006523
Richard Trieudef75842011-09-06 21:13:51 +00006524 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6525 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006526 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006527
Chris Lattner6e4ab612007-12-09 21:53:25 +00006528 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006529 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006530 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006531 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006532
David Blaikie4e4d0842012-03-11 07:00:24 +00006533 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006534 // Pointee types must be the same: C++ [expr.add]
6535 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006536 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006537 }
6538 } else {
6539 // Pointee types must be compatible C99 6.5.6p3
6540 if (!Context.typesAreCompatible(
6541 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6542 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006543 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006544 return QualType();
6545 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006546 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006547
Chandler Carruth13b21be2011-06-27 08:02:19 +00006548 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006549 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006550 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006551
Richard Trieudef75842011-09-06 21:13:51 +00006552 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006553 return Context.getPointerDiffType();
6554 }
6555 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006556
Richard Trieudef75842011-09-06 21:13:51 +00006557 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006558}
6559
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006560static bool isScopedEnumerationType(QualType T) {
6561 if (const EnumType *ET = dyn_cast<EnumType>(T))
6562 return ET->getDecl()->isScoped();
6563 return false;
6564}
6565
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006566static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006567 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006568 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006569 llvm::APSInt Right;
6570 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006571 if (RHS.get()->isValueDependent() ||
6572 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006573 return;
6574
6575 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006576 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006577 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006578 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006579 return;
6580 }
6581 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006582 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006583 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006584 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006585 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006586 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006587 return;
6588 }
6589 if (Opc != BO_Shl)
6590 return;
6591
6592 // When left shifting an ICE which is signed, we can check for overflow which
6593 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6594 // integers have defined behavior modulo one more than the maximum value
6595 // representable in the result type, so never warn for those.
6596 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006597 if (LHS.get()->isValueDependent() ||
6598 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6599 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006600 return;
6601 llvm::APInt ResultBits =
6602 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6603 if (LeftBits.uge(ResultBits))
6604 return;
6605 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6606 Result = Result.shl(Right);
6607
Ted Kremenekfa821382011-06-15 00:54:52 +00006608 // Print the bit representation of the signed integer as an unsigned
6609 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006610 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006611 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6612
Chandler Carruth21206d52011-02-23 23:34:11 +00006613 // If we are only missing a sign bit, this is less likely to result in actual
6614 // bugs -- if the result is cast back to an unsigned type, it will have the
6615 // expected value. Thus we place this behind a different warning that can be
6616 // turned off separately if needed.
6617 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006618 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006619 << HexResult.str() << LHSType
6620 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006621 return;
6622 }
6623
6624 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006625 << HexResult.str() << Result.getMinSignedBits() << LHSType
6626 << Left.getBitWidth() << LHS.get()->getSourceRange()
6627 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006628}
6629
Chris Lattnereca7be62008-04-07 05:30:13 +00006630// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006631QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006632 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006633 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006634 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6635
Chris Lattnerca5eede2007-12-12 05:47:28 +00006636 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006637 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6638 !RHS.get()->getType()->hasIntegerRepresentation())
6639 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006640
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006641 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6642 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006643 if (isScopedEnumerationType(LHS.get()->getType()) ||
6644 isScopedEnumerationType(RHS.get()->getType())) {
6645 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006646 }
6647
Nate Begeman2207d792009-10-25 02:26:48 +00006648 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006649 if (LHS.get()->getType()->isVectorType() ||
6650 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006651 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006652
Chris Lattnerca5eede2007-12-12 05:47:28 +00006653 // Shifts don't perform usual arithmetic conversions, they just do integer
6654 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006655
John McCall1bc80af2010-12-16 19:28:59 +00006656 // For the LHS, do usual unary conversions, but then reset them away
6657 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006658 ExprResult OldLHS = LHS;
6659 LHS = UsualUnaryConversions(LHS.take());
6660 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006661 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006662 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006663 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006664
6665 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006666 RHS = UsualUnaryConversions(RHS.take());
6667 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006668 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006669
Ryan Flynnd0439682009-08-07 16:20:20 +00006670 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006671 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006672
Chris Lattnerca5eede2007-12-12 05:47:28 +00006673 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006674 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006675}
6676
Chandler Carruth99919472010-07-10 12:30:03 +00006677static bool IsWithinTemplateSpecialization(Decl *D) {
6678 if (DeclContext *DC = D->getDeclContext()) {
6679 if (isa<ClassTemplateSpecializationDecl>(DC))
6680 return true;
6681 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6682 return FD->isFunctionTemplateSpecialization();
6683 }
6684 return false;
6685}
6686
Richard Trieue648ac32011-09-02 03:48:46 +00006687/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006688static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6689 ExprResult &RHS) {
6690 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6691 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006692
6693 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6694 if (!LHSEnumType)
6695 return;
6696 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6697 if (!RHSEnumType)
6698 return;
6699
6700 // Ignore anonymous enums.
6701 if (!LHSEnumType->getDecl()->getIdentifier())
6702 return;
6703 if (!RHSEnumType->getDecl()->getIdentifier())
6704 return;
6705
6706 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6707 return;
6708
6709 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6710 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006711 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006712}
6713
Richard Trieu7be1be02011-09-02 02:55:45 +00006714/// \brief Diagnose bad pointer comparisons.
6715static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006716 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006717 bool IsError) {
6718 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006719 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006720 << LHS.get()->getType() << RHS.get()->getType()
6721 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006722}
6723
6724/// \brief Returns false if the pointers are converted to a composite type,
6725/// true otherwise.
6726static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006727 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006728 // C++ [expr.rel]p2:
6729 // [...] Pointer conversions (4.10) and qualification
6730 // conversions (4.4) are performed on pointer operands (or on
6731 // a pointer operand and a null pointer constant) to bring
6732 // them to their composite pointer type. [...]
6733 //
6734 // C++ [expr.eq]p1 uses the same notion for (in)equality
6735 // comparisons of pointers.
6736
6737 // C++ [expr.eq]p2:
6738 // In addition, pointers to members can be compared, or a pointer to
6739 // member and a null pointer constant. Pointer to member conversions
6740 // (4.11) and qualification conversions (4.4) are performed to bring
6741 // them to a common type. If one operand is a null pointer constant,
6742 // the common type is the type of the other operand. Otherwise, the
6743 // common type is a pointer to member type similar (4.4) to the type
6744 // of one of the operands, with a cv-qualification signature (4.4)
6745 // that is the union of the cv-qualification signatures of the operand
6746 // types.
6747
Richard Trieuba261492011-09-06 21:27:33 +00006748 QualType LHSType = LHS.get()->getType();
6749 QualType RHSType = RHS.get()->getType();
6750 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6751 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006752
6753 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006754 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006755 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006756 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006757 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006758 return true;
6759 }
6760
6761 if (NonStandardCompositeType)
6762 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006763 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6764 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006765
Richard Trieuba261492011-09-06 21:27:33 +00006766 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6767 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006768 return false;
6769}
6770
6771static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006772 ExprResult &LHS,
6773 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006774 bool IsError) {
6775 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6776 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006777 << LHS.get()->getType() << RHS.get()->getType()
6778 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006779}
6780
Jordan Rose9f63a452012-06-08 21:14:25 +00006781static bool isObjCObjectLiteral(ExprResult &E) {
6782 switch (E.get()->getStmtClass()) {
6783 case Stmt::ObjCArrayLiteralClass:
6784 case Stmt::ObjCDictionaryLiteralClass:
6785 case Stmt::ObjCStringLiteralClass:
6786 case Stmt::ObjCBoxedExprClass:
6787 return true;
6788 default:
6789 // Note that ObjCBoolLiteral is NOT an object literal!
6790 return false;
6791 }
6792}
6793
Jordan Rose8d872ca2012-07-17 17:46:40 +00006794static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6795 // Get the LHS object's interface type.
6796 QualType Type = LHS->getType();
6797 QualType InterfaceType;
6798 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6799 InterfaceType = PTy->getPointeeType();
6800 if (const ObjCObjectType *iQFaceTy =
6801 InterfaceType->getAsObjCQualifiedInterfaceType())
6802 InterfaceType = iQFaceTy->getBaseType();
6803 } else {
6804 // If this is not actually an Objective-C object, bail out.
6805 return false;
6806 }
6807
6808 // If the RHS isn't an Objective-C object, bail out.
6809 if (!RHS->getType()->isObjCObjectPointerType())
6810 return false;
6811
6812 // Try to find the -isEqual: method.
6813 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6814 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6815 InterfaceType,
6816 /*instance=*/true);
6817 if (!Method) {
6818 if (Type->isObjCIdType()) {
6819 // For 'id', just check the global pool.
6820 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6821 /*receiverId=*/true,
6822 /*warn=*/false);
6823 } else {
6824 // Check protocols.
6825 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6826 cast<ObjCObjectPointerType>(Type),
6827 /*instance=*/true);
6828 }
6829 }
6830
6831 if (!Method)
6832 return false;
6833
6834 QualType T = Method->param_begin()[0]->getType();
6835 if (!T->isObjCObjectPointerType())
6836 return false;
6837
6838 QualType R = Method->getResultType();
6839 if (!R->isScalarType())
6840 return false;
6841
6842 return true;
6843}
6844
6845static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6846 ExprResult &LHS, ExprResult &RHS,
6847 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006848 Expr *Literal;
6849 Expr *Other;
6850 if (isObjCObjectLiteral(LHS)) {
6851 Literal = LHS.get();
6852 Other = RHS.get();
6853 } else {
6854 Literal = RHS.get();
6855 Other = LHS.get();
6856 }
6857
6858 // Don't warn on comparisons against nil.
6859 Other = Other->IgnoreParenCasts();
6860 if (Other->isNullPointerConstant(S.getASTContext(),
6861 Expr::NPC_ValueDependentIsNotNull))
6862 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006863
Jordan Roseeec207f2012-07-17 17:46:44 +00006864 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006865 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006866 enum {
6867 LK_Array,
6868 LK_Dictionary,
6869 LK_Numeric,
6870 LK_Boxed,
6871 LK_String
6872 } LiteralKind;
6873
Jordan Rose9f63a452012-06-08 21:14:25 +00006874 switch (Literal->getStmtClass()) {
6875 case Stmt::ObjCStringLiteralClass:
6876 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006877 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006878 break;
6879 case Stmt::ObjCArrayLiteralClass:
6880 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006881 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006882 break;
6883 case Stmt::ObjCDictionaryLiteralClass:
6884 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006885 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006886 break;
6887 case Stmt::ObjCBoxedExprClass: {
6888 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6889 switch (Inner->getStmtClass()) {
6890 case Stmt::IntegerLiteralClass:
6891 case Stmt::FloatingLiteralClass:
6892 case Stmt::CharacterLiteralClass:
6893 case Stmt::ObjCBoolLiteralExprClass:
6894 case Stmt::CXXBoolLiteralExprClass:
6895 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006896 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006897 break;
6898 case Stmt::ImplicitCastExprClass: {
6899 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6900 // Boolean literals can be represented by implicit casts.
6901 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006902 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006903 break;
6904 }
6905 // FALLTHROUGH
6906 }
6907 default:
6908 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006909 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006910 break;
6911 }
6912 break;
6913 }
6914 default:
6915 llvm_unreachable("Unknown Objective-C object literal kind");
6916 }
6917
Jordan Roseeec207f2012-07-17 17:46:44 +00006918 if (LiteralKind == LK_String)
6919 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6920 << Literal->getSourceRange();
6921 else
6922 S.Diag(Loc, diag::warn_objc_literal_comparison)
6923 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006924
Jordan Rose8d872ca2012-07-17 17:46:40 +00006925 if (BinaryOperator::isEqualityOp(Opc) &&
6926 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6927 SourceLocation Start = LHS.get()->getLocStart();
6928 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6929 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006930
Jordan Rose8d872ca2012-07-17 17:46:40 +00006931 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6932 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6933 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6934 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006935 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006936}
6937
Douglas Gregor0c6db942009-05-04 06:07:12 +00006938// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006939QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006940 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006941 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006942 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6943
John McCall2de56d12010-08-25 11:45:40 +00006944 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006945
Chris Lattner02dd4b12009-12-05 05:40:13 +00006946 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006947 if (LHS.get()->getType()->isVectorType() ||
6948 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006949 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006950
Richard Trieuf1775fb2011-09-06 21:43:51 +00006951 QualType LHSType = LHS.get()->getType();
6952 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006953
Richard Trieuf1775fb2011-09-06 21:43:51 +00006954 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6955 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006956
Richard Trieuf1775fb2011-09-06 21:43:51 +00006957 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006958
Richard Trieuf1775fb2011-09-06 21:43:51 +00006959 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006960 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006961 !LHS.get()->getLocStart().isMacroID() &&
6962 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006963 // For non-floating point types, check for self-comparisons of the form
6964 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6965 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006966 //
6967 // NOTE: Don't warn about comparison expressions resulting from macro
6968 // expansion. Also don't warn about comparisons which are only self
6969 // comparisons within a template specialization. The warnings should catch
6970 // obvious cases in the definition of the template anyways. The idea is to
6971 // warn when the typed comparison operator will always evaluate to the same
6972 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006973 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006974 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006975 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006976 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006977 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006978 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006979 << (Opc == BO_EQ
6980 || Opc == BO_LE
6981 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006982 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006983 !DRL->getDecl()->getType()->isReferenceType() &&
6984 !DRR->getDecl()->getType()->isReferenceType()) {
6985 // what is it always going to eval to?
6986 char always_evals_to;
6987 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006988 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006989 always_evals_to = 0; // false
6990 break;
John McCall2de56d12010-08-25 11:45:40 +00006991 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006992 always_evals_to = 1; // true
6993 break;
6994 default:
6995 // best we can say is 'a constant'
6996 always_evals_to = 2; // e.g. array1 <= array2
6997 break;
6998 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006999 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007000 << 1 // array
7001 << always_evals_to);
7002 }
7003 }
Chandler Carruth99919472010-07-10 12:30:03 +00007004 }
Mike Stump1eb44332009-09-09 15:08:12 +00007005
Chris Lattner55660a72009-03-08 19:39:53 +00007006 if (isa<CastExpr>(LHSStripped))
7007 LHSStripped = LHSStripped->IgnoreParenCasts();
7008 if (isa<CastExpr>(RHSStripped))
7009 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007010
Chris Lattner55660a72009-03-08 19:39:53 +00007011 // Warn about comparisons against a string constant (unless the other
7012 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007013 Expr *literalString = 0;
7014 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007015 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007016 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007017 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007018 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007019 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007020 } else if ((isa<StringLiteral>(RHSStripped) ||
7021 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007022 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007023 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007024 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007025 literalStringStripped = RHSStripped;
7026 }
7027
7028 if (literalString) {
7029 std::string resultComparison;
7030 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007031 case BO_LT: resultComparison = ") < 0"; break;
7032 case BO_GT: resultComparison = ") > 0"; break;
7033 case BO_LE: resultComparison = ") <= 0"; break;
7034 case BO_GE: resultComparison = ") >= 0"; break;
7035 case BO_EQ: resultComparison = ") == 0"; break;
7036 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00007037 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00007038 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007039
Ted Kremenek351ba912011-02-23 01:52:04 +00007040 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007041 PDiag(diag::warn_stringcompare)
7042 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007043 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007044 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007045 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007046
Douglas Gregord64fdd02010-06-08 19:50:34 +00007047 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00007048 if (LHS.get()->getType()->isArithmeticType() &&
7049 RHS.get()->getType()->isArithmeticType()) {
7050 UsualArithmeticConversions(LHS, RHS);
7051 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007052 return QualType();
7053 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007054 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007055 LHS = UsualUnaryConversions(LHS.take());
7056 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007057 return QualType();
7058
Richard Trieuf1775fb2011-09-06 21:43:51 +00007059 RHS = UsualUnaryConversions(RHS.take());
7060 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007061 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007062 }
7063
Richard Trieuf1775fb2011-09-06 21:43:51 +00007064 LHSType = LHS.get()->getType();
7065 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007066
Douglas Gregor447b69e2008-11-19 03:25:36 +00007067 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007068 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007069
Richard Trieuccd891a2011-09-09 01:45:06 +00007070 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007071 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007072 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007073 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007074 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007075 if (LHSType->hasFloatingRepresentation())
7076 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007077
Richard Trieuf1775fb2011-09-06 21:43:51 +00007078 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007079 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007080 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007081
Richard Trieuf1775fb2011-09-06 21:43:51 +00007082 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007083 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007084 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007085 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007086
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007087 // All of the following pointer-related warnings are GCC extensions, except
7088 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007089 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007090 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007091 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007092 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007093 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007094
David Blaikie4e4d0842012-03-11 07:00:24 +00007095 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007096 if (LCanPointeeTy == RCanPointeeTy)
7097 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007098 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007099 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7100 // Valid unless comparison between non-null pointer and function pointer
7101 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007102 // In a SFINAE context, we treat this as a hard error to maintain
7103 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007104 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7105 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007106 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007107 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007108
7109 if (isSFINAEContext())
7110 return QualType();
7111
Richard Trieuf1775fb2011-09-06 21:43:51 +00007112 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007113 return ResultTy;
7114 }
7115 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007116
Richard Trieuf1775fb2011-09-06 21:43:51 +00007117 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007118 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007119 else
7120 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007121 }
Eli Friedman3075e762009-08-23 00:27:47 +00007122 // C99 6.5.9p2 and C99 6.5.8p2
7123 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7124 RCanPointeeTy.getUnqualifiedType())) {
7125 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007126 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007127 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007128 << LHSType << RHSType << LHS.get()->getSourceRange()
7129 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007130 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007131 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007132 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7133 // Valid unless comparison between non-null pointer and function pointer
7134 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007135 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007136 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007137 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007138 } else {
7139 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007140 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007141 }
John McCall34d6f932011-03-11 04:25:25 +00007142 if (LCanPointeeTy != RCanPointeeTy) {
7143 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007144 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007145 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007146 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007147 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007148 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007149 }
Mike Stump1eb44332009-09-09 15:08:12 +00007150
David Blaikie4e4d0842012-03-11 07:00:24 +00007151 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007152 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007153 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007154 return ResultTy;
7155
Mike Stump1eb44332009-09-09 15:08:12 +00007156 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007157 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007158 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007159 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007160 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007161 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7162 RHS = ImpCastExprToType(RHS.take(), LHSType,
7163 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007164 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007165 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007166 return ResultTy;
7167 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007168 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007169 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007170 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007171 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7172 LHS = ImpCastExprToType(LHS.take(), RHSType,
7173 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007174 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007175 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007176 return ResultTy;
7177 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007178
7179 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007180 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007181 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7182 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007183 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007184 else
7185 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007186 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007187
7188 // Handle scoped enumeration types specifically, since they don't promote
7189 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007190 if (LHS.get()->getType()->isEnumeralType() &&
7191 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7192 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007193 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007194 }
Mike Stump1eb44332009-09-09 15:08:12 +00007195
Steve Naroff1c7d0672008-09-04 15:10:53 +00007196 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007197 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007198 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007199 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7200 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007201
Steve Naroff1c7d0672008-09-04 15:10:53 +00007202 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007203 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007204 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007205 << LHSType << RHSType << LHS.get()->getSourceRange()
7206 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007207 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007208 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007209 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007210 }
John Wiegley429bb272011-04-08 18:41:53 +00007211
Steve Naroff59f53942008-09-28 01:11:11 +00007212 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007213 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007214 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7215 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007216 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007217 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007218 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007219 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007220 ->getPointeeType()->isVoidType())))
7221 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007222 << LHSType << RHSType << LHS.get()->getSourceRange()
7223 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007224 }
John McCall34d6f932011-03-11 04:25:25 +00007225 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007226 LHS = ImpCastExprToType(LHS.take(), RHSType,
7227 RHSType->isPointerType() ? CK_BitCast
7228 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007229 else
John McCall1d9b3b22011-09-09 05:25:32 +00007230 RHS = ImpCastExprToType(RHS.take(), LHSType,
7231 LHSType->isPointerType() ? CK_BitCast
7232 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007233 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007234 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007235
Richard Trieuf1775fb2011-09-06 21:43:51 +00007236 if (LHSType->isObjCObjectPointerType() ||
7237 RHSType->isObjCObjectPointerType()) {
7238 const PointerType *LPT = LHSType->getAs<PointerType>();
7239 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007240 if (LPT || RPT) {
7241 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7242 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007243
Steve Naroffa8069f12008-11-17 19:49:16 +00007244 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007245 !Context.typesAreCompatible(LHSType, RHSType)) {
7246 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007247 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007248 }
John McCall34d6f932011-03-11 04:25:25 +00007249 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007250 LHS = ImpCastExprToType(LHS.take(), RHSType,
7251 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007252 else
John McCall1d9b3b22011-09-09 05:25:32 +00007253 RHS = ImpCastExprToType(RHS.take(), LHSType,
7254 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007255 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007256 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007257 if (LHSType->isObjCObjectPointerType() &&
7258 RHSType->isObjCObjectPointerType()) {
7259 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7260 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007261 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007262 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007263 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007264
John McCall34d6f932011-03-11 04:25:25 +00007265 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007266 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007267 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007268 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007269 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007270 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007271 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007272 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7273 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007274 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007275 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00007276 if (LangOpts.DebuggerSupport) {
7277 // Under a debugger, allow the comparison of pointers to integers,
7278 // since users tend to want to compare addresses.
7279 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00007280 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007281 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007282 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007283 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007284 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007285 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007286 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7287 isError = true;
7288 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007289 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007290
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007291 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007292 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007293 << LHSType << RHSType << LHS.get()->getSourceRange()
7294 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007295 if (isError)
7296 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007297 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007298
Richard Trieuf1775fb2011-09-06 21:43:51 +00007299 if (LHSType->isIntegerType())
7300 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007301 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007302 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007303 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007304 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007305 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007306 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007307
Steve Naroff39218df2008-09-04 16:56:14 +00007308 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007309 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007310 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7311 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007312 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007313 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007314 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007315 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7316 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007317 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007318 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007319
Richard Trieuf1775fb2011-09-06 21:43:51 +00007320 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007321}
7322
Tanya Lattner4f692c22012-01-16 21:02:28 +00007323
7324// Return a signed type that is of identical size and number of elements.
7325// For floating point vectors, return an integer type of identical size
7326// and number of elements.
7327QualType Sema::GetSignedVectorType(QualType V) {
7328 const VectorType *VTy = V->getAs<VectorType>();
7329 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7330 if (TypeSize == Context.getTypeSize(Context.CharTy))
7331 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7332 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7333 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7334 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7335 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7336 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7337 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7338 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7339 "Unhandled vector element size in vector compare");
7340 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7341}
7342
Nate Begemanbe2341d2008-07-14 18:02:46 +00007343/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007344/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007345/// like a scalar comparison, a vector comparison produces a vector of integer
7346/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007347QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007348 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007349 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007350 // Check to make sure we're operating on vectors of the same type and width,
7351 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007352 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007353 if (vType.isNull())
7354 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007355
Richard Trieu9f60dee2011-09-07 01:19:57 +00007356 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007357
Anton Yartsev7870b132011-03-27 15:36:07 +00007358 // If AltiVec, the comparison results in a numeric type, i.e.
7359 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007360 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007361 return Context.getLogicalOperationType();
7362
Nate Begemanbe2341d2008-07-14 18:02:46 +00007363 // For non-floating point types, check for self-comparisons of the form
7364 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7365 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007366 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007367 if (DeclRefExpr* DRL
7368 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7369 if (DeclRefExpr* DRR
7370 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007371 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007372 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007373 PDiag(diag::warn_comparison_always)
7374 << 0 // self-
7375 << 2 // "a constant"
7376 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007377 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007378
Nate Begemanbe2341d2008-07-14 18:02:46 +00007379 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007380 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007381 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007382 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007383 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007384
7385 // Return a signed type for the vector.
7386 return GetSignedVectorType(LHSType);
7387}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007388
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007389QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7390 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007391 // Ensure that either both operands are of the same vector type, or
7392 // one operand is of a vector type and the other is of its element type.
7393 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7394 if (vType.isNull() || vType->isFloatingType())
7395 return InvalidOperands(Loc, LHS, RHS);
7396
7397 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007398}
7399
Reid Spencer5f016e22007-07-11 17:01:13 +00007400inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007401 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007402 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7403
Richard Trieu9f60dee2011-09-07 01:19:57 +00007404 if (LHS.get()->getType()->isVectorType() ||
7405 RHS.get()->getType()->isVectorType()) {
7406 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7407 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007408 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007409
Richard Trieu9f60dee2011-09-07 01:19:57 +00007410 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007411 }
Steve Naroff90045e82007-07-13 23:32:42 +00007412
Richard Trieu9f60dee2011-09-07 01:19:57 +00007413 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7414 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007415 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007416 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007417 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007418 LHS = LHSResult.take();
7419 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007420
Eli Friedman860a3192012-06-16 02:19:17 +00007421 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007422 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007423 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007424}
7425
7426inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007427 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007428
Tanya Lattner4f692c22012-01-16 21:02:28 +00007429 // Check vector operands differently.
7430 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7431 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7432
Chris Lattner90a8f272010-07-13 19:41:32 +00007433 // Diagnose cases where the user write a logical and/or but probably meant a
7434 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7435 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007436 if (LHS.get()->getType()->isIntegerType() &&
7437 !LHS.get()->getType()->isBooleanType() &&
7438 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007439 // Don't warn in macros or template instantiations.
7440 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007441 // If the RHS can be constant folded, and if it constant folds to something
7442 // that isn't 0 or 1 (which indicate a potential logical operation that
7443 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007444 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007445 llvm::APSInt Result;
7446 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007447 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007448 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007449 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007450 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007451 << (Opc == BO_LAnd ? "&&" : "||");
7452 // Suggest replacing the logical operator with the bitwise version
7453 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7454 << (Opc == BO_LAnd ? "&" : "|")
7455 << FixItHint::CreateReplacement(SourceRange(
7456 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007457 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007458 Opc == BO_LAnd ? "&" : "|");
7459 if (Opc == BO_LAnd)
7460 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7461 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7462 << FixItHint::CreateRemoval(
7463 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007464 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007465 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007466 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007467 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007468 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007469 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007470
David Blaikie4e4d0842012-03-11 07:00:24 +00007471 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007472 LHS = UsualUnaryConversions(LHS.take());
7473 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007474 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007475
Richard Trieu9f60dee2011-09-07 01:19:57 +00007476 RHS = UsualUnaryConversions(RHS.take());
7477 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007478 return QualType();
7479
Richard Trieu9f60dee2011-09-07 01:19:57 +00007480 if (!LHS.get()->getType()->isScalarType() ||
7481 !RHS.get()->getType()->isScalarType())
7482 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007483
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007484 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007485 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007486
John McCall75f7c0f2010-06-04 00:29:51 +00007487 // The following is safe because we only use this method for
7488 // non-overloadable operands.
7489
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007490 // C++ [expr.log.and]p1
7491 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007492 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007493 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7494 if (LHSRes.isInvalid())
7495 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007496 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007497
Richard Trieu9f60dee2011-09-07 01:19:57 +00007498 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7499 if (RHSRes.isInvalid())
7500 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007501 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007502
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007503 // C++ [expr.log.and]p2
7504 // C++ [expr.log.or]p2
7505 // The result is a bool.
7506 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007507}
7508
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007509/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7510/// is a read-only property; return true if so. A readonly property expression
7511/// depends on various declarations and thus must be treated specially.
7512///
Mike Stump1eb44332009-09-09 15:08:12 +00007513static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007514 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7515 if (!PropExpr) return false;
7516 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007517
John McCall3c3b7f92011-10-25 17:37:35 +00007518 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7519 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007520 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007521 PropExpr->getBase()->getType();
7522
John McCall3c3b7f92011-10-25 17:37:35 +00007523 if (const ObjCObjectPointerType *OPT =
7524 BaseType->getAsObjCInterfacePointerType())
7525 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7526 if (S.isPropertyReadonly(PDecl, IFace))
7527 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007528 return false;
7529}
7530
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007531static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007532 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7533 if (!ME) return false;
7534 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7535 ObjCMessageExpr *Base =
7536 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7537 if (!Base) return false;
7538 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007539}
7540
John McCall78dae242012-03-13 00:37:01 +00007541/// Is the given expression (which must be 'const') a reference to a
7542/// variable which was originally non-const, but which has become
7543/// 'const' due to being captured within a block?
7544enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7545static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7546 assert(E->isLValue() && E->getType().isConstQualified());
7547 E = E->IgnoreParens();
7548
7549 // Must be a reference to a declaration from an enclosing scope.
7550 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7551 if (!DRE) return NCCK_None;
7552 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7553
7554 // The declaration must be a variable which is not declared 'const'.
7555 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7556 if (!var) return NCCK_None;
7557 if (var->getType().isConstQualified()) return NCCK_None;
7558 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7559
7560 // Decide whether the first capture was for a block or a lambda.
7561 DeclContext *DC = S.CurContext;
7562 while (DC->getParent() != var->getDeclContext())
7563 DC = DC->getParent();
7564 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7565}
7566
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007567/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7568/// emit an error and return true. If so, return false.
7569static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007570 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007571 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007572 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007573 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007574 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7575 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007576 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7577 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007578 if (IsLV == Expr::MLV_Valid)
7579 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007580
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007581 unsigned Diag = 0;
7582 bool NeedType = false;
7583 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007584 case Expr::MLV_ConstQualified:
7585 Diag = diag::err_typecheck_assign_const;
7586
John McCall78dae242012-03-13 00:37:01 +00007587 // Use a specialized diagnostic when we're assigning to an object
7588 // from an enclosing function or block.
7589 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7590 if (NCCK == NCCK_Block)
7591 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7592 else
7593 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7594 break;
7595 }
7596
John McCall7acddac2011-06-17 06:42:21 +00007597 // In ARC, use some specialized diagnostics for occasions where we
7598 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007599 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007600 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7601 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7602 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7603
John McCall7acddac2011-06-17 06:42:21 +00007604 // Use the normal diagnostic if it's pseudo-__strong but the
7605 // user actually wrote 'const'.
7606 if (var->isARCPseudoStrong() &&
7607 (!var->getTypeSourceInfo() ||
7608 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7609 // There are two pseudo-strong cases:
7610 // - self
John McCallf85e1932011-06-15 23:02:42 +00007611 ObjCMethodDecl *method = S.getCurMethodDecl();
7612 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007613 Diag = method->isClassMethod()
7614 ? diag::err_typecheck_arc_assign_self_class_method
7615 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007616
7617 // - fast enumeration variables
7618 else
John McCallf85e1932011-06-15 23:02:42 +00007619 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007620
John McCallf85e1932011-06-15 23:02:42 +00007621 SourceRange Assign;
7622 if (Loc != OrigLoc)
7623 Assign = SourceRange(OrigLoc, OrigLoc);
7624 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7625 // We need to preserve the AST regardless, so migration tool
7626 // can do its job.
7627 return false;
7628 }
7629 }
7630 }
7631
7632 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007633 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007634 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007635 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7636 NeedType = true;
7637 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007638 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007639 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7640 NeedType = true;
7641 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007642 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007643 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7644 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007645 case Expr::MLV_Valid:
7646 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007647 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007648 case Expr::MLV_MemberFunction:
7649 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007650 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7651 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007652 case Expr::MLV_IncompleteType:
7653 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007654 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007655 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007656 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007657 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7658 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007659 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007660 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007661 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007662 case Expr::MLV_InvalidMessageExpression:
7663 Diag = diag::error_readonly_message_assignment;
7664 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007665 case Expr::MLV_SubObjCPropertySetting:
7666 Diag = diag::error_no_subobject_property_setting;
7667 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007668 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007669
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007670 SourceRange Assign;
7671 if (Loc != OrigLoc)
7672 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007673 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007674 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007675 else
Mike Stump1eb44332009-09-09 15:08:12 +00007676 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007677 return true;
7678}
7679
Nico Weber7c81b432012-07-03 02:03:06 +00007680static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7681 SourceLocation Loc,
7682 Sema &Sema) {
7683 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007684 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7685 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7686 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7687 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007688 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007689 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007690
Nico Weber7c81b432012-07-03 02:03:06 +00007691 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007692 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7693 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7694 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7695 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7696 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7697 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007698 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007699 }
7700}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007701
7702// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007703QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007704 SourceLocation Loc,
7705 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007706 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7707
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007708 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007709 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007710 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007711
Richard Trieu268942b2011-09-07 01:33:52 +00007712 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007713 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7714 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007715 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007716 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007717 Expr *RHSCheck = RHS.get();
7718
Nico Weber7c81b432012-07-03 02:03:06 +00007719 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007720
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007721 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007722 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007723 if (RHS.isInvalid())
7724 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007725 // Special case of NSObject attributes on c-style pointer types.
7726 if (ConvTy == IncompatiblePointer &&
7727 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007728 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007729 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007730 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007731 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007732
John McCallf89e55a2010-11-18 06:31:45 +00007733 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007734 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007735 Diag(Loc, diag::err_objc_object_assignment)
7736 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007737
Chris Lattner2c156472008-08-21 18:04:13 +00007738 // If the RHS is a unary plus or minus, check to see if they = and + are
7739 // right next to each other. If so, the user may have typo'd "x =+ 4"
7740 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007741 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7742 RHSCheck = ICE->getSubExpr();
7743 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007744 if ((UO->getOpcode() == UO_Plus ||
7745 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007746 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007747 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007748 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007749 // And there is a space or other character before the subexpr of the
7750 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007751 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007752 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007753 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007754 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007755 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007756 }
Chris Lattner2c156472008-08-21 18:04:13 +00007757 }
John McCallf85e1932011-06-15 23:02:42 +00007758
7759 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00007760 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7761 // Warn about retain cycles where a block captures the LHS, but
7762 // not if the LHS is a simple variable into which the block is
7763 // being stored...unless that variable can be captured by reference!
7764 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7765 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7766 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7767 checkRetainCycles(LHSExpr, RHS.get());
7768
Jordan Rose58b6bdc2012-09-28 22:21:30 +00007769 // It is safe to assign a weak reference into a strong variable.
7770 // Although this code can still have problems:
7771 // id x = self.weakProp;
7772 // id y = self.weakProp;
7773 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7774 // paths through the function. This should be revisited if
7775 // -Wrepeated-use-of-weak is made flow-sensitive.
7776 DiagnosticsEngine::Level Level =
7777 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7778 RHS.get()->getLocStart());
7779 if (Level != DiagnosticsEngine::Ignored)
7780 getCurFunction()->markSafeWeakUse(RHS.get());
7781
Jordan Rosee10f4d32012-09-15 02:48:31 +00007782 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00007783 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00007784 }
John McCallf85e1932011-06-15 23:02:42 +00007785 }
Chris Lattner2c156472008-08-21 18:04:13 +00007786 } else {
7787 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007788 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007789 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007790
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007791 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007792 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007793 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007794
Richard Trieu268942b2011-09-07 01:33:52 +00007795 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007796
Reid Spencer5f016e22007-07-11 17:01:13 +00007797 // C99 6.5.16p3: The type of an assignment expression is the type of the
7798 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007799 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007800 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7801 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007802 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007803 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007804 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007805 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007806}
7807
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007808// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007809static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007810 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007811 LHS = S.CheckPlaceholderExpr(LHS.take());
7812 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007813 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007814 return QualType();
7815
John McCallcf2e5062010-10-12 07:14:40 +00007816 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7817 // operands, but not unary promotions.
7818 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007819
John McCallf6a16482010-12-04 03:47:34 +00007820 // So we treat the LHS as a ignored value, and in C++ we allow the
7821 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007822 LHS = S.IgnoredValueConversions(LHS.take());
7823 if (LHS.isInvalid())
7824 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007825
Eli Friedmana6115062012-05-24 00:47:05 +00007826 S.DiagnoseUnusedExprResult(LHS.get());
7827
David Blaikie4e4d0842012-03-11 07:00:24 +00007828 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007829 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7830 if (RHS.isInvalid())
7831 return QualType();
7832 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007833 S.RequireCompleteType(Loc, RHS.get()->getType(),
7834 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007835 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007836
John Wiegley429bb272011-04-08 18:41:53 +00007837 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007838}
7839
Steve Naroff49b45262007-07-13 16:58:59 +00007840/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7841/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007842static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7843 ExprValueKind &VK,
7844 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007845 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007846 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007847 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007848
Chris Lattner3528d352008-11-21 07:05:48 +00007849 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007850 // Atomic types can be used for increment / decrement where the non-atomic
7851 // versions can, so ignore the _Atomic() specifier for the purpose of
7852 // checking.
7853 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7854 ResType = ResAtomicType->getValueType();
7855
Chris Lattner3528d352008-11-21 07:05:48 +00007856 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007857
David Blaikie4e4d0842012-03-11 07:00:24 +00007858 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007859 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007860 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007861 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007862 return QualType();
7863 }
7864 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007865 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007866 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007867 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007868 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007869 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007870 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007871 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007872 } else if (ResType->isObjCObjectPointerType()) {
7873 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7874 // Otherwise, we just need a complete type.
7875 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7876 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7877 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007878 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007879 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007880 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007881 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007882 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007883 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007884 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007885 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007886 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007887 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007888 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007889 } else {
John McCall09431682010-11-18 19:01:18 +00007890 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007891 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007892 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007893 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007894 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007895 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007896 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007897 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007898 // In C++, a prefix increment is the same type as the operand. Otherwise
7899 // (in C or with postfix), the increment is the unqualified type of the
7900 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007901 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007902 VK = VK_LValue;
7903 return ResType;
7904 } else {
7905 VK = VK_RValue;
7906 return ResType.getUnqualifiedType();
7907 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007908}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007909
7910
Anders Carlsson369dee42008-02-01 07:15:58 +00007911/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007912/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007913/// where the declaration is needed for type checking. We only need to
7914/// handle cases when the expression references a function designator
7915/// or is an lvalue. Here are some examples:
7916/// - &(x) => x
7917/// - &*****f => f for f a function designator.
7918/// - &s.xx => s
7919/// - &s.zz[1].yy -> s, if zz is an array
7920/// - *(x + 1) -> x, if x is an array
7921/// - &"123"[2] -> 0
7922/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007923static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007924 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007925 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007926 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007927 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007928 // If this is an arrow operator, the address is an offset from
7929 // the base's value, so the object the base refers to is
7930 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007931 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007932 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007933 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007934 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007935 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007936 // FIXME: This code shouldn't be necessary! We should catch the implicit
7937 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007938 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7939 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7940 if (ICE->getSubExpr()->getType()->isArrayType())
7941 return getPrimaryDecl(ICE->getSubExpr());
7942 }
7943 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007944 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007945 case Stmt::UnaryOperatorClass: {
7946 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007947
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007948 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007949 case UO_Real:
7950 case UO_Imag:
7951 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007952 return getPrimaryDecl(UO->getSubExpr());
7953 default:
7954 return 0;
7955 }
7956 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007957 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007958 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007959 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007960 // If the result of an implicit cast is an l-value, we care about
7961 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007962 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007963 default:
7964 return 0;
7965 }
7966}
7967
Richard Trieu5520f232011-09-07 21:46:33 +00007968namespace {
7969 enum {
7970 AO_Bit_Field = 0,
7971 AO_Vector_Element = 1,
7972 AO_Property_Expansion = 2,
7973 AO_Register_Variable = 3,
7974 AO_No_Error = 4
7975 };
7976}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007977/// \brief Diagnose invalid operand for address of operations.
7978///
7979/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007980static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7981 Expr *E, unsigned Type) {
7982 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7983}
7984
Reid Spencer5f016e22007-07-11 17:01:13 +00007985/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007986/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007987/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007988/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007989/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007990/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007991/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007992static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007993 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007994 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7995 if (PTy->getKind() == BuiltinType::Overload) {
7996 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7997 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7998 << OrigOp.get()->getSourceRange();
7999 return QualType();
8000 }
8001
8002 return S.Context.OverloadTy;
8003 }
8004
8005 if (PTy->getKind() == BuiltinType::UnknownAny)
8006 return S.Context.UnknownAnyTy;
8007
8008 if (PTy->getKind() == BuiltinType::BoundMember) {
8009 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8010 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00008011 return QualType();
8012 }
John McCall3c3b7f92011-10-25 17:37:35 +00008013
8014 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8015 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00008016 }
John McCall9c72c602010-08-27 09:08:28 +00008017
John McCall3c3b7f92011-10-25 17:37:35 +00008018 if (OrigOp.get()->isTypeDependent())
8019 return S.Context.DependentTy;
8020
8021 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008022
John McCall9c72c602010-08-27 09:08:28 +00008023 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00008024 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008025
David Blaikie4e4d0842012-03-11 07:00:24 +00008026 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008027 // Implement C99-only parts of addressof rules.
8028 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008029 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008030 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8031 // (assuming the deref expression is valid).
8032 return uOp->getSubExpr()->getType();
8033 }
8034 // Technically, there should be a check for array subscript
8035 // expressions here, but the result of one is always an lvalue anyway.
8036 }
John McCall5808ce42011-02-03 08:15:49 +00008037 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008038 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00008039 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008040
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008041 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008042 bool sfinae = S.isSFINAEContext();
8043 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8044 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008045 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008046 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008047 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008048 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008049 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008050 } else if (lval == Expr::LV_MemberFunction) {
8051 // If it's an instance method, make a member pointer.
8052 // The expression must have exactly the form &A::foo.
8053
8054 // If the underlying expression isn't a decl ref, give up.
8055 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008056 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008057 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008058 return QualType();
8059 }
8060 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8061 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8062
8063 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00008064 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00008065 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00008066 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00008067
8068 // The method was named without a qualifier.
8069 } else if (!DRE->getQualifier()) {
David Blaikieabeadfb2012-10-11 22:55:07 +00008070 if (MD->getParent()->getName().empty())
8071 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8072 << op->getSourceRange();
8073 else {
8074 SmallString<32> Str;
8075 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8076 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8077 << op->getSourceRange()
8078 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8079 }
John McCall9c72c602010-08-27 09:08:28 +00008080 }
8081
John McCall09431682010-11-18 19:01:18 +00008082 return S.Context.getMemberPointerType(op->getType(),
8083 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008084 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008085 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008086 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008087 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00008088 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00008089 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00008090 AddressOfError = AO_Property_Expansion;
8091 } else {
8092 // FIXME: emit more specific diag...
8093 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8094 << op->getSourceRange();
8095 return QualType();
8096 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008097 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008098 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008099 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00008100 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00008101 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008102 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00008103 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00008104 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008105 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008106 // with the register storage-class specifier.
8107 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008108 // in C++ it is not error to take address of a register
8109 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008110 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008111 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008112 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008113 }
John McCallba135432009-11-21 08:51:07 +00008114 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008115 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008116 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008117 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008118 // Could be a pointer to member, though, if there is an explicit
8119 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008120 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008121 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008122 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008123 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008124 S.Diag(OpLoc,
8125 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008126 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008127 return QualType();
8128 }
Mike Stump1eb44332009-09-09 15:08:12 +00008129
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008130 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8131 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008132 return S.Context.getMemberPointerType(op->getType(),
8133 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008134 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008135 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008136 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008137 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008138 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008139
Richard Trieu5520f232011-09-07 21:46:33 +00008140 if (AddressOfError != AO_No_Error) {
8141 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8142 return QualType();
8143 }
8144
Eli Friedman441cf102009-05-16 23:27:50 +00008145 if (lval == Expr::LV_IncompleteVoidType) {
8146 // Taking the address of a void variable is technically illegal, but we
8147 // allow it in cases which are otherwise valid.
8148 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008149 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008150 }
8151
Reid Spencer5f016e22007-07-11 17:01:13 +00008152 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008153 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008154 return S.Context.getObjCObjectPointerType(op->getType());
8155 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008156}
8157
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008158/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008159static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8160 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008161 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008162 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008163
John Wiegley429bb272011-04-08 18:41:53 +00008164 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8165 if (ConvResult.isInvalid())
8166 return QualType();
8167 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008168 QualType OpTy = Op->getType();
8169 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008170
8171 if (isa<CXXReinterpretCastExpr>(Op)) {
8172 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8173 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8174 Op->getSourceRange());
8175 }
8176
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008177 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8178 // is an incomplete type or void. It would be possible to warn about
8179 // dereferencing a void pointer, but it's completely well-defined, and such a
8180 // warning is unlikely to catch any mistakes.
8181 if (const PointerType *PT = OpTy->getAs<PointerType>())
8182 Result = PT->getPointeeType();
8183 else if (const ObjCObjectPointerType *OPT =
8184 OpTy->getAs<ObjCObjectPointerType>())
8185 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008186 else {
John McCallfb8721c2011-04-10 19:13:55 +00008187 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008188 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008189 if (PR.take() != Op)
8190 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008191 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008192
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008193 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008194 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008195 << OpTy << Op->getSourceRange();
8196 return QualType();
8197 }
John McCall09431682010-11-18 19:01:18 +00008198
8199 // Dereferences are usually l-values...
8200 VK = VK_LValue;
8201
8202 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008203 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008204 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008205
8206 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008207}
8208
John McCall2de56d12010-08-25 11:45:40 +00008209static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008210 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008211 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008212 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008213 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008214 case tok::periodstar: Opc = BO_PtrMemD; break;
8215 case tok::arrowstar: Opc = BO_PtrMemI; break;
8216 case tok::star: Opc = BO_Mul; break;
8217 case tok::slash: Opc = BO_Div; break;
8218 case tok::percent: Opc = BO_Rem; break;
8219 case tok::plus: Opc = BO_Add; break;
8220 case tok::minus: Opc = BO_Sub; break;
8221 case tok::lessless: Opc = BO_Shl; break;
8222 case tok::greatergreater: Opc = BO_Shr; break;
8223 case tok::lessequal: Opc = BO_LE; break;
8224 case tok::less: Opc = BO_LT; break;
8225 case tok::greaterequal: Opc = BO_GE; break;
8226 case tok::greater: Opc = BO_GT; break;
8227 case tok::exclaimequal: Opc = BO_NE; break;
8228 case tok::equalequal: Opc = BO_EQ; break;
8229 case tok::amp: Opc = BO_And; break;
8230 case tok::caret: Opc = BO_Xor; break;
8231 case tok::pipe: Opc = BO_Or; break;
8232 case tok::ampamp: Opc = BO_LAnd; break;
8233 case tok::pipepipe: Opc = BO_LOr; break;
8234 case tok::equal: Opc = BO_Assign; break;
8235 case tok::starequal: Opc = BO_MulAssign; break;
8236 case tok::slashequal: Opc = BO_DivAssign; break;
8237 case tok::percentequal: Opc = BO_RemAssign; break;
8238 case tok::plusequal: Opc = BO_AddAssign; break;
8239 case tok::minusequal: Opc = BO_SubAssign; break;
8240 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8241 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8242 case tok::ampequal: Opc = BO_AndAssign; break;
8243 case tok::caretequal: Opc = BO_XorAssign; break;
8244 case tok::pipeequal: Opc = BO_OrAssign; break;
8245 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008246 }
8247 return Opc;
8248}
8249
John McCall2de56d12010-08-25 11:45:40 +00008250static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008251 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008252 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008253 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008254 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008255 case tok::plusplus: Opc = UO_PreInc; break;
8256 case tok::minusminus: Opc = UO_PreDec; break;
8257 case tok::amp: Opc = UO_AddrOf; break;
8258 case tok::star: Opc = UO_Deref; break;
8259 case tok::plus: Opc = UO_Plus; break;
8260 case tok::minus: Opc = UO_Minus; break;
8261 case tok::tilde: Opc = UO_Not; break;
8262 case tok::exclaim: Opc = UO_LNot; break;
8263 case tok::kw___real: Opc = UO_Real; break;
8264 case tok::kw___imag: Opc = UO_Imag; break;
8265 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008266 }
8267 return Opc;
8268}
8269
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008270/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8271/// This warning is only emitted for builtin assignment operations. It is also
8272/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008273static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008274 SourceLocation OpLoc) {
8275 if (!S.ActiveTemplateInstantiations.empty())
8276 return;
8277 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8278 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008279 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8280 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8281 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8282 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8283 if (!LHSDeclRef || !RHSDeclRef ||
8284 LHSDeclRef->getLocation().isMacroID() ||
8285 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008286 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008287 const ValueDecl *LHSDecl =
8288 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8289 const ValueDecl *RHSDecl =
8290 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8291 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008292 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008293 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008294 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008295 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008296 if (RefTy->getPointeeType().isVolatileQualified())
8297 return;
8298
8299 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008300 << LHSDeclRef->getType()
8301 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008302}
8303
Douglas Gregoreaebc752008-11-06 23:29:22 +00008304/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8305/// operator @p Opc at location @c TokLoc. This routine only supports
8306/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008307ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008308 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008309 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008310 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008311 // The syntax only allows initializer lists on the RHS of assignment,
8312 // so we don't need to worry about accepting invalid code for
8313 // non-assignment operators.
8314 // C++11 5.17p9:
8315 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8316 // of x = {} is x = T().
8317 InitializationKind Kind =
8318 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8319 InitializedEntity Entity =
8320 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8321 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008322 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008323 if (Init.isInvalid())
8324 return Init;
8325 RHSExpr = Init.take();
8326 }
8327
Richard Trieu78ea78b2011-09-07 01:49:20 +00008328 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008329 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008330 // The following two variables are used for compound assignment operators
8331 QualType CompLHSTy; // Type of LHS after promotions for computation
8332 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008333 ExprValueKind VK = VK_RValue;
8334 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008335
8336 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008337 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008338 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008339 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008340 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8341 VK = LHS.get()->getValueKind();
8342 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008343 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008344 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008345 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008346 break;
John McCall2de56d12010-08-25 11:45:40 +00008347 case BO_PtrMemD:
8348 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008349 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008350 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008351 break;
John McCall2de56d12010-08-25 11:45:40 +00008352 case BO_Mul:
8353 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008354 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008355 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008356 break;
John McCall2de56d12010-08-25 11:45:40 +00008357 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008358 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008359 break;
John McCall2de56d12010-08-25 11:45:40 +00008360 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008361 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008362 break;
John McCall2de56d12010-08-25 11:45:40 +00008363 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008364 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008365 break;
John McCall2de56d12010-08-25 11:45:40 +00008366 case BO_Shl:
8367 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008368 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008369 break;
John McCall2de56d12010-08-25 11:45:40 +00008370 case BO_LE:
8371 case BO_LT:
8372 case BO_GE:
8373 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008374 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008375 break;
John McCall2de56d12010-08-25 11:45:40 +00008376 case BO_EQ:
8377 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008378 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008379 break;
John McCall2de56d12010-08-25 11:45:40 +00008380 case BO_And:
8381 case BO_Xor:
8382 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008383 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008384 break;
John McCall2de56d12010-08-25 11:45:40 +00008385 case BO_LAnd:
8386 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008387 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008388 break;
John McCall2de56d12010-08-25 11:45:40 +00008389 case BO_MulAssign:
8390 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008391 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008392 Opc == BO_DivAssign);
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_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008398 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008399 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008400 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8401 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008402 break;
John McCall2de56d12010-08-25 11:45:40 +00008403 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008404 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008405 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8406 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008407 break;
John McCall2de56d12010-08-25 11:45:40 +00008408 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008409 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8410 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8411 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008412 break;
John McCall2de56d12010-08-25 11:45:40 +00008413 case BO_ShlAssign:
8414 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008415 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008416 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008417 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8418 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008419 break;
John McCall2de56d12010-08-25 11:45:40 +00008420 case BO_AndAssign:
8421 case BO_XorAssign:
8422 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008423 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008424 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008425 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8426 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008427 break;
John McCall2de56d12010-08-25 11:45:40 +00008428 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008429 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008430 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008431 VK = RHS.get()->getValueKind();
8432 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008433 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008434 break;
8435 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008436 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008437 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008438
8439 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008440 CheckArrayAccess(LHS.get());
8441 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008442
Eli Friedmanab3a8522009-03-28 01:22:36 +00008443 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008444 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hamesbe9af122012-10-02 04:45:10 +00008445 ResultTy, VK, OK, OpLoc,
8446 FPFeatures.fp_contract));
David Blaikie4e4d0842012-03-11 07:00:24 +00008447 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008448 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008449 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008450 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008451 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008452 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008453 ResultTy, VK, OK, CompLHSTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00008454 CompResultTy, OpLoc,
8455 FPFeatures.fp_contract));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008456}
8457
Sebastian Redlaee3c932009-10-27 12:10:02 +00008458/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8459/// operators are mixed in a way that suggests that the programmer forgot that
8460/// comparison operators have higher precedence. The most typical example of
8461/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008462static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008463 SourceLocation OpLoc, Expr *LHSExpr,
8464 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008465 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008466 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8467 RHSopc = static_cast<BinOp::Opcode>(-1);
8468 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8469 LHSopc = BO->getOpcode();
8470 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8471 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008472
8473 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008474 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008475 return;
8476
8477 // Bitwise operations are sometimes used as eager logical ops.
8478 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008479 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8480 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008481 return;
8482
Richard Trieu78ea78b2011-09-07 01:49:20 +00008483 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8484 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008485 if (!isLeftComp && !isRightComp) return;
8486
Richard Trieu78ea78b2011-09-07 01:49:20 +00008487 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8488 OpLoc)
8489 : SourceRange(OpLoc, RHSExpr->getLocEnd());
David Blaikie0bea8632012-10-08 01:11:04 +00008490 StringRef OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8491 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008492 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008493 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8494 RHSExpr->getLocEnd())
8495 : SourceRange(LHSExpr->getLocStart(),
8496 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008497
8498 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8499 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8500 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00008501 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008502 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008503 SuggestParentheses(Self, OpLoc,
8504 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8505 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008506}
8507
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008508/// \brief It accepts a '&' expr that is inside a '|' one.
8509/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8510/// in parentheses.
8511static void
8512EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8513 BinaryOperator *Bop) {
8514 assert(Bop->getOpcode() == BO_And);
8515 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8516 << Bop->getSourceRange() << OpLoc;
8517 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008518 Self.PDiag(diag::note_precedence_silence)
8519 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008520 Bop->getSourceRange());
8521}
8522
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008523/// \brief It accepts a '&&' expr that is inside a '||' one.
8524/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8525/// in parentheses.
8526static void
8527EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008528 BinaryOperator *Bop) {
8529 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008530 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8531 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008532 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008533 Self.PDiag(diag::note_precedence_silence)
8534 << Bop->getOpcodeStr(),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008535 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008536}
8537
8538/// \brief Returns true if the given expression can be evaluated as a constant
8539/// 'true'.
8540static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8541 bool Res;
8542 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8543}
8544
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008545/// \brief Returns true if the given expression can be evaluated as a constant
8546/// 'false'.
8547static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8548 bool Res;
8549 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8550}
8551
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008552/// \brief Look for '&&' in the left hand of a '||' expr.
8553static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008554 Expr *LHSExpr, Expr *RHSExpr) {
8555 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008556 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008557 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008558 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008559 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008560 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8561 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8562 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8563 } else if (Bop->getOpcode() == BO_LOr) {
8564 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8565 // If it's "a || b && 1 || c" we didn't warn earlier for
8566 // "a || b && 1", but warn now.
8567 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8568 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8569 }
8570 }
8571 }
8572}
8573
8574/// \brief Look for '&&' in the right hand of a '||' expr.
8575static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008576 Expr *LHSExpr, Expr *RHSExpr) {
8577 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008578 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008579 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008580 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008581 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008582 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8583 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8584 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008585 }
8586 }
8587}
8588
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008589/// \brief Look for '&' in the left or right hand of a '|' expr.
8590static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8591 Expr *OrArg) {
8592 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8593 if (Bop->getOpcode() == BO_And)
8594 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8595 }
8596}
8597
David Blaikieb3f55c52012-10-05 00:41:03 +00008598static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie5f531a42012-10-19 18:26:06 +00008599 Expr *SubExpr, StringRef Shift) {
David Blaikieb3f55c52012-10-05 00:41:03 +00008600 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8601 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikie6b34c172012-10-08 01:19:49 +00008602 StringRef Op = Bop->getOpcodeStr();
David Blaikieb3f55c52012-10-05 00:41:03 +00008603 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie5f531a42012-10-19 18:26:06 +00008604 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikieb3f55c52012-10-05 00:41:03 +00008605 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +00008606 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikieb3f55c52012-10-05 00:41:03 +00008607 Bop->getSourceRange());
8608 }
8609 }
8610}
8611
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008612/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008613/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008614static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008615 SourceLocation OpLoc, Expr *LHSExpr,
8616 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008617 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008618 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008619 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008620
8621 // Diagnose "arg1 & arg2 | arg3"
8622 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008623 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8624 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008625 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008626
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008627 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8628 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008629 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008630 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8631 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008632 }
David Blaikieb3f55c52012-10-05 00:41:03 +00008633
8634 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8635 || Opc == BO_Shr) {
David Blaikie5f531a42012-10-19 18:26:06 +00008636 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8637 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8638 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikieb3f55c52012-10-05 00:41:03 +00008639 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008640}
8641
Reid Spencer5f016e22007-07-11 17:01:13 +00008642// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008643ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008644 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008645 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008646 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008647 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8648 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008649
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008650 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008651 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008652
Richard Trieubefece12011-09-07 02:02:10 +00008653 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008654}
8655
John McCall3c3b7f92011-10-25 17:37:35 +00008656/// Build an overloaded binary operator expression in the given scope.
8657static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8658 BinaryOperatorKind Opc,
8659 Expr *LHS, Expr *RHS) {
8660 // Find all of the overloaded operators visible from this
8661 // point. We perform both an operator-name lookup from the local
8662 // scope and an argument-dependent lookup based on the types of
8663 // the arguments.
8664 UnresolvedSet<16> Functions;
8665 OverloadedOperatorKind OverOp
8666 = BinaryOperator::getOverloadedOperator(Opc);
8667 if (Sc && OverOp != OO_None)
8668 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8669 RHS->getType(), Functions);
8670
8671 // Build the (potentially-overloaded, potentially-dependent)
8672 // binary operation.
8673 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8674}
8675
John McCall60d7b3a2010-08-24 06:29:42 +00008676ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008677 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008678 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008679 // We want to end up calling one of checkPseudoObjectAssignment
8680 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8681 // both expressions are overloadable or either is type-dependent),
8682 // or CreateBuiltinBinOp (in any other case). We also want to get
8683 // any placeholder types out of the way.
8684
John McCall3c3b7f92011-10-25 17:37:35 +00008685 // Handle pseudo-objects in the LHS.
8686 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8687 // Assignments with a pseudo-object l-value need special analysis.
8688 if (pty->getKind() == BuiltinType::PseudoObject &&
8689 BinaryOperator::isAssignmentOp(Opc))
8690 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8691
8692 // Don't resolve overloads if the other type is overloadable.
8693 if (pty->getKind() == BuiltinType::Overload) {
8694 // We can't actually test that if we still have a placeholder,
8695 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008696 // code below are valid when the LHS is an overload set. Note
8697 // that an overload set can be dependently-typed, but it never
8698 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008699 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8700 if (resolvedRHS.isInvalid()) return ExprError();
8701 RHSExpr = resolvedRHS.take();
8702
John McCallac516502011-10-28 01:04:34 +00008703 if (RHSExpr->isTypeDependent() ||
8704 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008705 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8706 }
8707
8708 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8709 if (LHS.isInvalid()) return ExprError();
8710 LHSExpr = LHS.take();
8711 }
8712
8713 // Handle pseudo-objects in the RHS.
8714 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8715 // An overload in the RHS can potentially be resolved by the type
8716 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008717 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8718 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8719 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8720
Eli Friedman87884912012-01-17 21:27:43 +00008721 if (LHSExpr->getType()->isOverloadableType())
8722 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8723
John McCall3c3b7f92011-10-25 17:37:35 +00008724 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008725 }
John McCall3c3b7f92011-10-25 17:37:35 +00008726
8727 // Don't resolve overloads if the other type is overloadable.
8728 if (pty->getKind() == BuiltinType::Overload &&
8729 LHSExpr->getType()->isOverloadableType())
8730 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8731
8732 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8733 if (!resolvedRHS.isUsable()) return ExprError();
8734 RHSExpr = resolvedRHS.take();
8735 }
8736
David Blaikie4e4d0842012-03-11 07:00:24 +00008737 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008738 // If either expression is type-dependent, always build an
8739 // overloaded op.
8740 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8741 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008742
John McCallac516502011-10-28 01:04:34 +00008743 // Otherwise, build an overloaded op if either expression has an
8744 // overloadable type.
8745 if (LHSExpr->getType()->isOverloadableType() ||
8746 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008747 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008748 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008749
Douglas Gregoreaebc752008-11-06 23:29:22 +00008750 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008751 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008752}
8753
John McCall60d7b3a2010-08-24 06:29:42 +00008754ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008755 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008756 Expr *InputExpr) {
8757 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008758 ExprValueKind VK = VK_RValue;
8759 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008760 QualType resultType;
8761 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008762 case UO_PreInc:
8763 case UO_PreDec:
8764 case UO_PostInc:
8765 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008766 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008767 Opc == UO_PreInc ||
8768 Opc == UO_PostInc,
8769 Opc == UO_PreInc ||
8770 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008771 break;
John McCall2de56d12010-08-25 11:45:40 +00008772 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008773 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008774 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008775 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008776 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008777 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008778 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008779 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008780 }
John McCall2de56d12010-08-25 11:45:40 +00008781 case UO_Plus:
8782 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008783 Input = UsualUnaryConversions(Input.take());
8784 if (Input.isInvalid()) return ExprError();
8785 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008786 if (resultType->isDependentType())
8787 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008788 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8789 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008790 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008791 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008792 resultType->isEnumeralType())
8793 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008794 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008795 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008796 resultType->isPointerType())
8797 break;
8798
Sebastian Redl0eb23302009-01-19 00:08:26 +00008799 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008800 << resultType << Input.get()->getSourceRange());
8801
John McCall2de56d12010-08-25 11:45:40 +00008802 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008803 Input = UsualUnaryConversions(Input.take());
8804 if (Input.isInvalid()) return ExprError();
8805 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008806 if (resultType->isDependentType())
8807 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008808 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8809 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8810 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008811 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008812 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008813 else if (resultType->hasIntegerRepresentation())
8814 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008815 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008816 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008817 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008818 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008819 break;
John Wiegley429bb272011-04-08 18:41:53 +00008820
John McCall2de56d12010-08-25 11:45:40 +00008821 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008822 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008823 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8824 if (Input.isInvalid()) return ExprError();
8825 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008826
8827 // Though we still have to promote half FP to float...
8828 if (resultType->isHalfType()) {
8829 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8830 resultType = Context.FloatTy;
8831 }
8832
Sebastian Redl28507842009-02-26 14:39:58 +00008833 if (resultType->isDependentType())
8834 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008835 if (resultType->isScalarType()) {
8836 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008837 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008838 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8839 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008840 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8841 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008842 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008843 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008844 // Vector logical not returns the signed variant of the operand type.
8845 resultType = GetSignedVectorType(resultType);
8846 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008847 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008848 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008849 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008850 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008851
Reid Spencer5f016e22007-07-11 17:01:13 +00008852 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008853 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008854 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008855 break;
John McCall2de56d12010-08-25 11:45:40 +00008856 case UO_Real:
8857 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008858 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008859 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8860 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008861 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008862 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8863 if (Input.get()->getValueKind() != VK_RValue &&
8864 Input.get()->getObjectKind() == OK_Ordinary)
8865 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008866 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008867 // In C, a volatile scalar is read by __imag. In C++, it is not.
8868 Input = DefaultLvalueConversion(Input.take());
8869 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008870 break;
John McCall2de56d12010-08-25 11:45:40 +00008871 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008872 resultType = Input.get()->getType();
8873 VK = Input.get()->getValueKind();
8874 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008875 break;
8876 }
John Wiegley429bb272011-04-08 18:41:53 +00008877 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008878 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008879
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008880 // Check for array bounds violations in the operand of the UnaryOperator,
8881 // except for the '*' and '&' operators that have to be handled specially
8882 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8883 // that are explicitly defined as valid by the standard).
8884 if (Opc != UO_AddrOf && Opc != UO_Deref)
8885 CheckArrayAccess(Input.get());
8886
John Wiegley429bb272011-04-08 18:41:53 +00008887 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008888 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008889}
8890
Douglas Gregord3d08532011-12-14 21:23:13 +00008891/// \brief Determine whether the given expression is a qualified member
8892/// access expression, of a form that could be turned into a pointer to member
8893/// with the address-of operator.
8894static bool isQualifiedMemberAccess(Expr *E) {
8895 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8896 if (!DRE->getQualifier())
8897 return false;
8898
8899 ValueDecl *VD = DRE->getDecl();
8900 if (!VD->isCXXClassMember())
8901 return false;
8902
8903 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8904 return true;
8905 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8906 return Method->isInstance();
8907
8908 return false;
8909 }
8910
8911 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8912 if (!ULE->getQualifier())
8913 return false;
8914
8915 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8916 DEnd = ULE->decls_end();
8917 D != DEnd; ++D) {
8918 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8919 if (Method->isInstance())
8920 return true;
8921 } else {
8922 // Overload set does not contain methods.
8923 break;
8924 }
8925 }
8926
8927 return false;
8928 }
8929
8930 return false;
8931}
8932
John McCall60d7b3a2010-08-24 06:29:42 +00008933ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008934 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008935 // First things first: handle placeholders so that the
8936 // overloaded-operator check considers the right type.
8937 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8938 // Increment and decrement of pseudo-object references.
8939 if (pty->getKind() == BuiltinType::PseudoObject &&
8940 UnaryOperator::isIncrementDecrementOp(Opc))
8941 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8942
8943 // extension is always a builtin operator.
8944 if (Opc == UO_Extension)
8945 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8946
8947 // & gets special logic for several kinds of placeholder.
8948 // The builtin code knows what to do.
8949 if (Opc == UO_AddrOf &&
8950 (pty->getKind() == BuiltinType::Overload ||
8951 pty->getKind() == BuiltinType::UnknownAny ||
8952 pty->getKind() == BuiltinType::BoundMember))
8953 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8954
8955 // Anything else needs to be handled now.
8956 ExprResult Result = CheckPlaceholderExpr(Input);
8957 if (Result.isInvalid()) return ExprError();
8958 Input = Result.take();
8959 }
8960
David Blaikie4e4d0842012-03-11 07:00:24 +00008961 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008962 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8963 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008964 // Find all of the overloaded operators visible from this
8965 // point. We perform both an operator-name lookup from the local
8966 // scope and an argument-dependent lookup based on the types of
8967 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008968 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008969 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008970 if (S && OverOp != OO_None)
8971 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8972 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008973
John McCall9ae2f072010-08-23 23:25:46 +00008974 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008975 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008976
John McCall9ae2f072010-08-23 23:25:46 +00008977 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008978}
8979
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008980// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008981ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008982 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008983 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008984}
8985
Steve Naroff1b273c42007-09-16 14:56:35 +00008986/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008987ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008988 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008989 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008990 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008991 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008992 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008993}
8994
John McCallf85e1932011-06-15 23:02:42 +00008995/// Given the last statement in a statement-expression, check whether
8996/// the result is a producing expression (like a call to an
8997/// ns_returns_retained function) and, if so, rebuild it to hoist the
8998/// release out of the full-expression. Otherwise, return null.
8999/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00009000static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00009001 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00009002 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00009003 if (!cleanups) return 0;
9004
9005 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00009006 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00009007 return 0;
9008
9009 // Splice out the cast. This shouldn't modify any interesting
9010 // features of the statement.
9011 Expr *producer = cast->getSubExpr();
9012 assert(producer->getType() == cast->getType());
9013 assert(producer->getValueKind() == cast->getValueKind());
9014 cleanups->setSubExpr(producer);
9015 return cleanups;
9016}
9017
John McCall73f428c2012-04-04 01:27:53 +00009018void Sema::ActOnStartStmtExpr() {
9019 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9020}
9021
9022void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00009023 // Note that function is also called by TreeTransform when leaving a
9024 // StmtExpr scope without rebuilding anything.
9025
John McCall73f428c2012-04-04 01:27:53 +00009026 DiscardCleanupsInEvaluationContext();
9027 PopExpressionEvaluationContext();
9028}
9029
John McCall60d7b3a2010-08-24 06:29:42 +00009030ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009031Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009032 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009033 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9034 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9035
John McCall73f428c2012-04-04 01:27:53 +00009036 if (hasAnyUnrecoverableErrorsInThisFunction())
9037 DiscardCleanupsInEvaluationContext();
9038 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9039 PopExpressionEvaluationContext();
9040
Douglas Gregordd8f5692010-03-10 04:54:39 +00009041 bool isFileScope
9042 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009043 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009044 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009045
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009046 // FIXME: there are a variety of strange constraints to enforce here, for
9047 // example, it is not possible to goto into a stmt expression apparently.
9048 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009049
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009050 // If there are sub stmts in the compound stmt, take the type of the last one
9051 // as the type of the stmtexpr.
9052 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009053 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009054 if (!Compound->body_empty()) {
9055 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009056 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009057 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009058 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9059 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009060 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009061 }
John McCallf85e1932011-06-15 23:02:42 +00009062
John Wiegley429bb272011-04-08 18:41:53 +00009063 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009064 // Do function/array conversion on the last expression, but not
9065 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009066 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9067 if (LastExpr.isInvalid())
9068 return ExprError();
9069 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009070
John Wiegley429bb272011-04-08 18:41:53 +00009071 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009072 // In ARC, if the final expression ends in a consume, splice
9073 // the consume out and bind it later. In the alternate case
9074 // (when dealing with a retainable type), the result
9075 // initialization will create a produce. In both cases the
9076 // result will be +1, and we'll need to balance that out with
9077 // a bind.
9078 if (Expr *rebuiltLastStmt
9079 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9080 LastExpr = rebuiltLastStmt;
9081 } else {
9082 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009083 InitializedEntity::InitializeResult(LPLoc,
9084 Ty,
9085 false),
9086 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009087 LastExpr);
9088 }
9089
John Wiegley429bb272011-04-08 18:41:53 +00009090 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009091 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009092 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009093 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009094 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009095 else
John Wiegley429bb272011-04-08 18:41:53 +00009096 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009097 StmtExprMayBindToTemp = true;
9098 }
9099 }
9100 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009101 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009102
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009103 // FIXME: Check that expression type is complete/non-abstract; statement
9104 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009105 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9106 if (StmtExprMayBindToTemp)
9107 return MaybeBindToTemporary(ResStmtExpr);
9108 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009109}
Steve Naroffd34e9152007-08-01 22:05:33 +00009110
John McCall60d7b3a2010-08-24 06:29:42 +00009111ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009112 TypeSourceInfo *TInfo,
9113 OffsetOfComponent *CompPtr,
9114 unsigned NumComponents,
9115 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009116 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009117 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009118 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009119
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009120 // We must have at least one component that refers to the type, and the first
9121 // one is known to be a field designator. Verify that the ArgTy represents
9122 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009123 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009124 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9125 << ArgTy << TypeRange);
9126
9127 // Type must be complete per C99 7.17p3 because a declaring a variable
9128 // with an incomplete type would be ill-formed.
9129 if (!Dependent
9130 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00009131 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009132 return ExprError();
9133
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009134 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9135 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009136 // FIXME: This diagnostic isn't actually visible because the location is in
9137 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009138 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009139 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9140 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009141
9142 bool DidWarnAboutNonPOD = false;
9143 QualType CurrentType = ArgTy;
9144 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009145 SmallVector<OffsetOfNode, 4> Comps;
9146 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009147 for (unsigned i = 0; i != NumComponents; ++i) {
9148 const OffsetOfComponent &OC = CompPtr[i];
9149 if (OC.isBrackets) {
9150 // Offset of an array sub-field. TODO: Should we allow vector elements?
9151 if (!CurrentType->isDependentType()) {
9152 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9153 if(!AT)
9154 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9155 << CurrentType);
9156 CurrentType = AT->getElementType();
9157 } else
9158 CurrentType = Context.DependentTy;
9159
Richard Smithea011432011-10-17 23:29:39 +00009160 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9161 if (IdxRval.isInvalid())
9162 return ExprError();
9163 Expr *Idx = IdxRval.take();
9164
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009165 // The expression must be an integral expression.
9166 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009167 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9168 !Idx->getType()->isIntegerType())
9169 return ExprError(Diag(Idx->getLocStart(),
9170 diag::err_typecheck_subscript_not_integer)
9171 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009172
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009173 // Record this array index.
9174 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009175 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009176 continue;
9177 }
9178
9179 // Offset of a field.
9180 if (CurrentType->isDependentType()) {
9181 // We have the offset of a field, but we can't look into the dependent
9182 // type. Just record the identifier of the field.
9183 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9184 CurrentType = Context.DependentTy;
9185 continue;
9186 }
9187
9188 // We need to have a complete type to look into.
9189 if (RequireCompleteType(OC.LocStart, CurrentType,
9190 diag::err_offsetof_incomplete_type))
9191 return ExprError();
9192
9193 // Look for the designated field.
9194 const RecordType *RC = CurrentType->getAs<RecordType>();
9195 if (!RC)
9196 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9197 << CurrentType);
9198 RecordDecl *RD = RC->getDecl();
9199
9200 // C++ [lib.support.types]p5:
9201 // The macro offsetof accepts a restricted set of type arguments in this
9202 // International Standard. type shall be a POD structure or a POD union
9203 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009204 // C++11 [support.types]p4:
9205 // If type is not a standard-layout class (Clause 9), the results are
9206 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009207 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009208 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9209 unsigned DiagID =
9210 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9211 : diag::warn_offsetof_non_pod_type;
9212
9213 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009214 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009215 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009216 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9217 << CurrentType))
9218 DidWarnAboutNonPOD = true;
9219 }
9220
9221 // Look for the field.
9222 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9223 LookupQualifiedName(R, RD);
9224 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009225 IndirectFieldDecl *IndirectMemberDecl = 0;
9226 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009227 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009228 MemberDecl = IndirectMemberDecl->getAnonField();
9229 }
9230
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009231 if (!MemberDecl)
9232 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9233 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9234 OC.LocEnd));
9235
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009236 // C99 7.17p3:
9237 // (If the specified member is a bit-field, the behavior is undefined.)
9238 //
9239 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009240 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009241 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9242 << MemberDecl->getDeclName()
9243 << SourceRange(BuiltinLoc, RParenLoc);
9244 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9245 return ExprError();
9246 }
Eli Friedman19410a72010-08-05 10:11:36 +00009247
9248 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009249 if (IndirectMemberDecl)
9250 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009251
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009252 // If the member was found in a base class, introduce OffsetOfNodes for
9253 // the base class indirections.
9254 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9255 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009256 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009257 CXXBasePath &Path = Paths.front();
9258 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9259 B != BEnd; ++B)
9260 Comps.push_back(OffsetOfNode(B->Base));
9261 }
Eli Friedman19410a72010-08-05 10:11:36 +00009262
Francois Pichet87c2e122010-11-21 06:08:52 +00009263 if (IndirectMemberDecl) {
9264 for (IndirectFieldDecl::chain_iterator FI =
9265 IndirectMemberDecl->chain_begin(),
9266 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9267 assert(isa<FieldDecl>(*FI));
9268 Comps.push_back(OffsetOfNode(OC.LocStart,
9269 cast<FieldDecl>(*FI), OC.LocEnd));
9270 }
9271 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009272 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009273
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009274 CurrentType = MemberDecl->getType().getNonReferenceType();
9275 }
9276
9277 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009278 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009279}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009280
John McCall60d7b3a2010-08-24 06:29:42 +00009281ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009282 SourceLocation BuiltinLoc,
9283 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009284 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009285 OffsetOfComponent *CompPtr,
9286 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009287 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009288
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009289 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009290 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009291 if (ArgTy.isNull())
9292 return ExprError();
9293
Eli Friedman5a15dc12010-08-05 10:15:45 +00009294 if (!ArgTInfo)
9295 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9296
9297 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009298 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009299}
9300
9301
John McCall60d7b3a2010-08-24 06:29:42 +00009302ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009303 Expr *CondExpr,
9304 Expr *LHSExpr, Expr *RHSExpr,
9305 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009306 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9307
John McCallf89e55a2010-11-18 06:31:45 +00009308 ExprValueKind VK = VK_RValue;
9309 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009310 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009311 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009312 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009313 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009314 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009315 } else {
9316 // The conditional expression is required to be a constant expression.
9317 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009318 ExprResult CondICE
9319 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9320 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009321 if (CondICE.isInvalid())
9322 return ExprError();
9323 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009324
Sebastian Redl28507842009-02-26 14:39:58 +00009325 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009326 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9327
9328 resType = ActiveExpr->getType();
9329 ValueDependent = ActiveExpr->isValueDependent();
9330 VK = ActiveExpr->getValueKind();
9331 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009332 }
9333
Sebastian Redlf53597f2009-03-15 17:47:39 +00009334 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009335 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009336 resType->isDependentType(),
9337 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009338}
9339
Steve Naroff4eb206b2008-09-03 18:15:37 +00009340//===----------------------------------------------------------------------===//
9341// Clang Extensions.
9342//===----------------------------------------------------------------------===//
9343
9344/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009345void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009346 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009347 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009348 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009349 if (CurScope)
9350 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009351 else
9352 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009353
Eli Friedman84b007f2012-01-26 03:00:14 +00009354 getCurBlock()->HasImplicitReturnType = true;
9355
John McCall538773c2011-11-11 03:19:12 +00009356 // Enter a new evaluation context to insulate the block from any
9357 // cleanups from the enclosing full-expression.
9358 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009359}
9360
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009361void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9362 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009363 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009364 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009365 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009366
John McCallbf1a0282010-06-04 23:28:52 +00009367 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009368 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009369
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009370 // FIXME: We should allow unexpanded parameter packs here, but that would,
9371 // in turn, make the block expression contain unexpanded parameter packs.
9372 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9373 // Drop the parameters.
9374 FunctionProtoType::ExtProtoInfo EPI;
9375 EPI.HasTrailingReturn = false;
9376 EPI.TypeQuals |= DeclSpec::TQ_const;
9377 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9378 EPI);
9379 Sig = Context.getTrivialTypeSourceInfo(T);
9380 }
9381
John McCall711c52b2011-01-05 12:14:39 +00009382 // GetTypeForDeclarator always produces a function type for a block
9383 // literal signature. Furthermore, it is always a FunctionProtoType
9384 // unless the function was written with a typedef.
9385 assert(T->isFunctionType() &&
9386 "GetTypeForDeclarator made a non-function block signature");
9387
9388 // Look for an explicit signature in that function type.
9389 FunctionProtoTypeLoc ExplicitSignature;
9390
9391 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9392 if (isa<FunctionProtoTypeLoc>(tmp)) {
9393 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9394
9395 // Check whether that explicit signature was synthesized by
9396 // GetTypeForDeclarator. If so, don't save that as part of the
9397 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009398 if (ExplicitSignature.getLocalRangeBegin() ==
9399 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009400 // This would be much cheaper if we stored TypeLocs instead of
9401 // TypeSourceInfos.
9402 TypeLoc Result = ExplicitSignature.getResultLoc();
9403 unsigned Size = Result.getFullDataSize();
9404 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9405 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9406
9407 ExplicitSignature = FunctionProtoTypeLoc();
9408 }
John McCall82dc0092010-06-04 11:21:44 +00009409 }
Mike Stump1eb44332009-09-09 15:08:12 +00009410
John McCall711c52b2011-01-05 12:14:39 +00009411 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9412 CurBlock->FunctionType = T;
9413
9414 const FunctionType *Fn = T->getAs<FunctionType>();
9415 QualType RetTy = Fn->getResultType();
9416 bool isVariadic =
9417 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9418
John McCallc71a4912010-06-04 19:02:56 +00009419 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009420
John McCall82dc0092010-06-04 11:21:44 +00009421 // Don't allow returning a objc interface by value.
9422 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009423 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009424 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9425 return;
9426 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009427
John McCall82dc0092010-06-04 11:21:44 +00009428 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009429 // return type. TODO: what should we do with declarators like:
9430 // ^ * { ... }
9431 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009432 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009433 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009434 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009435 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009436 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009437
John McCall82dc0092010-06-04 11:21:44 +00009438 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009439 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009440 if (ExplicitSignature) {
9441 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9442 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009443 if (Param->getIdentifier() == 0 &&
9444 !Param->isImplicit() &&
9445 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009446 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009447 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009448 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009449 }
John McCall82dc0092010-06-04 11:21:44 +00009450
9451 // Fake up parameter variables if we have a typedef, like
9452 // ^ fntype { ... }
9453 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9454 for (FunctionProtoType::arg_type_iterator
9455 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9456 ParmVarDecl *Param =
9457 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009458 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009459 *I);
John McCallc71a4912010-06-04 19:02:56 +00009460 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009461 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009462 }
John McCall82dc0092010-06-04 11:21:44 +00009463
John McCallc71a4912010-06-04 19:02:56 +00009464 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009465 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009466 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009467 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9468 CurBlock->TheDecl->param_end(),
9469 /*CheckParameterNames=*/false);
9470 }
9471
John McCall82dc0092010-06-04 11:21:44 +00009472 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009473 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009474
John McCall82dc0092010-06-04 11:21:44 +00009475 // Put the parameter variables in scope. We can bail out immediately
9476 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009477 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009478 return;
9479
Steve Naroff090276f2008-10-10 01:28:17 +00009480 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009481 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9482 (*AI)->setOwningFunction(CurBlock->TheDecl);
9483
Steve Naroff090276f2008-10-10 01:28:17 +00009484 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009485 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009486 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009487
Steve Naroff090276f2008-10-10 01:28:17 +00009488 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009489 }
John McCall7a9813c2010-01-22 00:28:27 +00009490 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009491}
9492
9493/// ActOnBlockError - If there is an error parsing a block, this callback
9494/// is invoked to pop the information about the block from the action impl.
9495void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009496 // Leave the expression-evaluation context.
9497 DiscardCleanupsInEvaluationContext();
9498 PopExpressionEvaluationContext();
9499
Steve Naroff4eb206b2008-09-03 18:15:37 +00009500 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009501 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009502 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009503}
9504
9505/// ActOnBlockStmtExpr - This is called when the body of a block statement
9506/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009507ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009508 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009509 // If blocks are disabled, emit an error.
9510 if (!LangOpts.Blocks)
9511 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009512
John McCall538773c2011-11-11 03:19:12 +00009513 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009514 if (hasAnyUnrecoverableErrorsInThisFunction())
9515 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009516 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9517 PopExpressionEvaluationContext();
9518
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009519 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009520
9521 if (BSI->HasImplicitReturnType)
9522 deduceClosureReturnType(*BSI);
9523
Steve Naroff090276f2008-10-10 01:28:17 +00009524 PopDeclContext();
9525
Steve Naroff4eb206b2008-09-03 18:15:37 +00009526 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009527 if (!BSI->ReturnType.isNull())
9528 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009529
Mike Stump56925862009-07-28 22:04:01 +00009530 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009531 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009532
John McCall469a1eb2011-02-02 13:00:07 +00009533 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009534 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9535 SmallVector<BlockDecl::Capture, 4> Captures;
9536 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9537 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9538 if (Cap.isThisCapture())
9539 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009540 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009541 Cap.isNested(), Cap.getCopyExpr());
9542 Captures.push_back(NewCap);
9543 }
9544 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9545 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009546
John McCallc71a4912010-06-04 19:02:56 +00009547 // If the user wrote a function type in some form, try to use that.
9548 if (!BSI->FunctionType.isNull()) {
9549 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9550
9551 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9552 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9553
9554 // Turn protoless block types into nullary block types.
9555 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009556 FunctionProtoType::ExtProtoInfo EPI;
9557 EPI.ExtInfo = Ext;
9558 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009559
9560 // Otherwise, if we don't need to change anything about the function type,
9561 // preserve its sugar structure.
9562 } else if (FTy->getResultType() == RetTy &&
9563 (!NoReturn || FTy->getNoReturnAttr())) {
9564 BlockTy = BSI->FunctionType;
9565
9566 // Otherwise, make the minimal modifications to the function type.
9567 } else {
9568 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009569 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9570 EPI.TypeQuals = 0; // FIXME: silently?
9571 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009572 BlockTy = Context.getFunctionType(RetTy,
9573 FPT->arg_type_begin(),
9574 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009575 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009576 }
9577
9578 // If we don't have a function type, just build one from nothing.
9579 } else {
John McCalle23cf432010-12-14 08:05:40 +00009580 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009581 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009582 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009583 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009584
John McCallc71a4912010-06-04 19:02:56 +00009585 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9586 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009587 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009588
Chris Lattner17a78302009-04-19 05:28:12 +00009589 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009590 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009591 !hasAnyUnrecoverableErrorsInThisFunction() &&
9592 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009593 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009594
Chris Lattnere476bdc2011-02-17 23:58:47 +00009595 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009596
Jordan Rose7dd900e2012-07-02 21:19:23 +00009597 // Try to apply the named return value optimization. We have to check again
9598 // if we can do this, though, because blocks keep return statements around
9599 // to deduce an implicit return type.
9600 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9601 !BSI->TheDecl->isDependentContext())
9602 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009603
Benjamin Kramerd2486192011-07-12 14:11:05 +00009604 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9605 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009606 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009607
John McCall80ee6e82011-11-10 05:35:25 +00009608 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009609 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009610 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009611 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009612 ExprCleanupObjects.push_back(Result->getBlockDecl());
9613 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009614
9615 // It also gets a branch-protected scope if any of the captured
9616 // variables needs destruction.
9617 for (BlockDecl::capture_const_iterator
9618 ci = Result->getBlockDecl()->capture_begin(),
9619 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9620 const VarDecl *var = ci->getVariable();
9621 if (var->getType().isDestructedType() != QualType::DK_none) {
9622 getCurFunction()->setHasBranchProtectedScope();
9623 break;
9624 }
9625 }
John McCall80ee6e82011-11-10 05:35:25 +00009626 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009627
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009628 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009629}
9630
John McCall60d7b3a2010-08-24 06:29:42 +00009631ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009632 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009633 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009634 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009635 GetTypeFromParser(Ty, &TInfo);
9636 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009637}
9638
John McCall60d7b3a2010-08-24 06:29:42 +00009639ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009640 Expr *E, TypeSourceInfo *TInfo,
9641 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009642 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009643
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009644 // Get the va_list type
9645 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009646 if (VaListType->isArrayType()) {
9647 // Deal with implicit array decay; for example, on x86-64,
9648 // va_list is an array, but it's supposed to decay to
9649 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009650 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009651 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009652 ExprResult Result = UsualUnaryConversions(E);
9653 if (Result.isInvalid())
9654 return ExprError();
9655 E = Result.take();
Logan Chienb687f3b2012-10-20 06:11:33 +00009656 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9657 // If va_list is a record type and we are compiling in C++ mode,
9658 // check the argument using reference binding.
9659 InitializedEntity Entity
9660 = InitializedEntity::InitializeParameter(Context,
9661 Context.getLValueReferenceType(VaListType), false);
9662 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9663 if (Init.isInvalid())
9664 return ExprError();
9665 E = Init.takeAs<Expr>();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009666 } else {
9667 // Otherwise, the va_list argument must be an l-value because
9668 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009669 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009670 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009671 return ExprError();
9672 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009673
Douglas Gregordd027302009-05-19 23:10:31 +00009674 if (!E->isTypeDependent() &&
9675 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009676 return ExprError(Diag(E->getLocStart(),
9677 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009678 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009679 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009680
David Majnemer0adde122011-06-14 05:17:32 +00009681 if (!TInfo->getType()->isDependentType()) {
9682 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009683 diag::err_second_parameter_to_va_arg_incomplete,
9684 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009685 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009686
David Majnemer0adde122011-06-14 05:17:32 +00009687 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009688 TInfo->getType(),
9689 diag::err_second_parameter_to_va_arg_abstract,
9690 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009691 return ExprError();
9692
Douglas Gregor4eb75222011-07-30 06:45:27 +00009693 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009694 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009695 TInfo->getType()->isObjCLifetimeType()
9696 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9697 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009698 << TInfo->getType()
9699 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009700 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009701
9702 // Check for va_arg where arguments of the given type will be promoted
9703 // (i.e. this va_arg is guaranteed to have undefined behavior).
9704 QualType PromoteType;
9705 if (TInfo->getType()->isPromotableIntegerType()) {
9706 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9707 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9708 PromoteType = QualType();
9709 }
9710 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9711 PromoteType = Context.DoubleTy;
9712 if (!PromoteType.isNull())
9713 Diag(TInfo->getTypeLoc().getBeginLoc(),
9714 diag::warn_second_parameter_to_va_arg_never_compatible)
9715 << TInfo->getType()
9716 << PromoteType
9717 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009718 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009719
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009720 QualType T = TInfo->getType().getNonLValueExprType(Context);
9721 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009722}
9723
John McCall60d7b3a2010-08-24 06:29:42 +00009724ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009725 // The type of __null will be int or long, depending on the size of
9726 // pointers on the target.
9727 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009728 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9729 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009730 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009731 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009732 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009733 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009734 Ty = Context.LongLongTy;
9735 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009736 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009737 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009738
Sebastian Redlf53597f2009-03-15 17:47:39 +00009739 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009740}
9741
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009742static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009743 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009744 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009745 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009746
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009747 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9748 if (!PT)
9749 return;
9750
9751 // Check if the destination is of type 'id'.
9752 if (!PT->isObjCIdType()) {
9753 // Check if the destination is the 'NSString' interface.
9754 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9755 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9756 return;
9757 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009758
John McCall4b9c2d22011-11-06 09:01:30 +00009759 // Ignore any parens, implicit casts (should only be
9760 // array-to-pointer decays), and not-so-opaque values. The last is
9761 // important for making this trigger for property assignments.
9762 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9763 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9764 if (OV->getSourceExpr())
9765 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9766
9767 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009768 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009769 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009770
Douglas Gregor849b2432010-03-31 17:46:05 +00009771 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009772}
9773
Chris Lattner5cf216b2008-01-04 18:04:52 +00009774bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9775 SourceLocation Loc,
9776 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009777 Expr *SrcExpr, AssignmentAction Action,
9778 bool *Complained) {
9779 if (Complained)
9780 *Complained = false;
9781
Chris Lattner5cf216b2008-01-04 18:04:52 +00009782 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009783 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009784 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009785 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009786 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009787 ConversionFixItGenerator ConvHints;
9788 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009789 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009790
Chris Lattner5cf216b2008-01-04 18:04:52 +00009791 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009792 case Compatible:
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00009793 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9794 return false;
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009795
Chris Lattnerb7b61152008-01-04 18:22:42 +00009796 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009797 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009798 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9799 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009800 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009801 case IntToPointer:
9802 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009803 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9804 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009805 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009806 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009807 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009808 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009809 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9810 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009811 if (Hint.isNull() && !CheckInferredResultType) {
9812 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9813 }
9814 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009815 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009816 case IncompatiblePointerSign:
9817 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9818 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009819 case FunctionVoidPointer:
9820 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9821 break;
John McCall86c05f32011-02-01 00:10:29 +00009822 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009823 // Perform array-to-pointer decay if necessary.
9824 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9825
John McCall86c05f32011-02-01 00:10:29 +00009826 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9827 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9828 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9829 DiagKind = diag::err_typecheck_incompatible_address_space;
9830 break;
John McCallf85e1932011-06-15 23:02:42 +00009831
9832
9833 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009834 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009835 break;
John McCall86c05f32011-02-01 00:10:29 +00009836 }
9837
9838 llvm_unreachable("unknown error case for discarding qualifiers!");
9839 // fallthrough
9840 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009841 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009842 // If the qualifiers lost were because we were applying the
9843 // (deprecated) C++ conversion from a string literal to a char*
9844 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9845 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009846 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009847 // bit of refactoring (so that the second argument is an
9848 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009849 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009850 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009851 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009852 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9853 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009854 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9855 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009856 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009857 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009858 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009859 case IntToBlockPointer:
9860 DiagKind = diag::err_int_to_block_pointer;
9861 break;
9862 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009863 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009864 break;
Steve Naroff39579072008-10-14 22:18:38 +00009865 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009866 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009867 // it can give a more specific diagnostic.
9868 DiagKind = diag::warn_incompatible_qualified_id;
9869 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009870 case IncompatibleVectors:
9871 DiagKind = diag::warn_incompatible_vectors;
9872 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009873 case IncompatibleObjCWeakRef:
9874 DiagKind = diag::err_arc_weak_unavailable_assign;
9875 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009876 case Incompatible:
9877 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009878 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9879 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009880 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009881 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009882 break;
9883 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009884
Douglas Gregord4eea832010-04-09 00:35:39 +00009885 QualType FirstType, SecondType;
9886 switch (Action) {
9887 case AA_Assigning:
9888 case AA_Initializing:
9889 // The destination type comes first.
9890 FirstType = DstType;
9891 SecondType = SrcType;
9892 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009893
Douglas Gregord4eea832010-04-09 00:35:39 +00009894 case AA_Returning:
9895 case AA_Passing:
9896 case AA_Converting:
9897 case AA_Sending:
9898 case AA_Casting:
9899 // The source type comes first.
9900 FirstType = SrcType;
9901 SecondType = DstType;
9902 break;
9903 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009904
Anna Zaks67221552011-07-28 19:51:27 +00009905 PartialDiagnostic FDiag = PDiag(DiagKind);
9906 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9907
9908 // If we can fix the conversion, suggest the FixIts.
9909 assert(ConvHints.isNull() || Hint.isNull());
9910 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009911 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9912 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009913 FDiag << *HI;
9914 } else {
9915 FDiag << Hint;
9916 }
9917 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9918
Richard Trieu6efd4c52011-11-23 22:32:32 +00009919 if (MayHaveFunctionDiff)
9920 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9921
Anna Zaks67221552011-07-28 19:51:27 +00009922 Diag(Loc, FDiag);
9923
Richard Trieu6efd4c52011-11-23 22:32:32 +00009924 if (SecondType == Context.OverloadTy)
9925 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9926 FirstType);
9927
Douglas Gregor926df6c2011-06-11 01:09:30 +00009928 if (CheckInferredResultType)
9929 EmitRelatedResultTypeNote(SrcExpr);
9930
Douglas Gregora41a8c52010-04-22 00:20:18 +00009931 if (Complained)
9932 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009933 return isInvalid;
9934}
Anders Carlssone21555e2008-11-30 19:50:32 +00009935
Richard Smith282e7e62012-02-04 09:53:13 +00009936ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9937 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009938 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9939 public:
9940 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9941 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9942 }
9943 } Diagnoser;
9944
9945 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9946}
9947
9948ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9949 llvm::APSInt *Result,
9950 unsigned DiagID,
9951 bool AllowFold) {
9952 class IDDiagnoser : public VerifyICEDiagnoser {
9953 unsigned DiagID;
9954
9955 public:
9956 IDDiagnoser(unsigned DiagID)
9957 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9958
9959 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9960 S.Diag(Loc, DiagID) << SR;
9961 }
9962 } Diagnoser(DiagID);
9963
9964 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9965}
9966
9967void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9968 SourceRange SR) {
9969 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009970}
9971
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009972ExprResult
9973Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009974 VerifyICEDiagnoser &Diagnoser,
9975 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009976 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009977
David Blaikie4e4d0842012-03-11 07:00:24 +00009978 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009979 // C++11 [expr.const]p5:
9980 // If an expression of literal class type is used in a context where an
9981 // integral constant expression is required, then that class type shall
9982 // have a single non-explicit conversion function to an integral or
9983 // unscoped enumeration type
9984 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009985 if (!Diagnoser.Suppress) {
9986 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9987 public:
9988 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9989
9990 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9991 QualType T) {
9992 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9993 }
9994
9995 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9996 SourceLocation Loc,
9997 QualType T) {
9998 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9999 }
10000
10001 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10002 SourceLocation Loc,
10003 QualType T,
10004 QualType ConvTy) {
10005 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10006 }
10007
10008 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10009 CXXConversionDecl *Conv,
10010 QualType ConvTy) {
10011 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10012 << ConvTy->isEnumeralType() << ConvTy;
10013 }
10014
10015 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10016 QualType T) {
10017 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10018 }
10019
10020 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10021 CXXConversionDecl *Conv,
10022 QualType ConvTy) {
10023 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10024 << ConvTy->isEnumeralType() << ConvTy;
10025 }
10026
10027 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10028 SourceLocation Loc,
10029 QualType T,
10030 QualType ConvTy) {
10031 return DiagnosticBuilder::getEmpty();
10032 }
10033 } ConvertDiagnoser;
10034
10035 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10036 ConvertDiagnoser,
10037 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +000010038 } else {
10039 // The caller wants to silently enquire whether this is an ICE. Don't
10040 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010041 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10042 public:
10043 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10044
10045 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10046 QualType T) {
10047 return DiagnosticBuilder::getEmpty();
10048 }
10049
10050 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10051 SourceLocation Loc,
10052 QualType T) {
10053 return DiagnosticBuilder::getEmpty();
10054 }
10055
10056 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10057 SourceLocation Loc,
10058 QualType T,
10059 QualType ConvTy) {
10060 return DiagnosticBuilder::getEmpty();
10061 }
10062
10063 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10064 CXXConversionDecl *Conv,
10065 QualType ConvTy) {
10066 return DiagnosticBuilder::getEmpty();
10067 }
10068
10069 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10070 QualType T) {
10071 return DiagnosticBuilder::getEmpty();
10072 }
10073
10074 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10075 CXXConversionDecl *Conv,
10076 QualType ConvTy) {
10077 return DiagnosticBuilder::getEmpty();
10078 }
10079
10080 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10081 SourceLocation Loc,
10082 QualType T,
10083 QualType ConvTy) {
10084 return DiagnosticBuilder::getEmpty();
10085 }
10086 } ConvertDiagnoser;
10087
10088 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10089 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +000010090 }
10091 if (Converted.isInvalid())
10092 return Converted;
10093 E = Converted.take();
10094 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10095 return ExprError();
10096 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10097 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000010098 if (!Diagnoser.Suppress)
10099 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000010100 return ExprError();
10101 }
10102
Richard Smithdaaefc52011-12-14 23:32:26 +000010103 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10104 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +000010105 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000010106 if (Result)
10107 *Result = E->EvaluateKnownConstInt(Context);
10108 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010109 }
10110
Anders Carlssone21555e2008-11-30 19:50:32 +000010111 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +000010112 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10113 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000010114
Richard Smithdaaefc52011-12-14 23:32:26 +000010115 // Try to evaluate the expression, and produce diagnostics explaining why it's
10116 // not a constant expression as a side-effect.
10117 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10118 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10119
10120 // In C++11, we can rely on diagnostics being produced for any expression
10121 // which is not a constant expression. If no diagnostics were produced, then
10122 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +000010123 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000010124 if (Result)
10125 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010126 return Owned(E);
10127 }
10128
10129 // If our only note is the usual "invalid subexpression" note, just point
10130 // the caret at its location rather than producing an essentially
10131 // redundant note.
10132 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10133 diag::note_invalid_subexpr_in_const_expr) {
10134 DiagLoc = Notes[0].first;
10135 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000010136 }
10137
10138 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000010139 if (!Diagnoser.Suppress) {
10140 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000010141 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10142 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010143 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010144
Richard Smith282e7e62012-02-04 09:53:13 +000010145 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010146 }
10147
Douglas Gregorab41fe92012-05-04 22:38:52 +000010148 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010149 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10150 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010151
Anders Carlssone21555e2008-11-30 19:50:32 +000010152 if (Result)
10153 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010154 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010155}
Douglas Gregore0762c92009-06-19 23:52:42 +000010156
Eli Friedmanef331b72012-01-20 01:26:23 +000010157namespace {
10158 // Handle the case where we conclude a expression which we speculatively
10159 // considered to be unevaluated is actually evaluated.
10160 class TransformToPE : public TreeTransform<TransformToPE> {
10161 typedef TreeTransform<TransformToPE> BaseTransform;
10162
10163 public:
10164 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10165
10166 // Make sure we redo semantic analysis
10167 bool AlwaysRebuild() { return true; }
10168
Eli Friedman56ff2832012-02-06 23:29:57 +000010169 // Make sure we handle LabelStmts correctly.
10170 // FIXME: This does the right thing, but maybe we need a more general
10171 // fix to TreeTransform?
10172 StmtResult TransformLabelStmt(LabelStmt *S) {
10173 S->getDecl()->setStmt(0);
10174 return BaseTransform::TransformLabelStmt(S);
10175 }
10176
Eli Friedmanef331b72012-01-20 01:26:23 +000010177 // We need to special-case DeclRefExprs referring to FieldDecls which
10178 // are not part of a member pointer formation; normal TreeTransforming
10179 // doesn't catch this case because of the way we represent them in the AST.
10180 // FIXME: This is a bit ugly; is it really the best way to handle this
10181 // case?
10182 //
10183 // Error on DeclRefExprs referring to FieldDecls.
10184 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10185 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010186 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010187 return SemaRef.Diag(E->getLocation(),
10188 diag::err_invalid_non_static_member_use)
10189 << E->getDecl() << E->getSourceRange();
10190
10191 return BaseTransform::TransformDeclRefExpr(E);
10192 }
10193
10194 // Exception: filter out member pointer formation
10195 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10196 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10197 return E;
10198
10199 return BaseTransform::TransformUnaryOperator(E);
10200 }
10201
Douglas Gregore2c59132012-02-09 08:14:43 +000010202 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10203 // Lambdas never need to be transformed.
10204 return E;
10205 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010206 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010207}
10208
Eli Friedmanef331b72012-01-20 01:26:23 +000010209ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010210 assert(ExprEvalContexts.back().Context == Unevaluated &&
10211 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010212 ExprEvalContexts.back().Context =
10213 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10214 if (ExprEvalContexts.back().Context == Unevaluated)
10215 return E;
10216 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010217}
10218
Douglas Gregor2afce722009-11-26 00:44:06 +000010219void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010220Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010221 Decl *LambdaContextDecl,
10222 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010223 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010224 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010225 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010226 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010227 LambdaContextDecl,
10228 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010229 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010230 if (!MaybeODRUseExprs.empty())
10231 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010232}
10233
Eli Friedman80bfa3d2012-09-26 04:34:21 +000010234void
10235Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10236 ReuseLambdaContextDecl_t,
10237 bool IsDecltype) {
10238 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10239 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10240}
10241
Richard Trieu67e29332011-08-02 04:35:43 +000010242void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010243 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010244
Douglas Gregore2c59132012-02-09 08:14:43 +000010245 if (!Rec.Lambdas.empty()) {
10246 if (Rec.Context == Unevaluated) {
10247 // C++11 [expr.prim.lambda]p2:
10248 // A lambda-expression shall not appear in an unevaluated operand
10249 // (Clause 5).
10250 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10251 Diag(Rec.Lambdas[I]->getLocStart(),
10252 diag::err_lambda_unevaluated_operand);
10253 } else {
10254 // Mark the capture expressions odr-used. This was deferred
10255 // during lambda expression creation.
10256 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10257 LambdaExpr *Lambda = Rec.Lambdas[I];
10258 for (LambdaExpr::capture_init_iterator
10259 C = Lambda->capture_init_begin(),
10260 CEnd = Lambda->capture_init_end();
10261 C != CEnd; ++C) {
10262 MarkDeclarationsReferencedInExpr(*C);
10263 }
10264 }
10265 }
10266 }
10267
Douglas Gregor2afce722009-11-26 00:44:06 +000010268 // When are coming out of an unevaluated context, clear out any
10269 // temporaries that we may have created as part of the evaluation of
10270 // the expression in that context: they aren't relevant because they
10271 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010272 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010273 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10274 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010275 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010276 CleanupVarDeclMarking();
10277 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010278 // Otherwise, merge the contexts together.
10279 } else {
10280 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010281 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10282 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010283 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010284
10285 // Pop the current expression evaluation context off the stack.
10286 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010287}
Douglas Gregore0762c92009-06-19 23:52:42 +000010288
John McCallf85e1932011-06-15 23:02:42 +000010289void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010290 ExprCleanupObjects.erase(
10291 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10292 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010293 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010294 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010295}
10296
Eli Friedman71b8fb52012-01-21 01:01:51 +000010297ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10298 if (!E->getType()->isVariablyModifiedType())
10299 return E;
10300 return TranformToPotentiallyEvaluated(E);
10301}
10302
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010303static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010304 // Do not mark anything as "used" within a dependent context; wait for
10305 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010306 if (SemaRef.CurContext->isDependentContext())
10307 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010308
Eli Friedman5f2987c2012-02-02 03:46:19 +000010309 switch (SemaRef.ExprEvalContexts.back().Context) {
10310 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010311 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010312 // (Depending on how you read the standard, we actually do need to do
10313 // something here for null pointer constants, but the standard's
10314 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010315 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010316
Eli Friedman5f2987c2012-02-02 03:46:19 +000010317 case Sema::ConstantEvaluated:
10318 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010319 // We are in a potentially evaluated expression (or a constant-expression
10320 // in C++03); we need to do implicit template instantiation, implicitly
10321 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010322 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010323
Eli Friedman5f2987c2012-02-02 03:46:19 +000010324 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010325 // Referenced declarations will only be used if the construct in the
10326 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010327 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010328 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010329 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010330}
10331
10332/// \brief Mark a function referenced, and check whether it is odr-used
10333/// (C++ [basic.def.odr]p2, C99 6.9p3)
10334void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10335 assert(Func && "No function?");
10336
10337 Func->setReferenced();
10338
Richard Smith57b9c4e2012-02-14 22:25:15 +000010339 // Don't mark this function as used multiple times, unless it's a constexpr
10340 // function which we need to instantiate.
10341 if (Func->isUsed(false) &&
10342 !(Func->isConstexpr() && !Func->getBody() &&
10343 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010344 return;
10345
10346 if (!IsPotentiallyEvaluatedContext(*this))
10347 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010348
Douglas Gregore0762c92009-06-19 23:52:42 +000010349 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010350 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010351 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010352 if (Constructor->isDefaultConstructor()) {
10353 if (Constructor->isTrivial())
10354 return;
10355 if (!Constructor->isUsed(false))
10356 DefineImplicitDefaultConstructor(Loc, Constructor);
10357 } else if (Constructor->isCopyConstructor()) {
10358 if (!Constructor->isUsed(false))
10359 DefineImplicitCopyConstructor(Loc, Constructor);
10360 } else if (Constructor->isMoveConstructor()) {
10361 if (!Constructor->isUsed(false))
10362 DefineImplicitMoveConstructor(Loc, Constructor);
10363 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010364 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010365
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010366 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010367 } else if (CXXDestructorDecl *Destructor =
10368 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010369 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10370 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010371 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010372 if (Destructor->isVirtual())
10373 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010374 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010375 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10376 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010377 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010378 if (!MethodDecl->isUsed(false)) {
10379 if (MethodDecl->isCopyAssignmentOperator())
10380 DefineImplicitCopyAssignment(Loc, MethodDecl);
10381 else
10382 DefineImplicitMoveAssignment(Loc, MethodDecl);
10383 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010384 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10385 MethodDecl->getParent()->isLambda()) {
10386 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10387 if (Conversion->isLambdaToBlockPointerConversion())
10388 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10389 else
10390 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010391 } else if (MethodDecl->isVirtual())
10392 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010393 }
John McCall15e310a2011-02-19 02:53:41 +000010394
Eli Friedman5f2987c2012-02-02 03:46:19 +000010395 // Recursive functions should be marked when used from another function.
10396 // FIXME: Is this really right?
10397 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010398
Richard Smithb9d0b762012-07-27 04:22:15 +000010399 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010400 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010401 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010402 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10403 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010404
Eli Friedman5f2987c2012-02-02 03:46:19 +000010405 // Implicit instantiation of function templates and member functions of
10406 // class templates.
10407 if (Func->isImplicitlyInstantiable()) {
10408 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010409 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010410 if (FunctionTemplateSpecializationInfo *SpecInfo
10411 = Func->getTemplateSpecializationInfo()) {
10412 if (SpecInfo->getPointOfInstantiation().isInvalid())
10413 SpecInfo->setPointOfInstantiation(Loc);
10414 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010415 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010416 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010417 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10418 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010419 } else if (MemberSpecializationInfo *MSInfo
10420 = Func->getMemberSpecializationInfo()) {
10421 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010422 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010423 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010424 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010425 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010426 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10427 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010428 }
Mike Stump1eb44332009-09-09 15:08:12 +000010429
Richard Smith57b9c4e2012-02-14 22:25:15 +000010430 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010431 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10432 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010433 PendingLocalImplicitInstantiations.push_back(
10434 std::make_pair(Func, PointOfInstantiation));
10435 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010436 // Do not defer instantiations of constexpr functions, to avoid the
10437 // expression evaluator needing to call back into Sema if it sees a
10438 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010439 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010440 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010441 PendingInstantiations.push_back(std::make_pair(Func,
10442 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010443 // Notify the consumer that a function was implicitly instantiated.
10444 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10445 }
John McCall15e310a2011-02-19 02:53:41 +000010446 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010447 } else {
10448 // Walk redefinitions, as some of them may be instantiable.
10449 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10450 e(Func->redecls_end()); i != e; ++i) {
10451 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10452 MarkFunctionReferenced(Loc, *i);
10453 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010454 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010455
10456 // Keep track of used but undefined functions.
10457 if (!Func->isPure() && !Func->hasBody() &&
10458 Func->getLinkage() != ExternalLinkage) {
10459 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10460 if (old.isInvalid()) old = Loc;
10461 }
10462
10463 Func->setUsed(true);
10464}
10465
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010466static void
10467diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10468 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010469 DeclContext *VarDC = var->getDeclContext();
10470
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010471 // If the parameter still belongs to the translation unit, then
10472 // we're actually just using one parameter in the declaration of
10473 // the next.
10474 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010475 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010476 return;
10477
Eli Friedman0a294222012-02-07 00:15:00 +000010478 // For C code, don't diagnose about capture if we're not actually in code
10479 // right now; it's impossible to write a non-constant expression outside of
10480 // function context, so we'll get other (more useful) diagnostics later.
10481 //
10482 // For C++, things get a bit more nasty... it would be nice to suppress this
10483 // diagnostic for certain cases like using a local variable in an array bound
10484 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010485 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010486 return;
10487
Eli Friedman0a294222012-02-07 00:15:00 +000010488 if (isa<CXXMethodDecl>(VarDC) &&
10489 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10490 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10491 << var->getIdentifier();
10492 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10493 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10494 << var->getIdentifier() << fn->getDeclName();
10495 } else if (isa<BlockDecl>(VarDC)) {
10496 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10497 << var->getIdentifier();
10498 } else {
10499 // FIXME: Is there any other context where a local variable can be
10500 // declared?
10501 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10502 << var->getIdentifier();
10503 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010504
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010505 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10506 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010507
10508 // FIXME: Add additional diagnostic info about class etc. which prevents
10509 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010510}
10511
Douglas Gregorf8af9822012-02-12 18:42:33 +000010512/// \brief Capture the given variable in the given lambda expression.
10513static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010514 VarDecl *Var, QualType FieldType,
10515 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010516 SourceLocation Loc,
10517 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010518 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010519
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010520 // Build the non-static data member.
10521 FieldDecl *Field
10522 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10523 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010524 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010525 Field->setImplicit(true);
10526 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010527 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010528
10529 // C++11 [expr.prim.lambda]p21:
10530 // When the lambda-expression is evaluated, the entities that
10531 // are captured by copy are used to direct-initialize each
10532 // corresponding non-static data member of the resulting closure
10533 // object. (For array members, the array elements are
10534 // direct-initialized in increasing subscript order.) These
10535 // initializations are performed in the (unspecified) order in
10536 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010537
Douglas Gregore2c59132012-02-09 08:14:43 +000010538 // Introduce a new evaluation context for the initialization, so
10539 // that temporaries introduced as part of the capture are retained
10540 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010541 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10542
Douglas Gregor73d90922012-02-10 09:26:04 +000010543 // C++ [expr.prim.labda]p12:
10544 // An entity captured by a lambda-expression is odr-used (3.2) in
10545 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010546 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10547 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010548 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010549 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010550
10551 // When the field has array type, create index variables for each
10552 // dimension of the array. We use these index variables to subscript
10553 // the source array, and other clients (e.g., CodeGen) will perform
10554 // the necessary iteration with these index variables.
10555 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010556 QualType BaseType = FieldType;
10557 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010558 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010559 while (const ConstantArrayType *Array
10560 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010561 // Create the iteration variable for this array index.
10562 IdentifierInfo *IterationVarName = 0;
10563 {
10564 SmallString<8> Str;
10565 llvm::raw_svector_ostream OS(Str);
10566 OS << "__i" << IndexVariables.size();
10567 IterationVarName = &S.Context.Idents.get(OS.str());
10568 }
10569 VarDecl *IterationVar
10570 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10571 IterationVarName, SizeType,
10572 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10573 SC_None, SC_None);
10574 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010575 LSI->ArrayIndexVars.push_back(IterationVar);
10576
Douglas Gregor18fe0842012-02-09 02:45:47 +000010577 // Create a reference to the iteration variable.
10578 ExprResult IterationVarRef
10579 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10580 assert(!IterationVarRef.isInvalid() &&
10581 "Reference to invented variable cannot fail!");
10582 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10583 assert(!IterationVarRef.isInvalid() &&
10584 "Conversion of invented variable cannot fail!");
10585
10586 // Subscript the array with this iteration variable.
10587 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10588 Ref, Loc, IterationVarRef.take(), Loc);
10589 if (Subscript.isInvalid()) {
10590 S.CleanupVarDeclMarking();
10591 S.DiscardCleanupsInEvaluationContext();
10592 S.PopExpressionEvaluationContext();
10593 return ExprError();
10594 }
10595
10596 Ref = Subscript.take();
10597 BaseType = Array->getElementType();
10598 }
10599
10600 // Construct the entity that we will be initializing. For an array, this
10601 // will be first element in the array, which may require several levels
10602 // of array-subscript entities.
10603 SmallVector<InitializedEntity, 4> Entities;
10604 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010605 Entities.push_back(
10606 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010607 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10608 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10609 0,
10610 Entities.back()));
10611
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010612 InitializationKind InitKind
10613 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010614 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010615 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010616 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010617 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010618
10619 // If this initialization requires any cleanups (e.g., due to a
10620 // default argument to a copy constructor), note that for the
10621 // lambda.
10622 if (S.ExprNeedsCleanups)
10623 LSI->ExprNeedsCleanups = true;
10624
10625 // Exit the expression evaluation context used for the capture.
10626 S.CleanupVarDeclMarking();
10627 S.DiscardCleanupsInEvaluationContext();
10628 S.PopExpressionEvaluationContext();
10629 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010630}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010631
Douglas Gregor999713e2012-02-18 09:37:24 +000010632bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10633 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10634 bool BuildAndDiagnose,
10635 QualType &CaptureType,
10636 QualType &DeclRefType) {
10637 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010638
Eli Friedmanb942cb22012-02-03 22:47:37 +000010639 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010640 if (Var->getDeclContext() == DC) return true;
10641 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010642
Douglas Gregorf8af9822012-02-12 18:42:33 +000010643 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010644
Douglas Gregor999713e2012-02-18 09:37:24 +000010645 // Walk up the stack to determine whether we can capture the variable,
10646 // performing the "simple" checks that don't depend on type. We stop when
10647 // we've either hit the declared scope of the variable or find an existing
10648 // capture of that variable.
10649 CaptureType = Var->getType();
10650 DeclRefType = CaptureType.getNonReferenceType();
10651 bool Explicit = (Kind != TryCapture_Implicit);
10652 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010653 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010654 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010655 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010656 DeclContext *ParentDC;
10657 if (isa<BlockDecl>(DC))
10658 ParentDC = DC->getParent();
10659 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010660 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010661 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10662 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010663 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010664 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010665 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010666 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010667 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010668
Eli Friedmanb942cb22012-02-03 22:47:37 +000010669 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010670 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010671
Eli Friedmanb942cb22012-02-03 22:47:37 +000010672 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010673 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010674 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010675 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010676
10677 // Retrieve the capture type for this variable.
10678 CaptureType = CSI->getCapture(Var).getCaptureType();
10679
10680 // Compute the type of an expression that refers to this variable.
10681 DeclRefType = CaptureType.getNonReferenceType();
10682
10683 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10684 if (Cap.isCopyCapture() &&
10685 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10686 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010687 break;
10688 }
10689
Douglas Gregorf8af9822012-02-12 18:42:33 +000010690 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010691 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010692
10693 // Lambdas are not allowed to capture unnamed variables
10694 // (e.g. anonymous unions).
10695 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10696 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010697 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010698 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010699 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10700 Diag(Var->getLocation(), diag::note_declared_at);
10701 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010702 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010703 }
10704
10705 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010706 if (Var->getType()->isVariablyModifiedType()) {
10707 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010708 if (IsBlock)
10709 Diag(Loc, diag::err_ref_vm_type);
10710 else
10711 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10712 Diag(Var->getLocation(), diag::note_previous_decl)
10713 << Var->getDeclName();
10714 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010715 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010716 }
10717
Eli Friedmanb942cb22012-02-03 22:47:37 +000010718 // Lambdas are not allowed to capture __block variables; they don't
10719 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010720 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010721 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010722 Diag(Loc, diag::err_lambda_capture_block)
10723 << Var->getDeclName();
10724 Diag(Var->getLocation(), diag::note_previous_decl)
10725 << Var->getDeclName();
10726 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010727 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010728 }
10729
Douglas Gregorf8af9822012-02-12 18:42:33 +000010730 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10731 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010732 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010733 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10734 Diag(Var->getLocation(), diag::note_previous_decl)
10735 << Var->getDeclName();
10736 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10737 diag::note_lambda_decl);
10738 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010739 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010740 }
10741
10742 FunctionScopesIndex--;
10743 DC = ParentDC;
10744 Explicit = false;
10745 } while (!Var->getDeclContext()->Equals(DC));
10746
Douglas Gregor999713e2012-02-18 09:37:24 +000010747 // Walk back down the scope stack, computing the type of the capture at
10748 // each step, checking type-specific requirements, and adding captures if
10749 // requested.
10750 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10751 ++I) {
10752 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010753
Douglas Gregor999713e2012-02-18 09:37:24 +000010754 // Compute the type of the capture and of a reference to the capture within
10755 // this scope.
10756 if (isa<BlockScopeInfo>(CSI)) {
10757 Expr *CopyExpr = 0;
10758 bool ByRef = false;
10759
10760 // Blocks are not allowed to capture arrays.
10761 if (CaptureType->isArrayType()) {
10762 if (BuildAndDiagnose) {
10763 Diag(Loc, diag::err_ref_array_type);
10764 Diag(Var->getLocation(), diag::note_previous_decl)
10765 << Var->getDeclName();
10766 }
10767 return true;
10768 }
10769
John McCall100c6492012-03-30 05:23:48 +000010770 // Forbid the block-capture of autoreleasing variables.
10771 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10772 if (BuildAndDiagnose) {
10773 Diag(Loc, diag::err_arc_autoreleasing_capture)
10774 << /*block*/ 0;
10775 Diag(Var->getLocation(), diag::note_previous_decl)
10776 << Var->getDeclName();
10777 }
10778 return true;
10779 }
10780
Douglas Gregor999713e2012-02-18 09:37:24 +000010781 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10782 // Block capture by reference does not change the capture or
10783 // declaration reference types.
10784 ByRef = true;
10785 } else {
10786 // Block capture by copy introduces 'const'.
10787 CaptureType = CaptureType.getNonReferenceType().withConst();
10788 DeclRefType = CaptureType;
10789
David Blaikie4e4d0842012-03-11 07:00:24 +000010790 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010791 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10792 // The capture logic needs the destructor, so make sure we mark it.
10793 // Usually this is unnecessary because most local variables have
10794 // their destructors marked at declaration time, but parameters are
10795 // an exception because it's technically only the call site that
10796 // actually requires the destructor.
10797 if (isa<ParmVarDecl>(Var))
10798 FinalizeVarWithDestructor(Var, Record);
10799
10800 // According to the blocks spec, the capture of a variable from
10801 // the stack requires a const copy constructor. This is not true
10802 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010803 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010804 DeclRefType.withConst(),
10805 VK_LValue, Loc);
10806 ExprResult Result
10807 = PerformCopyInitialization(
10808 InitializedEntity::InitializeBlock(Var->getLocation(),
10809 CaptureType, false),
10810 Loc, Owned(DeclRef));
10811
10812 // Build a full-expression copy expression if initialization
10813 // succeeded and used a non-trivial constructor. Recover from
10814 // errors by pretending that the copy isn't necessary.
10815 if (!Result.isInvalid() &&
10816 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10817 ->isTrivial()) {
10818 Result = MaybeCreateExprWithCleanups(Result);
10819 CopyExpr = Result.take();
10820 }
10821 }
10822 }
10823 }
10824
10825 // Actually capture the variable.
10826 if (BuildAndDiagnose)
10827 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10828 SourceLocation(), CaptureType, CopyExpr);
10829 Nested = true;
10830 continue;
10831 }
Douglas Gregor68932842012-02-18 05:51:20 +000010832
Douglas Gregor999713e2012-02-18 09:37:24 +000010833 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10834
10835 // Determine whether we are capturing by reference or by value.
10836 bool ByRef = false;
10837 if (I == N - 1 && Kind != TryCapture_Implicit) {
10838 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010839 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010840 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010841 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010842
10843 // Compute the type of the field that will capture this variable.
10844 if (ByRef) {
10845 // C++11 [expr.prim.lambda]p15:
10846 // An entity is captured by reference if it is implicitly or
10847 // explicitly captured but not captured by copy. It is
10848 // unspecified whether additional unnamed non-static data
10849 // members are declared in the closure type for entities
10850 // captured by reference.
10851 //
10852 // FIXME: It is not clear whether we want to build an lvalue reference
10853 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10854 // to do the former, while EDG does the latter. Core issue 1249 will
10855 // clarify, but for now we follow GCC because it's a more permissive and
10856 // easily defensible position.
10857 CaptureType = Context.getLValueReferenceType(DeclRefType);
10858 } else {
10859 // C++11 [expr.prim.lambda]p14:
10860 // For each entity captured by copy, an unnamed non-static
10861 // data member is declared in the closure type. The
10862 // declaration order of these members is unspecified. The type
10863 // of such a data member is the type of the corresponding
10864 // captured entity if the entity is not a reference to an
10865 // object, or the referenced type otherwise. [Note: If the
10866 // captured entity is a reference to a function, the
10867 // corresponding data member is also a reference to a
10868 // function. - end note ]
10869 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10870 if (!RefType->getPointeeType()->isFunctionType())
10871 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010872 }
John McCall100c6492012-03-30 05:23:48 +000010873
10874 // Forbid the lambda copy-capture of autoreleasing variables.
10875 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10876 if (BuildAndDiagnose) {
10877 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10878 Diag(Var->getLocation(), diag::note_previous_decl)
10879 << Var->getDeclName();
10880 }
10881 return true;
10882 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010883 }
10884
Douglas Gregor999713e2012-02-18 09:37:24 +000010885 // Capture this variable in the lambda.
10886 Expr *CopyExpr = 0;
10887 if (BuildAndDiagnose) {
10888 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010889 DeclRefType, Loc,
10890 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010891 if (!Result.isInvalid())
10892 CopyExpr = Result.take();
10893 }
10894
10895 // Compute the type of a reference to this captured variable.
10896 if (ByRef)
10897 DeclRefType = CaptureType.getNonReferenceType();
10898 else {
10899 // C++ [expr.prim.lambda]p5:
10900 // The closure type for a lambda-expression has a public inline
10901 // function call operator [...]. This function call operator is
10902 // declared const (9.3.1) if and only if the lambda-expression’s
10903 // parameter-declaration-clause is not followed by mutable.
10904 DeclRefType = CaptureType.getNonReferenceType();
10905 if (!LSI->Mutable && !CaptureType->isReferenceType())
10906 DeclRefType.addConst();
10907 }
10908
10909 // Add the capture.
10910 if (BuildAndDiagnose)
10911 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10912 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010913 Nested = true;
10914 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010915
10916 return false;
10917}
10918
10919bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10920 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10921 QualType CaptureType;
10922 QualType DeclRefType;
10923 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10924 /*BuildAndDiagnose=*/true, CaptureType,
10925 DeclRefType);
10926}
10927
10928QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10929 QualType CaptureType;
10930 QualType DeclRefType;
10931
10932 // Determine whether we can capture this variable.
10933 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10934 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10935 return QualType();
10936
10937 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010938}
10939
Eli Friedmand2cce132012-02-02 23:15:15 +000010940static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10941 SourceLocation Loc) {
10942 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010943 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010944 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010945 Var->getLinkage() != ExternalLinkage &&
10946 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010947 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10948 if (old.isInvalid()) old = Loc;
10949 }
10950
Douglas Gregor999713e2012-02-18 09:37:24 +000010951 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010952
Eli Friedmand2cce132012-02-02 23:15:15 +000010953 Var->setUsed(true);
10954}
10955
10956void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10957 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10958 // an object that satisfies the requirements for appearing in a
10959 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10960 // is immediately applied." This function handles the lvalue-to-rvalue
10961 // conversion part.
10962 MaybeODRUseExprs.erase(E->IgnoreParens());
10963}
10964
Eli Friedmanac626012012-02-29 03:16:56 +000010965ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10966 if (!Res.isUsable())
10967 return Res;
10968
10969 // If a constant-expression is a reference to a variable where we delay
10970 // deciding whether it is an odr-use, just assume we will apply the
10971 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10972 // (a non-type template argument), we have special handling anyway.
10973 UpdateMarkingForLValueToRValue(Res.get());
10974 return Res;
10975}
10976
Eli Friedmand2cce132012-02-02 23:15:15 +000010977void Sema::CleanupVarDeclMarking() {
10978 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10979 e = MaybeODRUseExprs.end();
10980 i != e; ++i) {
10981 VarDecl *Var;
10982 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010983 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010984 Var = cast<VarDecl>(DRE->getDecl());
10985 Loc = DRE->getLocation();
10986 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10987 Var = cast<VarDecl>(ME->getMemberDecl());
10988 Loc = ME->getMemberLoc();
10989 } else {
10990 llvm_unreachable("Unexpcted expression");
10991 }
10992
10993 MarkVarDeclODRUsed(*this, Var, Loc);
10994 }
10995
10996 MaybeODRUseExprs.clear();
10997}
10998
10999// Mark a VarDecl referenced, and perform the necessary handling to compute
11000// odr-uses.
11001static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11002 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011003 Var->setReferenced();
11004
Eli Friedmand2cce132012-02-02 23:15:15 +000011005 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011006 return;
11007
11008 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000011009 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011010 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11011 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000011012 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11013 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011014 (!AlreadyInstantiated ||
11015 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000011016 if (!AlreadyInstantiated) {
11017 // This is a modification of an existing AST node. Notify listeners.
11018 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11019 L->StaticDataMemberInstantiated(Var);
11020 MSInfo->setPointOfInstantiation(Loc);
11021 }
11022 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011023 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000011024 // Do not defer instantiations of variables which could be used in a
11025 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000011026 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011027 else
Richard Smith37ce0102012-02-15 02:42:50 +000011028 SemaRef.PendingInstantiations.push_back(
11029 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000011030 }
11031 }
11032
Richard Smith5016a702012-10-20 01:38:33 +000011033 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11034 // the requirements for appearing in a constant expression (5.19) and, if
11035 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedmand2cce132012-02-02 23:15:15 +000011036 // is immediately applied." We check the first part here, and
11037 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11038 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5016a702012-10-20 01:38:33 +000011039 // C++03 depends on whether we get the C++03 version correct. The second
11040 // part does not apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000011041 const VarDecl *DefVD;
Richard Smith5016a702012-10-20 01:38:33 +000011042 if (E && !isa<ParmVarDecl>(Var) &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000011043 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Richard Smith5016a702012-10-20 01:38:33 +000011044 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11045 if (!Var->getType()->isReferenceType())
11046 SemaRef.MaybeODRUseExprs.insert(E);
11047 } else
Eli Friedmand2cce132012-02-02 23:15:15 +000011048 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11049}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011050
Eli Friedmand2cce132012-02-02 23:15:15 +000011051/// \brief Mark a variable referenced, and check whether it is odr-used
11052/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11053/// used directly for normal expressions referring to VarDecl.
11054void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11055 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011056}
11057
11058static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11059 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000011060 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11061 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11062 return;
11063 }
11064
Eli Friedman5f2987c2012-02-02 03:46:19 +000011065 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011066
11067 // If this is a call to a method via a cast, also mark the method in the
11068 // derived class used in case codegen can devirtualize the call.
11069 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11070 if (!ME)
11071 return;
11072 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11073 if (!MD)
11074 return;
11075 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000011076 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011077 if (!MostDerivedClassDecl)
11078 return;
11079 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000011080 if (!DM)
11081 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000011082 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011083}
Eli Friedman5f2987c2012-02-02 03:46:19 +000011084
Eli Friedman5f2987c2012-02-02 03:46:19 +000011085/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11086void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11087 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11088}
11089
11090/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11091void Sema::MarkMemberReferenced(MemberExpr *E) {
11092 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11093}
11094
Douglas Gregor73d90922012-02-10 09:26:04 +000011095/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000011096/// marks the declaration referenced, and performs odr-use checking for functions
11097/// and variables. This method should not be used when building an normal
11098/// expression which refers to a variable.
11099void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11100 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11101 MarkVariableReferenced(Loc, VD);
11102 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11103 MarkFunctionReferenced(Loc, FD);
11104 else
11105 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000011106}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011107
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011108namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011109 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011110 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011111 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011112 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11113 Sema &S;
11114 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011115
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011116 public:
11117 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011118
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011119 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011120
11121 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11122 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011123 };
11124}
11125
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011126bool MarkReferencedDecls::TraverseTemplateArgument(
11127 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011128 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000011129 if (Decl *D = Arg.getAsDecl())
11130 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011131 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011132
11133 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011134}
11135
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011136bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011137 if (ClassTemplateSpecializationDecl *Spec
11138 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11139 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000011140 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011141 }
11142
Chandler Carruthe3e210c2010-06-10 10:31:57 +000011143 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011144}
11145
11146void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11147 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000011148 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000011149}
11150
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011151namespace {
11152 /// \brief Helper class that marks all of the declarations referenced by
11153 /// potentially-evaluated subexpressions as "referenced".
11154 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11155 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011156 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011157
11158 public:
11159 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11160
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011161 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11162 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011163
11164 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011165 // If we were asked not to visit local variables, don't.
11166 if (SkipLocalVariables) {
11167 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11168 if (VD->hasLocalStorage())
11169 return;
11170 }
11171
Eli Friedman5f2987c2012-02-02 03:46:19 +000011172 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011173 }
11174
11175 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011176 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011177 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011178 }
11179
John McCall80ee6e82011-11-10 05:35:25 +000011180 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011181 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011182 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11183 Visit(E->getSubExpr());
11184 }
11185
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011186 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011187 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011188 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011189 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011190 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011191 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011192 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011193
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011194 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11195 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011196 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011197 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11198 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11199 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011200 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011201 S.LookupDestructor(Record));
11202 }
11203
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011204 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011205 }
11206
11207 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011208 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011209 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011210 }
11211
Douglas Gregor102ff972010-10-19 17:17:35 +000011212 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11213 Visit(E->getExpr());
11214 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011215
11216 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11217 Inherited::VisitImplicitCastExpr(E);
11218
11219 if (E->getCastKind() == CK_LValueToRValue)
11220 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11221 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011222 };
11223}
11224
11225/// \brief Mark any declarations that appear within this expression or any
11226/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011227///
11228/// \param SkipLocalVariables If true, don't mark local variables as
11229/// 'referenced'.
11230void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11231 bool SkipLocalVariables) {
11232 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011233}
11234
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011235/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11236/// of the program being compiled.
11237///
11238/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011239/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011240/// possibility that the code will actually be executable. Code in sizeof()
11241/// expressions, code used only during overload resolution, etc., are not
11242/// potentially evaluated. This routine will suppress such diagnostics or,
11243/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011244/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011245/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011246///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011247/// This routine should be used for all diagnostics that describe the run-time
11248/// behavior of a program, such as passing a non-POD value through an ellipsis.
11249/// Failure to do so will likely result in spurious diagnostics or failures
11250/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011251bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011252 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011253 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011254 case Unevaluated:
11255 // The argument will never be evaluated, so don't complain.
11256 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011257
Richard Smithf6702a32011-12-20 02:08:33 +000011258 case ConstantEvaluated:
11259 // Relevant diagnostics should be produced by constant evaluation.
11260 break;
11261
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011262 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011263 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011264 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011265 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011266 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011267 }
11268 else
11269 Diag(Loc, PD);
11270
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011271 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011272 }
11273
11274 return false;
11275}
11276
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011277bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11278 CallExpr *CE, FunctionDecl *FD) {
11279 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11280 return false;
11281
Richard Smith76f3f692012-02-22 02:04:18 +000011282 // If we're inside a decltype's expression, don't check for a valid return
11283 // type or construct temporaries until we know whether this is the last call.
11284 if (ExprEvalContexts.back().IsDecltype) {
11285 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11286 return false;
11287 }
11288
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011289 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011290 FunctionDecl *FD;
11291 CallExpr *CE;
11292
11293 public:
11294 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11295 : FD(FD), CE(CE) { }
11296
11297 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11298 if (!FD) {
11299 S.Diag(Loc, diag::err_call_incomplete_return)
11300 << T << CE->getSourceRange();
11301 return;
11302 }
11303
11304 S.Diag(Loc, diag::err_call_function_incomplete_return)
11305 << CE->getSourceRange() << FD->getDeclName() << T;
11306 S.Diag(FD->getLocation(),
11307 diag::note_function_with_incomplete_return_type_declared_here)
11308 << FD->getDeclName();
11309 }
11310 } Diagnoser(FD, CE);
11311
11312 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011313 return true;
11314
11315 return false;
11316}
11317
Douglas Gregor92c3a042011-01-19 16:50:08 +000011318// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011319// will prevent this condition from triggering, which is what we want.
11320void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11321 SourceLocation Loc;
11322
John McCalla52ef082009-11-11 02:41:58 +000011323 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011324 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011325
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011326 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011327 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011328 return;
11329
Douglas Gregor92c3a042011-01-19 16:50:08 +000011330 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11331
John McCallc8d8ac52009-11-12 00:06:05 +000011332 // Greylist some idioms by putting them into a warning subcategory.
11333 if (ObjCMessageExpr *ME
11334 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11335 Selector Sel = ME->getSelector();
11336
John McCallc8d8ac52009-11-12 00:06:05 +000011337 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011338 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011339 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11340
11341 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011342 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011343 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11344 }
John McCalla52ef082009-11-11 02:41:58 +000011345
John McCall5a881bb2009-10-12 21:59:07 +000011346 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011347 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011348 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011349 return;
11350
Douglas Gregor92c3a042011-01-19 16:50:08 +000011351 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011352 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000011353 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11354 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11355 else {
John McCall5a881bb2009-10-12 21:59:07 +000011356 // Not an assignment.
11357 return;
11358 }
11359
Douglas Gregor55b38842010-04-14 16:09:52 +000011360 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011361
Daniel Dunbar96a00142012-03-09 18:35:03 +000011362 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011363 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11364 Diag(Loc, diag::note_condition_assign_silence)
11365 << FixItHint::CreateInsertion(Open, "(")
11366 << FixItHint::CreateInsertion(Close, ")");
11367
Douglas Gregor92c3a042011-01-19 16:50:08 +000011368 if (IsOrAssign)
11369 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11370 << FixItHint::CreateReplacement(Loc, "!=");
11371 else
11372 Diag(Loc, diag::note_condition_assign_to_comparison)
11373 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011374}
11375
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011376/// \brief Redundant parentheses over an equality comparison can indicate
11377/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011378void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011379 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011380 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011381 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11382 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011383 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011384 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011385 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011386
Richard Trieuccd891a2011-09-09 01:45:06 +000011387 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011388
11389 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011390 if (opE->getOpcode() == BO_EQ &&
11391 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11392 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011393 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011394
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011395 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011396 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011397 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011398 << FixItHint::CreateRemoval(ParenERange.getBegin())
11399 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011400 Diag(Loc, diag::note_equality_comparison_to_assign)
11401 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011402 }
11403}
11404
John Wiegley429bb272011-04-08 18:41:53 +000011405ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011406 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011407 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11408 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011409
John McCall864c0412011-04-26 20:42:42 +000011410 ExprResult result = CheckPlaceholderExpr(E);
11411 if (result.isInvalid()) return ExprError();
11412 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011413
John McCall864c0412011-04-26 20:42:42 +000011414 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011415 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011416 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11417
John Wiegley429bb272011-04-08 18:41:53 +000011418 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11419 if (ERes.isInvalid())
11420 return ExprError();
11421 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011422
11423 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011424 if (!T->isScalarType()) { // C99 6.8.4.1p1
11425 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11426 << T << E->getSourceRange();
11427 return ExprError();
11428 }
John McCall5a881bb2009-10-12 21:59:07 +000011429 }
11430
John Wiegley429bb272011-04-08 18:41:53 +000011431 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011432}
Douglas Gregor586596f2010-05-06 17:25:47 +000011433
John McCall60d7b3a2010-08-24 06:29:42 +000011434ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011435 Expr *SubExpr) {
11436 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011437 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011438
Richard Trieuccd891a2011-09-09 01:45:06 +000011439 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011440}
John McCall2a984ca2010-10-12 00:20:44 +000011441
John McCall1de4d4e2011-04-07 08:22:57 +000011442namespace {
John McCall755d8492011-04-12 00:42:48 +000011443 /// A visitor for rebuilding a call to an __unknown_any expression
11444 /// to have an appropriate type.
11445 struct RebuildUnknownAnyFunction
11446 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11447
11448 Sema &S;
11449
11450 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11451
11452 ExprResult VisitStmt(Stmt *S) {
11453 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011454 }
11455
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011456 ExprResult VisitExpr(Expr *E) {
11457 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11458 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011459 return ExprError();
11460 }
11461
11462 /// Rebuild an expression which simply semantically wraps another
11463 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011464 template <class T> ExprResult rebuildSugarExpr(T *E) {
11465 ExprResult SubResult = Visit(E->getSubExpr());
11466 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011467
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011468 Expr *SubExpr = SubResult.take();
11469 E->setSubExpr(SubExpr);
11470 E->setType(SubExpr->getType());
11471 E->setValueKind(SubExpr->getValueKind());
11472 assert(E->getObjectKind() == OK_Ordinary);
11473 return E;
John McCall755d8492011-04-12 00:42:48 +000011474 }
11475
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011476 ExprResult VisitParenExpr(ParenExpr *E) {
11477 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011478 }
11479
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011480 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11481 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011482 }
11483
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011484 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11485 ExprResult SubResult = Visit(E->getSubExpr());
11486 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011487
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011488 Expr *SubExpr = SubResult.take();
11489 E->setSubExpr(SubExpr);
11490 E->setType(S.Context.getPointerType(SubExpr->getType()));
11491 assert(E->getValueKind() == VK_RValue);
11492 assert(E->getObjectKind() == OK_Ordinary);
11493 return E;
John McCall755d8492011-04-12 00:42:48 +000011494 }
11495
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011496 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11497 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011498
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011499 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011500
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011501 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011502 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011503 !(isa<CXXMethodDecl>(VD) &&
11504 cast<CXXMethodDecl>(VD)->isInstance()))
11505 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011506
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011507 return E;
John McCall755d8492011-04-12 00:42:48 +000011508 }
11509
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011510 ExprResult VisitMemberExpr(MemberExpr *E) {
11511 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011512 }
11513
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011514 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11515 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011516 }
11517 };
11518}
11519
11520/// Given a function expression of unknown-any type, try to rebuild it
11521/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011522static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11523 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11524 if (Result.isInvalid()) return ExprError();
11525 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011526}
11527
11528namespace {
John McCall379b5152011-04-11 07:02:50 +000011529 /// A visitor for rebuilding an expression of type __unknown_anytype
11530 /// into one which resolves the type directly on the referring
11531 /// expression. Strict preservation of the original source
11532 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011533 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011534 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011535
11536 Sema &S;
11537
11538 /// The current destination type.
11539 QualType DestType;
11540
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011541 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11542 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011543
John McCalla5fc4722011-04-09 22:50:59 +000011544 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011545 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011546 }
11547
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011548 ExprResult VisitExpr(Expr *E) {
11549 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11550 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011551 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011552 }
11553
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011554 ExprResult VisitCallExpr(CallExpr *E);
11555 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011556
John McCalla5fc4722011-04-09 22:50:59 +000011557 /// Rebuild an expression which simply semantically wraps another
11558 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011559 template <class T> ExprResult rebuildSugarExpr(T *E) {
11560 ExprResult SubResult = Visit(E->getSubExpr());
11561 if (SubResult.isInvalid()) return ExprError();
11562 Expr *SubExpr = SubResult.take();
11563 E->setSubExpr(SubExpr);
11564 E->setType(SubExpr->getType());
11565 E->setValueKind(SubExpr->getValueKind());
11566 assert(E->getObjectKind() == OK_Ordinary);
11567 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011568 }
John McCall1de4d4e2011-04-07 08:22:57 +000011569
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011570 ExprResult VisitParenExpr(ParenExpr *E) {
11571 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011572 }
11573
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011574 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11575 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011576 }
11577
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011578 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11579 const PointerType *Ptr = DestType->getAs<PointerType>();
11580 if (!Ptr) {
11581 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11582 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011583 return ExprError();
11584 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011585 assert(E->getValueKind() == VK_RValue);
11586 assert(E->getObjectKind() == OK_Ordinary);
11587 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011588
11589 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011590 DestType = Ptr->getPointeeType();
11591 ExprResult SubResult = Visit(E->getSubExpr());
11592 if (SubResult.isInvalid()) return ExprError();
11593 E->setSubExpr(SubResult.take());
11594 return E;
John McCall755d8492011-04-12 00:42:48 +000011595 }
11596
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011597 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011598
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011599 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011600
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011601 ExprResult VisitMemberExpr(MemberExpr *E) {
11602 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011603 }
John McCalla5fc4722011-04-09 22:50:59 +000011604
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011605 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11606 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011607 }
11608 };
11609}
11610
John McCall379b5152011-04-11 07:02:50 +000011611/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011612ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11613 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011614
11615 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011616 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011617 FK_FunctionPointer,
11618 FK_BlockPointer
11619 };
11620
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011621 FnKind Kind;
11622 QualType CalleeType = CalleeExpr->getType();
11623 if (CalleeType == S.Context.BoundMemberTy) {
11624 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11625 Kind = FK_MemberFunction;
11626 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11627 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11628 CalleeType = Ptr->getPointeeType();
11629 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011630 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011631 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11632 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011633 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011634 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011635
11636 // Verify that this is a legal result type of a function.
11637 if (DestType->isArrayType() || DestType->isFunctionType()) {
11638 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011639 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011640 diagID = diag::err_block_returning_array_function;
11641
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011642 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011643 << DestType->isFunctionType() << DestType;
11644 return ExprError();
11645 }
11646
11647 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011648 E->setType(DestType.getNonLValueExprType(S.Context));
11649 E->setValueKind(Expr::getValueKindForType(DestType));
11650 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011651
11652 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011653 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011654 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011655 Proto->arg_type_begin(),
11656 Proto->getNumArgs(),
11657 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011658 else
11659 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011660 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011661
11662 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011663 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011664 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011665 // Nothing to do.
11666 break;
11667
11668 case FK_FunctionPointer:
11669 DestType = S.Context.getPointerType(DestType);
11670 break;
11671
11672 case FK_BlockPointer:
11673 DestType = S.Context.getBlockPointerType(DestType);
11674 break;
11675 }
11676
11677 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011678 ExprResult CalleeResult = Visit(CalleeExpr);
11679 if (!CalleeResult.isUsable()) return ExprError();
11680 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011681
11682 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011683 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011684}
11685
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011686ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011687 // Verify that this is a legal result type of a call.
11688 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011689 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011690 << DestType->isFunctionType() << DestType;
11691 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011692 }
11693
John McCall48218c62011-07-13 17:56:40 +000011694 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011695 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11696 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11697 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011698 }
John McCall755d8492011-04-12 00:42:48 +000011699
John McCall379b5152011-04-11 07:02:50 +000011700 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011701 E->setType(DestType.getNonReferenceType());
11702 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011703
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011704 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011705}
11706
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011707ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011708 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011709 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011710 assert(E->getValueKind() == VK_RValue);
11711 assert(E->getObjectKind() == OK_Ordinary);
11712
11713 E->setType(DestType);
11714
11715 // Rebuild the sub-expression as the pointee (function) type.
11716 DestType = DestType->castAs<PointerType>()->getPointeeType();
11717
11718 ExprResult Result = Visit(E->getSubExpr());
11719 if (!Result.isUsable()) return ExprError();
11720
11721 E->setSubExpr(Result.take());
11722 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011723 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011724 assert(E->getValueKind() == VK_RValue);
11725 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011726
Sean Callanance9c8312012-03-06 21:34:12 +000011727 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011728
Sean Callanance9c8312012-03-06 21:34:12 +000011729 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011730
Sean Callanance9c8312012-03-06 21:34:12 +000011731 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11732 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011733
Sean Callanance9c8312012-03-06 21:34:12 +000011734 ExprResult Result = Visit(E->getSubExpr());
11735 if (!Result.isUsable()) return ExprError();
11736
11737 E->setSubExpr(Result.take());
11738 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011739 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011740 llvm_unreachable("Unhandled cast type!");
11741 }
John McCall379b5152011-04-11 07:02:50 +000011742}
11743
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011744ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11745 ExprValueKind ValueKind = VK_LValue;
11746 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011747
11748 // We know how to make this work for certain kinds of decls:
11749
11750 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011751 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11752 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11753 DestType = Ptr->getPointeeType();
11754 ExprResult Result = resolveDecl(E, VD);
11755 if (Result.isInvalid()) return ExprError();
11756 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011757 CK_FunctionToPointerDecay, VK_RValue);
11758 }
11759
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011760 if (!Type->isFunctionType()) {
11761 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11762 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011763 return ExprError();
11764 }
John McCall379b5152011-04-11 07:02:50 +000011765
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11767 if (MD->isInstance()) {
11768 ValueKind = VK_RValue;
11769 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011770 }
11771
John McCall379b5152011-04-11 07:02:50 +000011772 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011773 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011774 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011775
11776 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011777 } else if (isa<VarDecl>(VD)) {
11778 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11779 Type = RefTy->getPointeeType();
11780 } else if (Type->isFunctionType()) {
11781 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11782 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011783 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011784 }
11785
11786 // - nothing else
11787 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011788 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11789 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011790 return ExprError();
11791 }
11792
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011793 VD->setType(DestType);
11794 E->setType(Type);
11795 E->setValueKind(ValueKind);
11796 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011797}
11798
John McCall1de4d4e2011-04-07 08:22:57 +000011799/// Check a cast of an unknown-any type. We intentionally only
11800/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011801ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11802 Expr *CastExpr, CastKind &CastKind,
11803 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011804 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011805 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011806 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011807
Richard Trieuccd891a2011-09-09 01:45:06 +000011808 CastExpr = result.take();
11809 VK = CastExpr->getValueKind();
11810 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011811
Richard Trieuccd891a2011-09-09 01:45:06 +000011812 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011813}
11814
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011815ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11816 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11817}
11818
Richard Trieuccd891a2011-09-09 01:45:06 +000011819static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11820 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011821 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011822 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011823 E = E->IgnoreParenImpCasts();
11824 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11825 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011826 diagID = diag::err_uncasted_call_of_unknown_any;
11827 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011828 break;
John McCall379b5152011-04-11 07:02:50 +000011829 }
John McCall1de4d4e2011-04-07 08:22:57 +000011830 }
11831
John McCall379b5152011-04-11 07:02:50 +000011832 SourceLocation loc;
11833 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011834 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011835 loc = ref->getLocation();
11836 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011837 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011838 loc = mem->getMemberLoc();
11839 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011840 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011841 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011842 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011843 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011844 if (!d) {
11845 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11846 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11847 << orig->getSourceRange();
11848 return ExprError();
11849 }
John McCall379b5152011-04-11 07:02:50 +000011850 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011851 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11852 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011853 return ExprError();
11854 }
11855
11856 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011857
11858 // Never recoverable.
11859 return ExprError();
11860}
11861
John McCall2a984ca2010-10-12 00:20:44 +000011862/// Check for operands with placeholder types and complain if found.
11863/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011864ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011865 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11866 if (!placeholderType) return Owned(E);
11867
11868 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011869
John McCall1de4d4e2011-04-07 08:22:57 +000011870 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011871 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011872 // Try to resolve a single function template specialization.
11873 // This is obligatory.
11874 ExprResult result = Owned(E);
11875 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11876 return result;
11877
11878 // If that failed, try to recover with a call.
11879 } else {
11880 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11881 /*complain*/ true);
11882 return result;
11883 }
11884 }
John McCall1de4d4e2011-04-07 08:22:57 +000011885
John McCall864c0412011-04-26 20:42:42 +000011886 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011887 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011888 ExprResult result = Owned(E);
11889 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11890 /*complain*/ true);
11891 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011892 }
11893
11894 // ARC unbridged casts.
11895 case BuiltinType::ARCUnbridgedCast: {
11896 Expr *realCast = stripARCUnbridgedCast(E);
11897 diagnoseARCUnbridgedCast(realCast);
11898 return Owned(realCast);
11899 }
John McCall864c0412011-04-26 20:42:42 +000011900
John McCall1de4d4e2011-04-07 08:22:57 +000011901 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011902 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011903 return diagnoseUnknownAnyExpr(*this, E);
11904
John McCall3c3b7f92011-10-25 17:37:35 +000011905 // Pseudo-objects.
11906 case BuiltinType::PseudoObject:
11907 return checkPseudoObjectRValue(E);
11908
Eli Friedmana6c66ce2012-08-31 00:14:07 +000011909 case BuiltinType::BuiltinFn:
11910 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11911 return ExprError();
11912
John McCalle0a22d02011-10-18 21:02:43 +000011913 // Everything else should be impossible.
11914#define BUILTIN_TYPE(Id, SingletonId) \
11915 case BuiltinType::Id:
11916#define PLACEHOLDER_TYPE(Id, SingletonId)
11917#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011918 break;
11919 }
11920
11921 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011922}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011923
Richard Trieuccd891a2011-09-09 01:45:06 +000011924bool Sema::CheckCaseExpression(Expr *E) {
11925 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011926 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011927 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11928 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011929 return false;
11930}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011931
11932/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11933ExprResult
11934Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11935 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11936 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000011937 QualType BoolT = Context.ObjCBuiltinBoolTy;
11938 if (!Context.getBOOLDecl()) {
Fariborz Jahanian1c9a2da2012-10-16 17:08:11 +000011939 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011940 Sema::LookupOrdinaryName);
Fariborz Jahanian9f5933a2012-10-16 16:21:20 +000011941 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanian96171302012-08-30 18:49:41 +000011942 NamedDecl *ND = Result.getFoundDecl();
11943 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11944 Context.setBOOLDecl(TD);
11945 }
11946 }
11947 if (Context.getBOOLDecl())
11948 BoolT = Context.getBOOLType();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011949 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian96171302012-08-30 18:49:41 +000011950 BoolT, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011951}