blob: 49c84664fce0ba5fd906616d65a0a756de00fc29 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedmanef331b72012-01-20 01:26:23 +000044#include "TreeTransform.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000046using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Sebastian Redl14b0c192011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redl14b0c192011-09-24 17:48:00 +000066 return true;
67}
David Chisnall0f436562009-08-17 16:35:33 +000068
Ted Kremenekd6cf9122012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenekd6cf9122012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000096 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith6c4c36c2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith5bdaac52012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Jordan Rose0eb3f452012-06-18 22:09:19 +0000133/// \brief Determine whether a FunctionDecl was ever declared with an
134/// explicit storage class.
135static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137 E = D->redecls_end();
138 I != E; ++I) {
139 if (I->getStorageClassAsWritten() != SC_None)
140 return true;
141 }
142 return false;
143}
144
145/// \brief Check whether we're in an extern inline function and referring to a
146/// variable or function with internal linkage.
147///
148/// This also applies to anonymous-namespaced objects, which are effectively
149/// internal.
150/// This is only a warning because we used to silently accept this code, but
151/// most likely it will not do what the user intends.
152static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
153 const NamedDecl *D,
154 SourceLocation Loc) {
155 // C11 6.7.4p3: An inline definition of a function with external linkage...
156 // shall not contain a reference to an identifier with internal linkage.
157 // C++11 [basic.def.odr]p6: ...in each definition of D, corresponding names,
158 // looked up according to 3.4, shall refer to an entity defined within the
159 // definition of D, or shall refer to the same entity, after overload
160 // resolution (13.3) and after matching of partial template specialization
161 // (14.8.3), except that a name can refer to a const object with internal or
162 // no linkage if the object has the same literal type in all definitions of
163 // D, and the object is initialized with a constant expression (5.19), and
164 // the value (but not the address) of the object is used, and the object has
165 // the same value in all definitions of D; ...
166
167 // Check if this is an inlined function or method.
168 FunctionDecl *Current = S.getCurFunctionDecl();
169 if (!Current)
170 return;
171 if (!Current->isInlined())
172 return;
173 if (Current->getLinkage() != ExternalLinkage)
174 return;
175
176 // Check if the decl has internal linkage.
177 Linkage UsedLinkage = D->getLinkage();
178 switch (UsedLinkage) {
179 case NoLinkage:
180 return;
181 case InternalLinkage:
182 case UniqueExternalLinkage:
183 break;
184 case ExternalLinkage:
185 return;
186 }
187
188 // Check C++'s exception for const variables. This is in the standard
189 // because in C++ const variables have internal linkage unless
190 // explicitly declared extern.
191 // Note that we don't do any of the cross-TU checks, and this code isn't
192 // even particularly careful about checking if the variable "has the
193 // same value in all definitions" of the inline function. It just does a
194 // sanity check to make sure there is an initializer at all.
195 // FIXME: We should still be checking to see if we're using a constant
196 // as a glvalue anywhere, but we don't have the necessary information to
197 // do that here, and as long as this is a warning and not a hard error
198 // it's not appropriate to change the semantics of the program (i.e.
199 // by having BuildDeclRefExpr use VK_RValue for constants like these).
200 const VarDecl *VD = dyn_cast<VarDecl>(D);
201 if (VD && S.getLangOpts().CPlusPlus)
202 if (VD->getType().isConstant(S.getASTContext()) && VD->getAnyInitializer())
203 return;
204
205 // Don't warn unless -pedantic is on if the inline function is in the main
Jordan Rosec4429b92012-06-18 23:58:49 +0000206 // source file, and in C++ don't warn at all, since the one-definition rule is
207 // still satisfied. This function will most likely not be inlined into
208 // another translation unit, so it's effectively internal.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000209 bool IsInMainFile = S.getSourceManager().isFromMainFile(Loc);
Jordan Rosec4429b92012-06-18 23:58:49 +0000210 if (S.getLangOpts().CPlusPlus) {
211 if (IsInMainFile)
212 return;
213
214 S.Diag(Loc, diag::warn_internal_in_extern_inline_cxx)
215 << (bool)VD << D
216 << (UsedLinkage == UniqueExternalLinkage)
217 << isa<CXXMethodDecl>(Current);
218 } else {
219 S.Diag(Loc, IsInMainFile ? diag::ext_internal_in_extern_inline
220 : diag::warn_internal_in_extern_inline)
221 << (bool)VD << D;
222 }
Jordan Rose0eb3f452012-06-18 22:09:19 +0000223
224 // Suggest "static" on the inline function, if possible.
225 if (!isa<CXXMethodDecl>(Current) &&
226 !hasAnyExplicitStorageClass(Current)) {
227 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
228 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
229 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
230 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
231 }
232
233 S.Diag(D->getCanonicalDecl()->getLocation(),
234 diag::note_internal_decl_declared_here)
235 << D;
236}
237
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000238/// \brief Determine whether the use of this declaration is valid, and
239/// emit any corresponding diagnostics.
240///
241/// This routine diagnoses various problems with referencing
242/// declarations that can occur when using a declaration. For example,
243/// it might warn if a deprecated or unavailable declaration is being
244/// used, or produce an error (and return true) if a C++0x deleted
245/// function is being used.
246///
247/// \returns true if there was an error (this declaration cannot be
248/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000249///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000250bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000251 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000252 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000253 // If there were any diagnostics suppressed by template argument deduction,
254 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000255 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000256 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
257 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000258 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000259 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
260 Diag(Suppressed[I].first, Suppressed[I].second);
261
262 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000263 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000264 // entry from the table, because we want to avoid ever emitting these
265 // diagnostics again.
266 Suppressed.clear();
267 }
268 }
269
Richard Smith34b41d92011-02-20 03:19:35 +0000270 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000271 if (ParsingInitForAutoVars.count(D)) {
272 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
273 << D->getDeclName();
274 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000275 }
276
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000277 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000278 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000279 if (FD->isDeleted()) {
280 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000281 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000282 return true;
283 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000284 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000285 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000286
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000287 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000288 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000289 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Jordan Rose106af9e2012-06-15 18:19:48 +0000290
Jordan Rose0eb3f452012-06-18 22:09:19 +0000291 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000292
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000293 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000294}
295
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000296/// \brief Retrieve the message suffix that should be added to a
297/// diagnostic complaining about the given function being deleted or
298/// unavailable.
299std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
300 // FIXME: C++0x implicitly-deleted special member functions could be
301 // detected here so that we could improve diagnostics to say, e.g.,
302 // "base class 'A' had a deleted copy constructor".
303 if (FD->isDeleted())
304 return std::string();
305
306 std::string Message;
307 if (FD->getAvailability(&Message))
308 return ": " + Message;
309
310 return std::string();
311}
312
John McCall3323fad2011-09-09 07:56:05 +0000313/// DiagnoseSentinelCalls - This routine checks whether a call or
314/// message-send is to a declaration with the sentinel attribute, and
315/// if so, it checks that the requirements of the sentinel are
316/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000317void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000318 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000319 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000320 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000321 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000322
John McCall3323fad2011-09-09 07:56:05 +0000323 // The number of formal parameters of the declaration.
324 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000325
John McCall3323fad2011-09-09 07:56:05 +0000326 // The kind of declaration. This is also an index into a %select in
327 // the diagnostic.
328 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
329
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000330 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000331 numFormalParams = MD->param_size();
332 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000333 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000334 numFormalParams = FD->param_size();
335 calleeType = CT_Function;
336 } else if (isa<VarDecl>(D)) {
337 QualType type = cast<ValueDecl>(D)->getType();
338 const FunctionType *fn = 0;
339 if (const PointerType *ptr = type->getAs<PointerType>()) {
340 fn = ptr->getPointeeType()->getAs<FunctionType>();
341 if (!fn) return;
342 calleeType = CT_Function;
343 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
344 fn = ptr->getPointeeType()->castAs<FunctionType>();
345 calleeType = CT_Block;
346 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000347 return;
John McCall3323fad2011-09-09 07:56:05 +0000348 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000349
John McCall3323fad2011-09-09 07:56:05 +0000350 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
351 numFormalParams = proto->getNumArgs();
352 } else {
353 numFormalParams = 0;
354 }
355 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000356 return;
357 }
John McCall3323fad2011-09-09 07:56:05 +0000358
359 // "nullPos" is the number of formal parameters at the end which
360 // effectively count as part of the variadic arguments. This is
361 // useful if you would prefer to not have *any* formal parameters,
362 // but the language forces you to have at least one.
363 unsigned nullPos = attr->getNullPos();
364 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
365 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
366
367 // The number of arguments which should follow the sentinel.
368 unsigned numArgsAfterSentinel = attr->getSentinel();
369
370 // If there aren't enough arguments for all the formal parameters,
371 // the sentinel, and the args after the sentinel, complain.
372 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000373 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000374 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000375 return;
376 }
John McCall3323fad2011-09-09 07:56:05 +0000377
378 // Otherwise, find the sentinel expression.
379 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000380 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000381 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000382 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000383
John McCall3323fad2011-09-09 07:56:05 +0000384 // Pick a reasonable string to insert. Optimistically use 'nil' or
385 // 'NULL' if those are actually defined in the context. Only use
386 // 'nil' for ObjC methods, where it's much more likely that the
387 // variadic arguments form a list of object pointers.
388 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000389 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
390 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000391 if (calleeType == CT_Method &&
392 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000393 NullValue = "nil";
394 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
395 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000396 else
John McCall3323fad2011-09-09 07:56:05 +0000397 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000398
399 if (MissingNilLoc.isInvalid())
400 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
401 else
402 Diag(MissingNilLoc, diag::warn_missing_sentinel)
403 << calleeType
404 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000405 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000406}
407
Richard Trieuccd891a2011-09-09 01:45:06 +0000408SourceRange Sema::getExprRange(Expr *E) const {
409 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000410}
411
Chris Lattnere7a2e912008-07-25 21:10:04 +0000412//===----------------------------------------------------------------------===//
413// Standard Promotions and Conversions
414//===----------------------------------------------------------------------===//
415
Chris Lattnere7a2e912008-07-25 21:10:04 +0000416/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000417ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000418 // Handle any placeholder expressions which made it here.
419 if (E->getType()->isPlaceholderType()) {
420 ExprResult result = CheckPlaceholderExpr(E);
421 if (result.isInvalid()) return ExprError();
422 E = result.take();
423 }
424
Chris Lattnere7a2e912008-07-25 21:10:04 +0000425 QualType Ty = E->getType();
426 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
427
Chris Lattnere7a2e912008-07-25 21:10:04 +0000428 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000429 E = ImpCastExprToType(E, Context.getPointerType(Ty),
430 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000431 else if (Ty->isArrayType()) {
432 // In C90 mode, arrays only promote to pointers if the array expression is
433 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
434 // type 'array of type' is converted to an expression that has type 'pointer
435 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
436 // that has type 'array of type' ...". The relevant change is "an lvalue"
437 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000438 //
439 // C++ 4.2p1:
440 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
441 // T" can be converted to an rvalue of type "pointer to T".
442 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000443 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000444 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
445 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000446 }
John Wiegley429bb272011-04-08 18:41:53 +0000447 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000448}
449
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000450static void CheckForNullPointerDereference(Sema &S, Expr *E) {
451 // Check to see if we are dereferencing a null pointer. If so,
452 // and if not volatile-qualified, this is undefined behavior that the
453 // optimizer will delete, so warn about it. People sometimes try to use this
454 // to get a deterministic trap and are surprised by clang's behavior. This
455 // only handles the pattern "*null", which is a very syntactic check.
456 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
457 if (UO->getOpcode() == UO_Deref &&
458 UO->getSubExpr()->IgnoreParenCasts()->
459 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
460 !UO->getType().isVolatileQualified()) {
461 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
462 S.PDiag(diag::warn_indirection_through_null)
463 << UO->getSubExpr()->getSourceRange());
464 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
465 S.PDiag(diag::note_indirection_through_null));
466 }
467}
468
John Wiegley429bb272011-04-08 18:41:53 +0000469ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000470 // Handle any placeholder expressions which made it here.
471 if (E->getType()->isPlaceholderType()) {
472 ExprResult result = CheckPlaceholderExpr(E);
473 if (result.isInvalid()) return ExprError();
474 E = result.take();
475 }
476
John McCall0ae287a2010-12-01 04:43:34 +0000477 // C++ [conv.lval]p1:
478 // A glvalue of a non-function, non-array type T can be
479 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000480 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000481
John McCall409fa9a2010-12-06 20:48:59 +0000482 QualType T = E->getType();
483 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000484
John McCall409fa9a2010-12-06 20:48:59 +0000485 // We don't want to throw lvalue-to-rvalue casts on top of
486 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000487 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000488 (E->getType() == Context.OverloadTy ||
489 T->isDependentType() ||
490 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000491 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000492
493 // The C standard is actually really unclear on this point, and
494 // DR106 tells us what the result should be but not why. It's
495 // generally best to say that void types just doesn't undergo
496 // lvalue-to-rvalue at all. Note that expressions of unqualified
497 // 'void' type are never l-values, but qualified void can be.
498 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000499 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000500
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000501 CheckForNullPointerDereference(*this, E);
502
John McCall409fa9a2010-12-06 20:48:59 +0000503 // C++ [conv.lval]p1:
504 // [...] If T is a non-class type, the type of the prvalue is the
505 // cv-unqualified version of T. Otherwise, the type of the
506 // rvalue is T.
507 //
508 // C99 6.3.2.1p2:
509 // If the lvalue has qualified type, the value has the unqualified
510 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000511 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000512 if (T.hasQualifiers())
513 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000514
Eli Friedmand2cce132012-02-02 23:15:15 +0000515 UpdateMarkingForLValueToRValue(E);
516
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000517 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
518 E, 0, VK_RValue));
519
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000520 // C11 6.3.2.1p2:
521 // ... if the lvalue has atomic type, the value has the non-atomic version
522 // of the type of the lvalue ...
523 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
524 T = Atomic->getValueType().getUnqualifiedType();
525 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
526 Res.get(), 0, VK_RValue));
527 }
528
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000529 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000530}
531
John Wiegley429bb272011-04-08 18:41:53 +0000532ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
533 ExprResult Res = DefaultFunctionArrayConversion(E);
534 if (Res.isInvalid())
535 return ExprError();
536 Res = DefaultLvalueConversion(Res.take());
537 if (Res.isInvalid())
538 return ExprError();
539 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000540}
541
542
Chris Lattnere7a2e912008-07-25 21:10:04 +0000543/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000544/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000545/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000546/// apply if the array is an argument to the sizeof or address (&) operators.
547/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000548ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000549 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000550 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
551 if (Res.isInvalid())
552 return Owned(E);
553 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000554
John McCall0ae287a2010-12-01 04:43:34 +0000555 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000556 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000557
558 // Half FP is a bit different: it's a storage-only type, meaning that any
559 // "use" of it should be promoted to float.
560 if (Ty->isHalfType())
561 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
562
John McCall0ae287a2010-12-01 04:43:34 +0000563 // Try to perform integral promotions if the object has a theoretically
564 // promotable type.
565 if (Ty->isIntegralOrUnscopedEnumerationType()) {
566 // C99 6.3.1.1p2:
567 //
568 // The following may be used in an expression wherever an int or
569 // unsigned int may be used:
570 // - an object or expression with an integer type whose integer
571 // conversion rank is less than or equal to the rank of int
572 // and unsigned int.
573 // - A bit-field of type _Bool, int, signed int, or unsigned int.
574 //
575 // If an int can represent all values of the original type, the
576 // value is converted to an int; otherwise, it is converted to an
577 // unsigned int. These are called the integer promotions. All
578 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000579
John McCall0ae287a2010-12-01 04:43:34 +0000580 QualType PTy = Context.isPromotableBitField(E);
581 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000582 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
583 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000584 }
585 if (Ty->isPromotableIntegerType()) {
586 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000587 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
588 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000589 }
Eli Friedman04e83572009-08-20 04:21:42 +0000590 }
John Wiegley429bb272011-04-08 18:41:53 +0000591 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000592}
593
Chris Lattner05faf172008-07-25 22:25:12 +0000594/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000595/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000596/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000597ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
598 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000599 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000600
John Wiegley429bb272011-04-08 18:41:53 +0000601 ExprResult Res = UsualUnaryConversions(E);
602 if (Res.isInvalid())
603 return Owned(E);
604 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000605
Chris Lattner05faf172008-07-25 22:25:12 +0000606 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000607 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000608 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
609
John McCall96a914a2011-08-27 22:06:17 +0000610 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000611 // promotion, even on class types, but note:
612 // C++11 [conv.lval]p2:
613 // When an lvalue-to-rvalue conversion occurs in an unevaluated
614 // operand or a subexpression thereof the value contained in the
615 // referenced object is not accessed. Otherwise, if the glvalue
616 // has a class type, the conversion copy-initializes a temporary
617 // of type T from the glvalue and the result of the conversion
618 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000619 // FIXME: add some way to gate this entire thing for correctness in
620 // potentially potentially evaluated contexts.
David Blaikie4e4d0842012-03-11 07:00:24 +0000621 if (getLangOpts().CPlusPlus && E->isGLValue() &&
Eli Friedman55693fb2012-01-17 02:13:45 +0000622 ExprEvalContexts.back().Context != Unevaluated) {
623 ExprResult Temp = PerformCopyInitialization(
624 InitializedEntity::InitializeTemporary(E->getType()),
625 E->getExprLoc(),
626 Owned(E));
627 if (Temp.isInvalid())
628 return ExprError();
629 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000630 }
631
John Wiegley429bb272011-04-08 18:41:53 +0000632 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000633}
634
Chris Lattner312531a2009-04-12 08:11:20 +0000635/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
636/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000637/// interfaces passed by value.
638ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000639 FunctionDecl *FDecl) {
John McCall5acb0c92011-10-17 18:40:02 +0000640 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
641 // Strip the unbridged-cast placeholder expression off, if applicable.
642 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
643 (CT == VariadicMethod ||
644 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
645 E = stripARCUnbridgedCast(E);
646
647 // Otherwise, do normal placeholder checking.
648 } else {
649 ExprResult ExprRes = CheckPlaceholderExpr(E);
650 if (ExprRes.isInvalid())
651 return ExprError();
652 E = ExprRes.take();
653 }
654 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000655
John McCall5acb0c92011-10-17 18:40:02 +0000656 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000657 if (ExprRes.isInvalid())
658 return ExprError();
659 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000661 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000662 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000663 DiagRuntimeBehavior(E->getLocStart(), 0,
664 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
665 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000666 return ExprError();
John McCall5f8d6042011-08-27 01:09:30 +0000667
Douglas Gregorb8e778d2011-10-14 20:34:19 +0000668 // Complain about passing non-POD types through varargs. However, don't
669 // perform this check for incomplete types, which we can get here when we're
670 // in an unevaluated context.
Benjamin Kramer152f6b72012-04-28 10:00:42 +0000671 if (!E->getType()->isIncompleteType() &&
672 !E->getType().isCXX98PODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000673 // C++0x [expr.call]p7:
674 // Passing a potentially-evaluated argument of class type (Clause 9)
675 // having a non-trivial copy constructor, a non-trivial move constructor,
676 // or a non-trivial destructor, with no corresponding parameter,
677 // is conditionally-supported with implementation-defined semantics.
678 bool TrivialEnough = false;
David Blaikie4e4d0842012-03-11 07:00:24 +0000679 if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType()) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000680 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
681 if (Record->hasTrivialCopyConstructor() &&
682 Record->hasTrivialMoveConstructor() &&
Richard Smithebaf0e62011-10-18 20:49:44 +0000683 Record->hasTrivialDestructor()) {
684 DiagRuntimeBehavior(E->getLocStart(), 0,
685 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
686 << E->getType() << CT);
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000687 TrivialEnough = true;
Richard Smithebaf0e62011-10-18 20:49:44 +0000688 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000689 }
690 }
John McCallf85e1932011-06-15 23:02:42 +0000691
692 if (!TrivialEnough &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000693 getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000694 E->getType()->isObjCLifetimeType())
695 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000696
697 if (TrivialEnough) {
698 // Nothing to diagnose. This is okay.
699 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000700 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
David Blaikie4e4d0842012-03-11 07:00:24 +0000701 << getLangOpts().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000702 << CT)) {
703 // Turn this into a trap.
704 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000705 SourceLocation TemplateKWLoc;
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000706 UnqualifiedId Name;
707 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
708 E->getLocStart());
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000709 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
710 true, false);
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000711 if (TrapFn.isInvalid())
712 return ExprError();
713
714 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
715 MultiExprArg(), E->getLocEnd());
716 if (Call.isInvalid())
717 return ExprError();
718
719 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
720 Call.get(), E);
721 if (Comma.isInvalid())
John McCall66c20302011-08-26 18:41:18 +0000722 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000723 E = Comma.get();
724 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000725 }
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000726 // c++ rules are enforced elsewhere.
David Blaikie4e4d0842012-03-11 07:00:24 +0000727 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000728 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000729 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000730 return ExprError();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000731
John Wiegley429bb272011-04-08 18:41:53 +0000732 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000733}
734
Richard Trieu8289f492011-09-02 20:58:51 +0000735/// \brief Converts an integer to complex float type. Helper function of
736/// UsualArithmeticConversions()
737///
738/// \return false if the integer expression is an integer type and is
739/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000740static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
741 ExprResult &ComplexExpr,
742 QualType IntTy,
743 QualType ComplexTy,
744 bool SkipCast) {
745 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
746 if (SkipCast) return false;
747 if (IntTy->isIntegerType()) {
748 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
749 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
750 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000751 CK_FloatingRealToComplex);
752 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000753 assert(IntTy->isComplexIntegerType());
754 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000755 CK_IntegralComplexToFloatingComplex);
756 }
757 return false;
758}
759
760/// \brief Takes two complex float types and converts them to the same type.
761/// Helper function of UsualArithmeticConversions()
762static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000763handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
764 ExprResult &RHS, QualType LHSType,
765 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000766 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000767 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000768
769 if (order < 0) {
770 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000771 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000772 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
773 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000774 }
775 if (order > 0)
776 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000777 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
778 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000779}
780
781/// \brief Converts otherExpr to complex float and promotes complexExpr if
782/// necessary. Helper function of UsualArithmeticConversions()
783static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000784 ExprResult &ComplexExpr,
785 ExprResult &OtherExpr,
786 QualType ComplexTy,
787 QualType OtherTy,
788 bool ConvertComplexExpr,
789 bool ConvertOtherExpr) {
790 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000791
792 // If just the complexExpr is complex, the otherExpr needs to be converted,
793 // and the complexExpr might need to be promoted.
794 if (order > 0) { // complexExpr is wider
795 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000796 if (ConvertOtherExpr) {
797 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
798 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
799 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000800 CK_FloatingRealToComplex);
801 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000802 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000803 }
804
805 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000806 QualType result = (order == 0 ? ComplexTy :
807 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000808
809 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 if (ConvertOtherExpr)
811 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000812 CK_FloatingRealToComplex);
813
814 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000815 if (ConvertComplexExpr && order < 0)
816 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000817 CK_FloatingComplexCast);
818
819 return result;
820}
821
822/// \brief Handle arithmetic conversion with complex types. Helper function of
823/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000824static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
825 ExprResult &RHS, QualType LHSType,
826 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000827 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000828 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000829 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000830 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000831 return LHSType;
832 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000833 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000834 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000835
836 // This handles complex/complex, complex/float, or float/complex.
837 // When both operands are complex, the shorter operand is converted to the
838 // type of the longer, and that is the type of the result. This corresponds
839 // to what is done when combining two real floating-point operands.
840 // The fun begins when size promotion occur across type domains.
841 // From H&S 6.3.4: When one operand is complex and the other is a real
842 // floating-point type, the less precise type is converted, within it's
843 // real or complex domain, to the precision of the other type. For example,
844 // when combining a "long double" with a "double _Complex", the
845 // "double _Complex" is promoted to "long double _Complex".
846
Richard Trieucafd30b2011-09-06 18:25:09 +0000847 bool LHSComplexFloat = LHSType->isComplexType();
848 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000849
850 // If both are complex, just cast to the more precise type.
851 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000852 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
853 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000854 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000855
856 // If only one operand is complex, promote it if necessary and convert the
857 // other operand to complex.
858 if (LHSComplexFloat)
859 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000860 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000861 /*convertOtherExpr*/ true);
862
863 assert(RHSComplexFloat);
864 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000865 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000866 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000867}
868
869/// \brief Hande arithmetic conversion from integer to float. Helper function
870/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000871static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
872 ExprResult &IntExpr,
873 QualType FloatTy, QualType IntTy,
874 bool ConvertFloat, bool ConvertInt) {
875 if (IntTy->isIntegerType()) {
876 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000877 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000878 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000879 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000880 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000881 }
882
883 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000884 assert(IntTy->isComplexIntegerType());
885 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000886
887 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000888 if (ConvertInt)
889 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000890 CK_IntegralComplexToFloatingComplex);
891
892 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000893 if (ConvertFloat)
894 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000895 CK_FloatingRealToComplex);
896
897 return result;
898}
899
900/// \brief Handle arithmethic conversion with floating point types. Helper
901/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000902static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
903 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000904 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000905 bool LHSFloat = LHSType->isRealFloatingType();
906 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000907
908 // If we have two real floating types, convert the smaller operand
909 // to the bigger result.
910 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000911 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000912 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000913 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
914 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000915 }
916
917 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000918 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000919 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
920 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000921 }
922
923 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000924 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000925 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000926 /*convertInt=*/ true);
927 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000928 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000929 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000930 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000931}
932
933/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000934/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000935// FIXME: if the operands are (int, _Complex long), we currently
936// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000937static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
938 ExprResult &RHS, QualType LHSType,
939 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000940 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000941 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
942 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000943
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000944 if (LHSComplexInt && RHSComplexInt) {
945 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
946 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000947 assert(order && "inequal types with equal element ordering");
948 if (order > 0) {
949 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000950 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
951 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000952 }
953
Richard Trieuccd891a2011-09-09 01:45:06 +0000954 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000955 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
956 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000957 }
958
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000959 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000960 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000961 // FIXME: This needs to take integer ranks into account
962 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
963 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000964 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
965 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000966 }
967
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000968 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000969 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000970 // FIXME: This needs to take integer ranks into account
971 if (!IsCompAssign) {
972 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
973 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000974 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000975 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000976 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000977}
978
979/// \brief Handle integer arithmetic conversions. Helper function of
980/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000981static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
982 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000983 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000984 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000985 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
986 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
987 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
988 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000989 // Same signedness; use the higher-ranked type
990 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000991 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
992 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000993 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000994 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
995 return RHSType;
996 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000997 // The unsigned type has greater than or equal rank to the
998 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000999 if (RHSSigned) {
1000 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1001 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001002 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001003 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1004 return RHSType;
1005 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001006 // The two types are different widths; if we are here, that
1007 // means the signed type is larger than the unsigned type, so
1008 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001009 if (LHSSigned) {
1010 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1011 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001012 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001013 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1014 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001015 } else {
1016 // The signed type is higher-ranked than the unsigned type,
1017 // but isn't actually any bigger (like unsigned int and long
1018 // on most 32-bit systems). Use the unsigned type corresponding
1019 // to the signed type.
1020 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001021 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1022 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001023 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001024 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001025 return result;
1026 }
1027}
1028
Chris Lattnere7a2e912008-07-25 21:10:04 +00001029/// UsualArithmeticConversions - Performs various conversions that are common to
1030/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001031/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001032/// responsible for emitting appropriate error diagnostics.
1033/// FIXME: verify the conversion rules for "complex int" are consistent with
1034/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001035QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001036 bool IsCompAssign) {
1037 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001038 LHS = UsualUnaryConversions(LHS.take());
1039 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001040 return QualType();
1041 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001042
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001043 RHS = UsualUnaryConversions(RHS.take());
1044 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001045 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001046
Mike Stump1eb44332009-09-09 15:08:12 +00001047 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001048 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001049 QualType LHSType =
1050 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1051 QualType RHSType =
1052 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001053
Eli Friedman860a3192012-06-16 02:19:17 +00001054 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1055 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1056 LHSType = AtomicLHS->getValueType();
1057
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001058 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001059 if (LHSType == RHSType)
1060 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001061
1062 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1063 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001064 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001065 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001066
John McCallcf33b242010-11-13 08:17:45 +00001067 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001068 QualType LHSUnpromotedType = LHSType;
1069 if (LHSType->isPromotableIntegerType())
1070 LHSType = Context.getPromotedIntegerType(LHSType);
1071 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001072 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001073 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001074 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001075 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001076
John McCallcf33b242010-11-13 08:17:45 +00001077 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001078 if (LHSType == RHSType)
1079 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001080
1081 // At this point, we have two different arithmetic types.
1082
1083 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001084 if (LHSType->isComplexType() || RHSType->isComplexType())
1085 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001086 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001087
1088 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001089 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1090 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001091 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001092
1093 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001094 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001095 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001096 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001097
1098 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001099 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001100 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001101}
1102
Chris Lattnere7a2e912008-07-25 21:10:04 +00001103//===----------------------------------------------------------------------===//
1104// Semantic Analysis for various Expression Types
1105//===----------------------------------------------------------------------===//
1106
1107
Peter Collingbournef111d932011-04-15 00:35:48 +00001108ExprResult
1109Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1110 SourceLocation DefaultLoc,
1111 SourceLocation RParenLoc,
1112 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001113 MultiTypeArg ArgTypes,
1114 MultiExprArg ArgExprs) {
1115 unsigned NumAssocs = ArgTypes.size();
1116 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001117
Richard Trieuccd891a2011-09-09 01:45:06 +00001118 ParsedType *ParsedTypes = ArgTypes.release();
1119 Expr **Exprs = ArgExprs.release();
Peter Collingbournef111d932011-04-15 00:35:48 +00001120
1121 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1122 for (unsigned i = 0; i < NumAssocs; ++i) {
1123 if (ParsedTypes[i])
1124 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1125 else
1126 Types[i] = 0;
1127 }
1128
1129 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1130 ControllingExpr, Types, Exprs,
1131 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001132 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001133 return ER;
1134}
1135
1136ExprResult
1137Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1138 SourceLocation DefaultLoc,
1139 SourceLocation RParenLoc,
1140 Expr *ControllingExpr,
1141 TypeSourceInfo **Types,
1142 Expr **Exprs,
1143 unsigned NumAssocs) {
1144 bool TypeErrorFound = false,
1145 IsResultDependent = ControllingExpr->isTypeDependent(),
1146 ContainsUnexpandedParameterPack
1147 = ControllingExpr->containsUnexpandedParameterPack();
1148
1149 for (unsigned i = 0; i < NumAssocs; ++i) {
1150 if (Exprs[i]->containsUnexpandedParameterPack())
1151 ContainsUnexpandedParameterPack = true;
1152
1153 if (Types[i]) {
1154 if (Types[i]->getType()->containsUnexpandedParameterPack())
1155 ContainsUnexpandedParameterPack = true;
1156
1157 if (Types[i]->getType()->isDependentType()) {
1158 IsResultDependent = true;
1159 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001160 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001161 // complete object type other than a variably modified type."
1162 unsigned D = 0;
1163 if (Types[i]->getType()->isIncompleteType())
1164 D = diag::err_assoc_type_incomplete;
1165 else if (!Types[i]->getType()->isObjectType())
1166 D = diag::err_assoc_type_nonobject;
1167 else if (Types[i]->getType()->isVariablyModifiedType())
1168 D = diag::err_assoc_type_variably_modified;
1169
1170 if (D != 0) {
1171 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1172 << Types[i]->getTypeLoc().getSourceRange()
1173 << Types[i]->getType();
1174 TypeErrorFound = true;
1175 }
1176
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001177 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001178 // selection shall specify compatible types."
1179 for (unsigned j = i+1; j < NumAssocs; ++j)
1180 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1181 Context.typesAreCompatible(Types[i]->getType(),
1182 Types[j]->getType())) {
1183 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1184 diag::err_assoc_compatible_types)
1185 << Types[j]->getTypeLoc().getSourceRange()
1186 << Types[j]->getType()
1187 << Types[i]->getType();
1188 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1189 diag::note_compat_assoc)
1190 << Types[i]->getTypeLoc().getSourceRange()
1191 << Types[i]->getType();
1192 TypeErrorFound = true;
1193 }
1194 }
1195 }
1196 }
1197 if (TypeErrorFound)
1198 return ExprError();
1199
1200 // If we determined that the generic selection is result-dependent, don't
1201 // try to compute the result expression.
1202 if (IsResultDependent)
1203 return Owned(new (Context) GenericSelectionExpr(
1204 Context, KeyLoc, ControllingExpr,
1205 Types, Exprs, NumAssocs, DefaultLoc,
1206 RParenLoc, ContainsUnexpandedParameterPack));
1207
Chris Lattner5f9e2722011-07-23 10:55:15 +00001208 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001209 unsigned DefaultIndex = -1U;
1210 for (unsigned i = 0; i < NumAssocs; ++i) {
1211 if (!Types[i])
1212 DefaultIndex = i;
1213 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1214 Types[i]->getType()))
1215 CompatIndices.push_back(i);
1216 }
1217
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001218 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001219 // type compatible with at most one of the types named in its generic
1220 // association list."
1221 if (CompatIndices.size() > 1) {
1222 // We strip parens here because the controlling expression is typically
1223 // parenthesized in macro definitions.
1224 ControllingExpr = ControllingExpr->IgnoreParens();
1225 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1226 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1227 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001228 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001229 E = CompatIndices.end(); I != E; ++I) {
1230 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1231 diag::note_compat_assoc)
1232 << Types[*I]->getTypeLoc().getSourceRange()
1233 << Types[*I]->getType();
1234 }
1235 return ExprError();
1236 }
1237
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001238 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001239 // its controlling expression shall have type compatible with exactly one of
1240 // the types named in its generic association list."
1241 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1242 // We strip parens here because the controlling expression is typically
1243 // parenthesized in macro definitions.
1244 ControllingExpr = ControllingExpr->IgnoreParens();
1245 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1246 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1247 return ExprError();
1248 }
1249
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001250 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001251 // type name that is compatible with the type of the controlling expression,
1252 // then the result expression of the generic selection is the expression
1253 // in that generic association. Otherwise, the result expression of the
1254 // generic selection is the expression in the default generic association."
1255 unsigned ResultIndex =
1256 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1257
1258 return Owned(new (Context) GenericSelectionExpr(
1259 Context, KeyLoc, ControllingExpr,
1260 Types, Exprs, NumAssocs, DefaultLoc,
1261 RParenLoc, ContainsUnexpandedParameterPack,
1262 ResultIndex));
1263}
1264
Richard Smithdd66be72012-03-08 01:34:56 +00001265/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1266/// location of the token and the offset of the ud-suffix within it.
1267static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1268 unsigned Offset) {
1269 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001270 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001271}
1272
Richard Smith36f5cfe2012-03-09 08:00:36 +00001273/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1274/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1275static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1276 IdentifierInfo *UDSuffix,
1277 SourceLocation UDSuffixLoc,
1278 ArrayRef<Expr*> Args,
1279 SourceLocation LitEndLoc) {
1280 assert(Args.size() <= 2 && "too many arguments for literal operator");
1281
1282 QualType ArgTy[2];
1283 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1284 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1285 if (ArgTy[ArgIdx]->isArrayType())
1286 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1287 }
1288
1289 DeclarationName OpName =
1290 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1291 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1292 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1293
1294 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1295 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1296 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1297 return ExprError();
1298
1299 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1300}
1301
Steve Narofff69936d2007-09-16 03:34:24 +00001302/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001303/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1304/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1305/// multiple tokens. However, the common case is that StringToks points to one
1306/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001307///
John McCall60d7b3a2010-08-24 06:29:42 +00001308ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001309Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1310 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 assert(NumStringToks && "Must have at least one string!");
1312
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001313 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001315 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001316
Chris Lattner5f9e2722011-07-23 10:55:15 +00001317 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 for (unsigned i = 0; i != NumStringToks; ++i)
1319 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001320
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001321 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001322 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001323 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001324 else if (Literal.isUTF16())
1325 StrTy = Context.Char16Ty;
1326 else if (Literal.isUTF32())
1327 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001328 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001329 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001330
Douglas Gregor5cee1192011-07-27 05:40:30 +00001331 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1332 if (Literal.isWide())
1333 Kind = StringLiteral::Wide;
1334 else if (Literal.isUTF8())
1335 Kind = StringLiteral::UTF8;
1336 else if (Literal.isUTF16())
1337 Kind = StringLiteral::UTF16;
1338 else if (Literal.isUTF32())
1339 Kind = StringLiteral::UTF32;
1340
Douglas Gregor77a52232008-09-12 00:47:35 +00001341 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001342 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001343 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001344
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001345 // Get an array type for the string, according to C99 6.4.5. This includes
1346 // the nul terminator character as well as the string length for pascal
1347 // strings.
1348 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001349 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001350 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001353 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1354 Kind, Literal.Pascal, StrTy,
1355 &StringTokLocs[0],
1356 StringTokLocs.size());
1357 if (Literal.getUDSuffix().empty())
1358 return Owned(Lit);
1359
1360 // We're building a user-defined literal.
1361 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001362 SourceLocation UDSuffixLoc =
1363 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1364 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001365
Richard Smith36f5cfe2012-03-09 08:00:36 +00001366 // Make sure we're allowed user-defined literals here.
1367 if (!UDLScope)
1368 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1369
Richard Smith9fcce652012-03-07 08:35:16 +00001370 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1371 // operator "" X (str, len)
1372 QualType SizeType = Context.getSizeType();
1373 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1374 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1375 StringTokLocs[0]);
1376 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001377 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1378 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001379}
1380
John McCall60d7b3a2010-08-24 06:29:42 +00001381ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001382Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001383 SourceLocation Loc,
1384 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001385 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001386 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001387}
1388
John McCall76a40212011-02-09 01:13:10 +00001389/// BuildDeclRefExpr - Build an expression that references a
1390/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001391ExprResult
John McCall76a40212011-02-09 01:13:10 +00001392Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001393 const DeclarationNameInfo &NameInfo,
1394 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001395 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001396 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1397 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1398 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1399 CalleeTarget = IdentifyCUDATarget(Callee);
1400 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1401 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1402 << CalleeTarget << D->getIdentifier() << CallerTarget;
1403 Diag(D->getLocation(), diag::note_previous_decl)
1404 << D->getIdentifier();
1405 return ExprError();
1406 }
1407 }
1408
John McCallf4b88a42012-03-10 09:33:50 +00001409 bool refersToEnclosingScope =
1410 (CurContext != D->getDeclContext() &&
1411 D->getDeclContext()->isFunctionOrMethod());
1412
Eli Friedman5f2987c2012-02-02 03:46:19 +00001413 DeclRefExpr *E = DeclRefExpr::Create(Context,
1414 SS ? SS->getWithLocInContext(Context)
1415 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001416 SourceLocation(),
1417 D, refersToEnclosingScope,
1418 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Eli Friedman5f2987c2012-02-02 03:46:19 +00001420 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001421
1422 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001423 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1424 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001425 E->setObjectKind(OK_BitField);
1426
1427 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001428}
1429
Abramo Bagnara25777432010-08-11 22:01:17 +00001430/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001431/// possibly a list of template arguments.
1432///
1433/// If this produces template arguments, it is permitted to call
1434/// DecomposeTemplateName.
1435///
1436/// This actually loses a lot of source location information for
1437/// non-standard name kinds; we should consider preserving that in
1438/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001439void
1440Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1441 TemplateArgumentListInfo &Buffer,
1442 DeclarationNameInfo &NameInfo,
1443 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001444 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1445 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1446 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1447
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001448 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001449 Id.TemplateId->getTemplateArgs(),
1450 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001451 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001452 TemplateArgsPtr.release();
1453
John McCall2b5289b2010-08-23 07:28:44 +00001454 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001455 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001456 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001457 TemplateArgs = &Buffer;
1458 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001459 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001460 TemplateArgs = 0;
1461 }
1462}
1463
John McCall578b69b2009-12-16 08:11:27 +00001464/// Diagnose an empty lookup.
1465///
1466/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001467bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001468 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001469 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001470 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001471 DeclarationName Name = R.getLookupName();
1472
John McCall578b69b2009-12-16 08:11:27 +00001473 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001474 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001475 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1476 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001477 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001478 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001479 diagnostic_suggest = diag::err_undeclared_use_suggest;
1480 }
John McCall578b69b2009-12-16 08:11:27 +00001481
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001482 // If the original lookup was an unqualified lookup, fake an
1483 // unqualified lookup. This is useful when (for example) the
1484 // original lookup would not have found something because it was a
1485 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001486 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1487 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001488 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001489 if (isa<CXXRecordDecl>(DC)) {
1490 LookupQualifiedName(R, DC);
1491
1492 if (!R.empty()) {
1493 // Don't give errors about ambiguities in this lookup.
1494 R.suppressDiagnostics();
1495
Francois Pichete6226ae2011-11-17 03:44:24 +00001496 // During a default argument instantiation the CurContext points
1497 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1498 // function parameter list, hence add an explicit check.
1499 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1500 ActiveTemplateInstantiations.back().Kind ==
1501 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001502 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1503 bool isInstance = CurMethod &&
1504 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001505 DC == CurMethod->getParent() && !isDefaultArgument;
1506
John McCall578b69b2009-12-16 08:11:27 +00001507
1508 // Give a code modification hint to insert 'this->'.
1509 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1510 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001511 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001512 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1513 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001514 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001515 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001516 if (DepMethod) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001517 if (getLangOpts().MicrosoftMode)
Francois Pichet0f74d1e2011-09-07 00:14:57 +00001518 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001519 Diag(R.getNameLoc(), diagnostic) << Name
1520 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1521 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman72899c32012-01-07 04:59:52 +00001522 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001523 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1524 R.getNameLoc(), DepThisType, false);
1525 TemplateArgumentListInfo TList;
1526 if (ULE->hasExplicitTemplateArgs())
1527 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001528
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001529 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001530 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001531 CXXDependentScopeMemberExpr *DepExpr =
1532 CXXDependentScopeMemberExpr::Create(
1533 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001534 SS.getWithLocInContext(Context),
1535 ULE->getTemplateKeywordLoc(), 0,
Francois Pichetf7400122011-09-04 23:00:48 +00001536 R.getLookupNameInfo(),
1537 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001538 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001539 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001540 // FIXME: we should be able to handle this case too. It is correct
1541 // to add this-> here. This is a workaround for PR7947.
1542 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001543 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001544 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00001545 if (getLangOpts().MicrosoftMode)
Francois Pichete614d6c2011-11-15 23:33:34 +00001546 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCall578b69b2009-12-16 08:11:27 +00001547 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001548 }
John McCall578b69b2009-12-16 08:11:27 +00001549
1550 // Do we really want to note all of these?
1551 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1552 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1553
Francois Pichete6226ae2011-11-17 03:44:24 +00001554 // Return true if we are inside a default argument instantiation
1555 // and the found name refers to an instance member function, otherwise
1556 // the function calling DiagnoseEmptyLookup will try to create an
1557 // implicit member call and this is wrong for default argument.
1558 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1559 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1560 return true;
1561 }
1562
John McCall578b69b2009-12-16 08:11:27 +00001563 // Tell the callee to try to recover.
1564 return false;
1565 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001566
1567 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001568 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001569
1570 // In Microsoft mode, if we are performing lookup from within a friend
1571 // function definition declared at class scope then we must set
1572 // DC to the lexical parent to be able to search into the parent
1573 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001574 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001575 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1576 DC->getLexicalParent()->isRecord())
1577 DC = DC->getLexicalParent();
1578 else
1579 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001580 }
1581
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001582 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001583 TypoCorrection Corrected;
1584 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001585 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001586 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1587 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001588 R.setLookupName(Corrected.getCorrection());
1589
Hans Wennborg701d1e72011-07-12 08:45:31 +00001590 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001591 if (Corrected.isOverloaded()) {
1592 OverloadCandidateSet OCS(R.getNameLoc());
1593 OverloadCandidateSet::iterator Best;
1594 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1595 CDEnd = Corrected.end();
1596 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001597 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001598 dyn_cast<FunctionTemplateDecl>(*CD))
1599 AddTemplateOverloadCandidate(
1600 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001601 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001602 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1603 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1604 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001605 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001606 }
1607 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1608 case OR_Success:
1609 ND = Best->Function;
1610 break;
1611 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001612 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001613 }
1614 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001615 R.addDecl(ND);
1616 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001617 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001618 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1619 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001620 else
1621 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001622 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001623 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001624 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1625 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001626 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001627 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001628
1629 // Tell the callee to try to recover.
1630 return false;
1631 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001632
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001633 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001634 // FIXME: If we ended up with a typo for a type name or
1635 // Objective-C class name, we're in trouble because the parser
1636 // is in the wrong place to recover. Suggest the typo
1637 // correction, but don't make it a fix-it since we're not going
1638 // to recover well anyway.
1639 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001640 Diag(R.getNameLoc(), diagnostic_suggest)
1641 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001642 else
1643 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001644 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001645 << SS.getRange();
1646
1647 // Don't try to recover; it won't work.
1648 return true;
1649 }
1650 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001651 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001652 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001653 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001654 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001655 else
Douglas Gregord203a162010-01-01 00:15:04 +00001656 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001657 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001658 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001659 return true;
1660 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001661 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001662 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001663
1664 // Emit a special diagnostic for failed member lookups.
1665 // FIXME: computing the declaration context might fail here (?)
1666 if (!SS.isEmpty()) {
1667 Diag(R.getNameLoc(), diag::err_no_member)
1668 << Name << computeDeclContext(SS, false)
1669 << SS.getRange();
1670 return true;
1671 }
1672
John McCall578b69b2009-12-16 08:11:27 +00001673 // Give up, we can't recover.
1674 Diag(R.getNameLoc(), diagnostic) << Name;
1675 return true;
1676}
1677
John McCall60d7b3a2010-08-24 06:29:42 +00001678ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001679 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001680 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001681 UnqualifiedId &Id,
1682 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001683 bool IsAddressOfOperand,
1684 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001685 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001686 "cannot be direct & operand and have a trailing lparen");
1687
1688 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001689 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001690
John McCall129e2df2009-11-30 22:42:35 +00001691 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001692
1693 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001694 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001695 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001696 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001697
Abramo Bagnara25777432010-08-11 22:01:17 +00001698 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001699 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001700 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001701
John McCallf7a1a742009-11-24 19:00:30 +00001702 // C++ [temp.dep.expr]p3:
1703 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001704 // -- an identifier that was declared with a dependent type,
1705 // (note: handled after lookup)
1706 // -- a template-id that is dependent,
1707 // (note: handled in BuildTemplateIdExpr)
1708 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001709 // -- a nested-name-specifier that contains a class-name that
1710 // names a dependent type.
1711 // Determine whether this is a member of an unknown specialization;
1712 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001713 bool DependentID = false;
1714 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1715 Name.getCXXNameType()->isDependentType()) {
1716 DependentID = true;
1717 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001718 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001719 if (RequireCompleteDeclContext(SS, DC))
1720 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001721 } else {
1722 DependentID = true;
1723 }
1724 }
1725
Chris Lattner337e5502011-02-18 01:27:55 +00001726 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001727 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1728 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001729
John McCallf7a1a742009-11-24 19:00:30 +00001730 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001731 LookupResult R(*this, NameInfo,
1732 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1733 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001734 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001735 // Lookup the template name again to correctly establish the context in
1736 // which it was found. This is really unfortunate as we already did the
1737 // lookup to determine that it was a template name in the first place. If
1738 // this becomes a performance hit, we can work harder to preserve those
1739 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001740 bool MemberOfUnknownSpecialization;
1741 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1742 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001743
1744 if (MemberOfUnknownSpecialization ||
1745 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001746 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1747 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001748 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001749 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001750 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001752 // If the result might be in a dependent base class, this is a dependent
1753 // id-expression.
1754 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001755 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1756 IsAddressOfOperand, TemplateArgs);
1757
John McCallf7a1a742009-11-24 19:00:30 +00001758 // If this reference is in an Objective-C method, then we need to do
1759 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001760 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001761 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001762 if (E.isInvalid())
1763 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Chris Lattner337e5502011-02-18 01:27:55 +00001765 if (Expr *Ex = E.takeAs<Expr>())
1766 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001767 }
Chris Lattner8a934232008-03-31 00:36:02 +00001768 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001769
John McCallf7a1a742009-11-24 19:00:30 +00001770 if (R.isAmbiguous())
1771 return ExprError();
1772
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001773 // Determine whether this name might be a candidate for
1774 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001775 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001776
John McCallf7a1a742009-11-24 19:00:30 +00001777 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001779 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001780 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001781 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1782 if (D) R.addDecl(D);
1783 }
1784
1785 // If this name wasn't predeclared and if this is not a function
1786 // call, diagnose the problem.
1787 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001788
1789 // In Microsoft mode, if we are inside a template class member function
1790 // and we can't resolve an identifier then assume the identifier is type
1791 // dependent. The goal is to postpone name lookup to instantiation time
1792 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001793 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001794 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001795 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1796 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001797
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001798 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001799 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001800 return ExprError();
1801
1802 assert(!R.empty() &&
1803 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001804
1805 // If we found an Objective-C instance variable, let
1806 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001807 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001808 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1809 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001810 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001811 // In a hopelessly buggy code, Objective-C instance variable
1812 // lookup fails and no expression will be built to reference it.
1813 if (!E.isInvalid() && !E.get())
1814 return ExprError();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001815 return move(E);
1816 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 }
1818 }
Mike Stump1eb44332009-09-09 15:08:12 +00001819
John McCallf7a1a742009-11-24 19:00:30 +00001820 // This is guaranteed from this point on.
1821 assert(!R.empty() || ADL);
1822
John McCallaa81e162009-12-01 22:10:20 +00001823 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001824 // C++ [class.mfct.non-static]p3:
1825 // When an id-expression that is not part of a class member access
1826 // syntax and not used to form a pointer to member is used in the
1827 // body of a non-static member function of class X, if name lookup
1828 // resolves the name in the id-expression to a non-static non-type
1829 // member of some class C, the id-expression is transformed into a
1830 // class member access expression using (*this) as the
1831 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001832 //
1833 // But we don't actually need to do this for '&' operands if R
1834 // resolved to a function or overloaded function set, because the
1835 // expression is ill-formed if it actually works out to be a
1836 // non-static member function:
1837 //
1838 // C++ [expr.ref]p4:
1839 // Otherwise, if E1.E2 refers to a non-static member function. . .
1840 // [t]he expression can be used only as the left-hand operand of a
1841 // member function call.
1842 //
1843 // There are other safeguards against such uses, but it's important
1844 // to get this right here so that we don't end up making a
1845 // spuriously dependent expression if we're inside a dependent
1846 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001847 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001848 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001849 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001850 MightBeImplicitMember = true;
1851 else if (!SS.isEmpty())
1852 MightBeImplicitMember = false;
1853 else if (R.isOverloadedResult())
1854 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001855 else if (R.isUnresolvableResult())
1856 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001857 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001858 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1859 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001860
1861 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001862 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1863 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001864 }
1865
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001866 if (TemplateArgs || TemplateKWLoc.isValid())
1867 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001868
John McCallf7a1a742009-11-24 19:00:30 +00001869 return BuildDeclarationNameExpr(SS, R, ADL);
1870}
1871
John McCall129e2df2009-11-30 22:42:35 +00001872/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1873/// declaration name, generally during template instantiation.
1874/// There's a large number of things which don't need to be done along
1875/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001876ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001877Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001878 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001879 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001880 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001881 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1882 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001883
John McCall77bb1aa2010-05-01 00:40:08 +00001884 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001885 return ExprError();
1886
Abramo Bagnara25777432010-08-11 22:01:17 +00001887 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001888 LookupQualifiedName(R, DC);
1889
1890 if (R.isAmbiguous())
1891 return ExprError();
1892
1893 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001894 Diag(NameInfo.getLoc(), diag::err_no_member)
1895 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001896 return ExprError();
1897 }
1898
1899 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1900}
1901
1902/// LookupInObjCMethod - The parser has read a name in, and Sema has
1903/// detected that we're currently inside an ObjC method. Perform some
1904/// additional lookup.
1905///
1906/// Ideally, most of this would be done by lookup, but there's
1907/// actually quite a lot of extra work involved.
1908///
1909/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001910ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001911Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001912 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001913 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001914 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001915
John McCallf7a1a742009-11-24 19:00:30 +00001916 // There are two cases to handle here. 1) scoped lookup could have failed,
1917 // in which case we should look for an ivar. 2) scoped lookup could have
1918 // found a decl, but that decl is outside the current instance method (i.e.
1919 // a global variable). In these two cases, we do a lookup for an ivar with
1920 // this name, if the lookup sucedes, we replace it our current decl.
1921
1922 // If we're in a class method, we don't normally want to look for
1923 // ivars. But if we don't find anything else, and there's an
1924 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001925 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001926
1927 bool LookForIvars;
1928 if (Lookup.empty())
1929 LookForIvars = true;
1930 else if (IsClassMethod)
1931 LookForIvars = false;
1932 else
1933 LookForIvars = (Lookup.isSingleResult() &&
1934 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001935 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001936 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001937 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001938 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001939 ObjCIvarDecl *IV = 0;
1940 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001941 // Diagnose using an ivar in a class method.
1942 if (IsClassMethod)
1943 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1944 << IV->getDeclName());
1945
1946 // If we're referencing an invalid decl, just return this as a silent
1947 // error node. The error diagnostic was already emitted on the decl.
1948 if (IV->isInvalidDecl())
1949 return ExprError();
1950
1951 // Check if referencing a field with __attribute__((deprecated)).
1952 if (DiagnoseUseOfDecl(IV, Loc))
1953 return ExprError();
1954
1955 // Diagnose the use of an ivar outside of the declaring class.
1956 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001957 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001958 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001959 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1960
1961 // FIXME: This should use a new expr for a direct reference, don't
1962 // turn this into Self->ivar, just return a BareIVarExpr or something.
1963 IdentifierInfo &II = Context.Idents.get("self");
1964 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001965 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001966 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001967 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001968 SourceLocation TemplateKWLoc;
1969 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001970 SelfName, false, false);
1971 if (SelfExpr.isInvalid())
1972 return ExprError();
1973
John Wiegley429bb272011-04-08 18:41:53 +00001974 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1975 if (SelfExpr.isInvalid())
1976 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001977
Eli Friedman5f2987c2012-02-02 03:46:19 +00001978 MarkAnyDeclReferenced(Loc, IV);
John McCallf7a1a742009-11-24 19:00:30 +00001979 return Owned(new (Context)
1980 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001981 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001982 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001983 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001984 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001985 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1986 ObjCInterfaceDecl *ClassDeclared;
1987 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1988 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00001989 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001990 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1991 }
John McCallf7a1a742009-11-24 19:00:30 +00001992 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00001993 } else if (Lookup.isSingleResult() &&
1994 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1995 // If accessing a stand-alone ivar in a class method, this is an error.
1996 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1997 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1998 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00001999 }
2000
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002001 if (Lookup.empty() && II && AllowBuiltinCreation) {
2002 // FIXME. Consolidate this with similar code in LookupName.
2003 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002004 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002005 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2006 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2007 S, Lookup.isForRedeclaration(),
2008 Lookup.getNameLoc());
2009 if (D) Lookup.addDecl(D);
2010 }
2011 }
2012 }
John McCallf7a1a742009-11-24 19:00:30 +00002013 // Sentinel value saying that we didn't do anything special.
2014 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002015}
John McCallba135432009-11-21 08:51:07 +00002016
John McCall6bb80172010-03-30 21:47:33 +00002017/// \brief Cast a base object to a member's actual type.
2018///
2019/// Logically this happens in three phases:
2020///
2021/// * First we cast from the base type to the naming class.
2022/// The naming class is the class into which we were looking
2023/// when we found the member; it's the qualifier type if a
2024/// qualifier was provided, and otherwise it's the base type.
2025///
2026/// * Next we cast from the naming class to the declaring class.
2027/// If the member we found was brought into a class's scope by
2028/// a using declaration, this is that class; otherwise it's
2029/// the class declaring the member.
2030///
2031/// * Finally we cast from the declaring class to the "true"
2032/// declaring class of the member. This conversion does not
2033/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002034ExprResult
2035Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002036 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002037 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002038 NamedDecl *Member) {
2039 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2040 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002041 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002042
Douglas Gregor5fccd362010-03-03 23:55:11 +00002043 QualType DestRecordType;
2044 QualType DestType;
2045 QualType FromRecordType;
2046 QualType FromType = From->getType();
2047 bool PointerConversions = false;
2048 if (isa<FieldDecl>(Member)) {
2049 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002050
Douglas Gregor5fccd362010-03-03 23:55:11 +00002051 if (FromType->getAs<PointerType>()) {
2052 DestType = Context.getPointerType(DestRecordType);
2053 FromRecordType = FromType->getPointeeType();
2054 PointerConversions = true;
2055 } else {
2056 DestType = DestRecordType;
2057 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002058 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002059 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2060 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002061 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002062
Douglas Gregor5fccd362010-03-03 23:55:11 +00002063 DestType = Method->getThisType(Context);
2064 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002065
Douglas Gregor5fccd362010-03-03 23:55:11 +00002066 if (FromType->getAs<PointerType>()) {
2067 FromRecordType = FromType->getPointeeType();
2068 PointerConversions = true;
2069 } else {
2070 FromRecordType = FromType;
2071 DestType = DestRecordType;
2072 }
2073 } else {
2074 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002075 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002076 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002077
Douglas Gregor5fccd362010-03-03 23:55:11 +00002078 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002079 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002080
Douglas Gregor5fccd362010-03-03 23:55:11 +00002081 // If the unqualified types are the same, no conversion is necessary.
2082 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002083 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002084
John McCall6bb80172010-03-30 21:47:33 +00002085 SourceRange FromRange = From->getSourceRange();
2086 SourceLocation FromLoc = FromRange.getBegin();
2087
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002088 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002089
Douglas Gregor5fccd362010-03-03 23:55:11 +00002090 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002091 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002092 // class name.
2093 //
2094 // If the member was a qualified name and the qualified referred to a
2095 // specific base subobject type, we'll cast to that intermediate type
2096 // first and then to the object in which the member is declared. That allows
2097 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2098 //
2099 // class Base { public: int x; };
2100 // class Derived1 : public Base { };
2101 // class Derived2 : public Base { };
2102 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2103 //
2104 // void VeryDerived::f() {
2105 // x = 17; // error: ambiguous base subobjects
2106 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2107 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002108 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002109 QualType QType = QualType(Qualifier->getAsType(), 0);
2110 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2111 assert(QType->isRecordType() && "lookup done with non-record type");
2112
2113 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2114
2115 // In C++98, the qualifier type doesn't actually have to be a base
2116 // type of the object type, in which case we just ignore it.
2117 // Otherwise build the appropriate casts.
2118 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002119 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002120 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002121 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002122 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002123
Douglas Gregor5fccd362010-03-03 23:55:11 +00002124 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002125 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002126 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2127 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002128
2129 FromType = QType;
2130 FromRecordType = QRecordType;
2131
2132 // If the qualifier type was the same as the destination type,
2133 // we're done.
2134 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002135 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002136 }
2137 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002138
John McCall6bb80172010-03-30 21:47:33 +00002139 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002140
John McCall6bb80172010-03-30 21:47:33 +00002141 // If we actually found the member through a using declaration, cast
2142 // down to the using declaration's type.
2143 //
2144 // Pointer equality is fine here because only one declaration of a
2145 // class ever has member declarations.
2146 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2147 assert(isa<UsingShadowDecl>(FoundDecl));
2148 QualType URecordType = Context.getTypeDeclType(
2149 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2150
2151 // We only need to do this if the naming-class to declaring-class
2152 // conversion is non-trivial.
2153 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2154 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002155 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002156 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002157 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002158 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002159
John McCall6bb80172010-03-30 21:47:33 +00002160 QualType UType = URecordType;
2161 if (PointerConversions)
2162 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002163 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2164 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002165 FromType = UType;
2166 FromRecordType = URecordType;
2167 }
2168
2169 // We don't do access control for the conversion from the
2170 // declaring class to the true declaring class.
2171 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002172 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002173
John McCallf871d0c2010-08-07 06:22:56 +00002174 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002175 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2176 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002177 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002178 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002179
John Wiegley429bb272011-04-08 18:41:53 +00002180 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2181 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002182}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002183
John McCallf7a1a742009-11-24 19:00:30 +00002184bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002185 const LookupResult &R,
2186 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002187 // Only when used directly as the postfix-expression of a call.
2188 if (!HasTrailingLParen)
2189 return false;
2190
2191 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002192 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002193 return false;
2194
2195 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002196 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002197 return false;
2198
2199 // Turn off ADL when we find certain kinds of declarations during
2200 // normal lookup:
2201 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2202 NamedDecl *D = *I;
2203
2204 // C++0x [basic.lookup.argdep]p3:
2205 // -- a declaration of a class member
2206 // Since using decls preserve this property, we check this on the
2207 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002208 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002209 return false;
2210
2211 // C++0x [basic.lookup.argdep]p3:
2212 // -- a block-scope function declaration that is not a
2213 // using-declaration
2214 // NOTE: we also trigger this for function templates (in fact, we
2215 // don't check the decl type at all, since all other decl types
2216 // turn off ADL anyway).
2217 if (isa<UsingShadowDecl>(D))
2218 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2219 else if (D->getDeclContext()->isFunctionOrMethod())
2220 return false;
2221
2222 // C++0x [basic.lookup.argdep]p3:
2223 // -- a declaration that is neither a function or a function
2224 // template
2225 // And also for builtin functions.
2226 if (isa<FunctionDecl>(D)) {
2227 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2228
2229 // But also builtin functions.
2230 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2231 return false;
2232 } else if (!isa<FunctionTemplateDecl>(D))
2233 return false;
2234 }
2235
2236 return true;
2237}
2238
2239
John McCallba135432009-11-21 08:51:07 +00002240/// Diagnoses obvious problems with the use of the given declaration
2241/// as an expression. This is only actually called for lookups that
2242/// were not overloaded, and it doesn't promise that the declaration
2243/// will in fact be used.
2244static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002245 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002246 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2247 return true;
2248 }
2249
2250 if (isa<ObjCInterfaceDecl>(D)) {
2251 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2252 return true;
2253 }
2254
2255 if (isa<NamespaceDecl>(D)) {
2256 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2257 return true;
2258 }
2259
2260 return false;
2261}
2262
John McCall60d7b3a2010-08-24 06:29:42 +00002263ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002264Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002265 LookupResult &R,
2266 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002267 // If this is a single, fully-resolved result and we don't need ADL,
2268 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002269 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002270 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2271 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002272
2273 // We only need to check the declaration if there's exactly one
2274 // result, because in the overloaded case the results can only be
2275 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002276 if (R.isSingleResult() &&
2277 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002278 return ExprError();
2279
John McCallc373d482010-01-27 01:50:18 +00002280 // Otherwise, just build an unresolved lookup expression. Suppress
2281 // any lookup-related diagnostics; we'll hash these out later, when
2282 // we've picked a target.
2283 R.suppressDiagnostics();
2284
John McCallba135432009-11-21 08:51:07 +00002285 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002286 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002287 SS.getWithLocInContext(Context),
2288 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002289 NeedsADL, R.isOverloadedResult(),
2290 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002291
2292 return Owned(ULE);
2293}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002294
John McCallba135432009-11-21 08:51:07 +00002295/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002296ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002297Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002298 const DeclarationNameInfo &NameInfo,
2299 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002300 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002301 assert(!isa<FunctionTemplateDecl>(D) &&
2302 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002303
Abramo Bagnara25777432010-08-11 22:01:17 +00002304 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002305 if (CheckDeclInExpr(*this, Loc, D))
2306 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002307
Douglas Gregor9af2f522009-12-01 16:58:18 +00002308 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2309 // Specifically diagnose references to class templates that are missing
2310 // a template argument list.
2311 Diag(Loc, diag::err_template_decl_ref)
2312 << Template << SS.getRange();
2313 Diag(Template->getLocation(), diag::note_template_decl_here);
2314 return ExprError();
2315 }
2316
2317 // Make sure that we're referring to a value.
2318 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2319 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002320 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002321 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002322 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002323 return ExprError();
2324 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002325
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002326 // Check whether this declaration can be used. Note that we suppress
2327 // this check when we're going to perform argument-dependent lookup
2328 // on this function name, because this might not be the function
2329 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002330 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002331 return ExprError();
2332
Steve Naroffdd972f22008-09-05 22:11:13 +00002333 // Only create DeclRefExpr's for valid Decl's.
2334 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002335 return ExprError();
2336
John McCall5808ce42011-02-03 08:15:49 +00002337 // Handle members of anonymous structs and unions. If we got here,
2338 // and the reference is to a class member indirect field, then this
2339 // must be the subject of a pointer-to-member expression.
2340 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2341 if (!indirectField->isCXXClassMember())
2342 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2343 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002344
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002345 {
John McCall76a40212011-02-09 01:13:10 +00002346 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002347 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002348
2349 switch (D->getKind()) {
2350 // Ignore all the non-ValueDecl kinds.
2351#define ABSTRACT_DECL(kind)
2352#define VALUE(type, base)
2353#define DECL(type, base) \
2354 case Decl::type:
2355#include "clang/AST/DeclNodes.inc"
2356 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002357
2358 // These shouldn't make it here.
2359 case Decl::ObjCAtDefsField:
2360 case Decl::ObjCIvar:
2361 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002362
2363 // Enum constants are always r-values and never references.
2364 // Unresolved using declarations are dependent.
2365 case Decl::EnumConstant:
2366 case Decl::UnresolvedUsingValue:
2367 valueKind = VK_RValue;
2368 break;
2369
2370 // Fields and indirect fields that got here must be for
2371 // pointer-to-member expressions; we just call them l-values for
2372 // internal consistency, because this subexpression doesn't really
2373 // exist in the high-level semantics.
2374 case Decl::Field:
2375 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002376 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002377 "building reference to field in C?");
2378
2379 // These can't have reference type in well-formed programs, but
2380 // for internal consistency we do this anyway.
2381 type = type.getNonReferenceType();
2382 valueKind = VK_LValue;
2383 break;
2384
2385 // Non-type template parameters are either l-values or r-values
2386 // depending on the type.
2387 case Decl::NonTypeTemplateParm: {
2388 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2389 type = reftype->getPointeeType();
2390 valueKind = VK_LValue; // even if the parameter is an r-value reference
2391 break;
2392 }
2393
2394 // For non-references, we need to strip qualifiers just in case
2395 // the template parameter was declared as 'const int' or whatever.
2396 valueKind = VK_RValue;
2397 type = type.getUnqualifiedType();
2398 break;
2399 }
2400
2401 case Decl::Var:
2402 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002403 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002404 !type.hasQualifiers() &&
2405 type->isVoidType()) {
2406 valueKind = VK_RValue;
2407 break;
2408 }
2409 // fallthrough
2410
2411 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002412 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002413 // These are always l-values.
2414 valueKind = VK_LValue;
2415 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002416
Douglas Gregor68932842012-02-18 05:51:20 +00002417 // FIXME: Does the addition of const really only apply in
2418 // potentially-evaluated contexts? Since the variable isn't actually
2419 // captured in an unevaluated context, it seems that the answer is no.
2420 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2421 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2422 if (!CapturedType.isNull())
2423 type = CapturedType;
2424 }
2425
John McCall76a40212011-02-09 01:13:10 +00002426 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002427 }
2428
John McCall76a40212011-02-09 01:13:10 +00002429 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002430 const FunctionType *fty = type->castAs<FunctionType>();
2431
2432 // If we're referring to a function with an __unknown_anytype
2433 // result type, make the entire expression __unknown_anytype.
2434 if (fty->getResultType() == Context.UnknownAnyTy) {
2435 type = Context.UnknownAnyTy;
2436 valueKind = VK_RValue;
2437 break;
2438 }
2439
John McCall76a40212011-02-09 01:13:10 +00002440 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002441 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002442 valueKind = VK_LValue;
2443 break;
2444 }
2445
2446 // C99 DR 316 says that, if a function type comes from a
2447 // function definition (without a prototype), that type is only
2448 // used for checking compatibility. Therefore, when referencing
2449 // the function, we pretend that we don't have the full function
2450 // type.
John McCall755d8492011-04-12 00:42:48 +00002451 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2452 isa<FunctionProtoType>(fty))
2453 type = Context.getFunctionNoProtoType(fty->getResultType(),
2454 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002455
2456 // Functions are r-values in C.
2457 valueKind = VK_RValue;
2458 break;
2459 }
2460
2461 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002462 // If we're referring to a method with an __unknown_anytype
2463 // result type, make the entire expression __unknown_anytype.
2464 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002465 if (const FunctionProtoType *proto
2466 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002467 if (proto->getResultType() == Context.UnknownAnyTy) {
2468 type = Context.UnknownAnyTy;
2469 valueKind = VK_RValue;
2470 break;
2471 }
2472
John McCall76a40212011-02-09 01:13:10 +00002473 // C++ methods are l-values if static, r-values if non-static.
2474 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2475 valueKind = VK_LValue;
2476 break;
2477 }
2478 // fallthrough
2479
2480 case Decl::CXXConversion:
2481 case Decl::CXXDestructor:
2482 case Decl::CXXConstructor:
2483 valueKind = VK_RValue;
2484 break;
2485 }
2486
2487 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2488 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002489}
2490
John McCall755d8492011-04-12 00:42:48 +00002491ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002492 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002493
Reid Spencer5f016e22007-07-11 17:01:13 +00002494 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002495 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002496 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2497 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2498 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002499 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002500
Chris Lattnerfa28b302008-01-12 08:14:25 +00002501 // Pre-defined identifiers are of type char[x], where x is the length of the
2502 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Anders Carlsson3a082d82009-09-08 18:24:21 +00002504 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002505 if (!currentDecl && getCurBlock())
2506 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002507 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002508 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002509 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002510 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002511
Anders Carlsson773f3972009-09-11 01:22:35 +00002512 QualType ResTy;
2513 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2514 ResTy = Context.DependentTy;
2515 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002516 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002517
Anders Carlsson773f3972009-09-11 01:22:35 +00002518 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002519 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002520 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2521 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002522 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002523}
2524
Richard Smith36f5cfe2012-03-09 08:00:36 +00002525ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002526 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002527 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002528 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002529 if (Invalid)
2530 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002531
Benjamin Kramerddeea562010-02-27 13:44:12 +00002532 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002533 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002534 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002535 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002536
Chris Lattnere8337df2009-12-30 21:19:39 +00002537 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002538 if (Literal.isWide())
2539 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002540 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002541 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002542 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002543 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002544 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002545 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002546 else
2547 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002548
Douglas Gregor5cee1192011-07-27 05:40:30 +00002549 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2550 if (Literal.isWide())
2551 Kind = CharacterLiteral::Wide;
2552 else if (Literal.isUTF16())
2553 Kind = CharacterLiteral::UTF16;
2554 else if (Literal.isUTF32())
2555 Kind = CharacterLiteral::UTF32;
2556
Richard Smithdd66be72012-03-08 01:34:56 +00002557 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2558 Tok.getLocation());
2559
2560 if (Literal.getUDSuffix().empty())
2561 return Owned(Lit);
2562
2563 // We're building a user-defined literal.
2564 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2565 SourceLocation UDSuffixLoc =
2566 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2567
Richard Smith36f5cfe2012-03-09 08:00:36 +00002568 // Make sure we're allowed user-defined literals here.
2569 if (!UDLScope)
2570 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2571
Richard Smithdd66be72012-03-08 01:34:56 +00002572 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2573 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002574 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2575 llvm::makeArrayRef(&Lit, 1),
2576 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002577}
2578
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002579ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2580 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2581 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2582 Context.IntTy, Loc));
2583}
2584
Richard Smithb453ad32012-03-08 08:45:32 +00002585static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2586 QualType Ty, SourceLocation Loc) {
2587 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2588
2589 using llvm::APFloat;
2590 APFloat Val(Format);
2591
2592 APFloat::opStatus result = Literal.GetFloatValue(Val);
2593
2594 // Overflow is always an error, but underflow is only an error if
2595 // we underflowed to zero (APFloat reports denormals as underflow).
2596 if ((result & APFloat::opOverflow) ||
2597 ((result & APFloat::opUnderflow) && Val.isZero())) {
2598 unsigned diagnostic;
2599 SmallString<20> buffer;
2600 if (result & APFloat::opOverflow) {
2601 diagnostic = diag::warn_float_overflow;
2602 APFloat::getLargest(Format).toString(buffer);
2603 } else {
2604 diagnostic = diag::warn_float_underflow;
2605 APFloat::getSmallest(Format).toString(buffer);
2606 }
2607
2608 S.Diag(Loc, diagnostic)
2609 << Ty
2610 << StringRef(buffer.data(), buffer.size());
2611 }
2612
2613 bool isExact = (result == APFloat::opOK);
2614 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2615}
2616
Richard Smith36f5cfe2012-03-09 08:00:36 +00002617ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002618 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002619 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002621 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002622 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002623 }
Ted Kremenek28396602009-01-13 23:19:12 +00002624
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002625 SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002626 // Add padding so that NumericLiteralParser can overread by one character.
2627 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002628 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002629
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002631 bool Invalid = false;
2632 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2633 if (Invalid)
2634 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002635
Mike Stump1eb44332009-09-09 15:08:12 +00002636 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 Tok.getLocation(), PP);
2638 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002639 return ExprError();
2640
Richard Smithb453ad32012-03-08 08:45:32 +00002641 if (Literal.hasUDSuffix()) {
2642 // We're building a user-defined literal.
2643 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2644 SourceLocation UDSuffixLoc =
2645 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2646
Richard Smith36f5cfe2012-03-09 08:00:36 +00002647 // Make sure we're allowed user-defined literals here.
2648 if (!UDLScope)
2649 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002650
Richard Smith36f5cfe2012-03-09 08:00:36 +00002651 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002652 if (Literal.isFloatingLiteral()) {
2653 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2654 // long double, the literal is treated as a call of the form
2655 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002656 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002657 } else {
2658 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2659 // unsigned long long, the literal is treated as a call of the form
2660 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002661 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002662 }
2663
Richard Smith36f5cfe2012-03-09 08:00:36 +00002664 DeclarationName OpName =
2665 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2666 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2667 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2668
2669 // Perform literal operator lookup to determine if we're building a raw
2670 // literal or a cooked one.
2671 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2672 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2673 /*AllowRawAndTemplate*/true)) {
2674 case LOLR_Error:
2675 return ExprError();
2676
2677 case LOLR_Cooked: {
2678 Expr *Lit;
2679 if (Literal.isFloatingLiteral()) {
2680 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2681 } else {
2682 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2683 if (Literal.GetIntegerValue(ResultVal))
2684 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2685 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2686 Tok.getLocation());
2687 }
2688 return BuildLiteralOperatorCall(R, OpNameInfo,
2689 llvm::makeArrayRef(&Lit, 1),
2690 Tok.getLocation());
2691 }
2692
2693 case LOLR_Raw: {
2694 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2695 // literal is treated as a call of the form
2696 // operator "" X ("n")
2697 SourceLocation TokLoc = Tok.getLocation();
2698 unsigned Length = Literal.getUDSuffixOffset();
2699 QualType StrTy = Context.getConstantArrayType(
2700 Context.CharTy, llvm::APInt(32, Length + 1),
2701 ArrayType::Normal, 0);
2702 Expr *Lit = StringLiteral::Create(
2703 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2704 /*Pascal*/false, StrTy, &TokLoc, 1);
2705 return BuildLiteralOperatorCall(R, OpNameInfo,
2706 llvm::makeArrayRef(&Lit, 1), TokLoc);
2707 }
2708
2709 case LOLR_Template:
2710 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2711 // template), L is treated as a call fo the form
2712 // operator "" X <'c1', 'c2', ... 'ck'>()
2713 // where n is the source character sequence c1 c2 ... ck.
2714 TemplateArgumentListInfo ExplicitArgs;
2715 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2716 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2717 llvm::APSInt Value(CharBits, CharIsUnsigned);
2718 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2719 Value = ThisTokBegin[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002720 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002721 TemplateArgumentLocInfo ArgInfo;
2722 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2723 }
2724 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2725 Tok.getLocation(), &ExplicitArgs);
2726 }
2727
2728 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002729 }
2730
Chris Lattner5d661452007-08-26 03:42:43 +00002731 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002732
Chris Lattner5d661452007-08-26 03:42:43 +00002733 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002734 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002735 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002736 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002737 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002738 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002739 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002740 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002741
Richard Smithb453ad32012-03-08 08:45:32 +00002742 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002743
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002744 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002745 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002746 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002747 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002748 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002749 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002750 }
2751 }
Chris Lattner5d661452007-08-26 03:42:43 +00002752 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002753 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002754 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002755 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002756
Neil Boothb9449512007-08-29 22:00:19 +00002757 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00002758 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smithebaf0e62011-10-18 20:49:44 +00002759 Diag(Tok.getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002760 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00002761 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002762
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002764 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2765 // The microsoft literal suffix extensions support 128-bit literals, which
2766 // may be wider than [u]intmax_t.
2767 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2768 MaxWidth = 128;
2769 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002770
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 if (Literal.GetIntegerValue(ResultVal)) {
2772 // If this value didn't fit into uintmax_t, warn and force to ull.
2773 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002774 Ty = Context.UnsignedLongLongTy;
2775 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002776 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 } else {
2778 // If this value fits into a ULL, try to figure out what else it fits into
2779 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002780
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2782 // be an unsigned int.
2783 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2784
2785 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002786 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002787 if (!Literal.isLong && !Literal.isLongLong) {
2788 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002789 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002790
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 // Does it fit in a unsigned int?
2792 if (ResultVal.isIntN(IntSize)) {
2793 // Does it fit in a signed int?
2794 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002795 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002797 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002798 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002801
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002803 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002804 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002805
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 // Does it fit in a unsigned long?
2807 if (ResultVal.isIntN(LongSize)) {
2808 // Does it fit in a signed long?
2809 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002810 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002812 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002813 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002815 }
2816
Stephen Canonb9e05f12012-05-03 22:49:43 +00002817 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002818 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002819 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002820
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 // Does it fit in a unsigned long long?
2822 if (ResultVal.isIntN(LongLongSize)) {
2823 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002824 // To be compatible with MSVC, hex integer literals ending with the
2825 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002826 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002827 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002828 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002830 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002831 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002832 }
2833 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002834
2835 // If it doesn't fit in unsigned long long, and we're using Microsoft
2836 // extensions, then its a 128-bit integer literal.
2837 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2838 if (Literal.isUnsigned)
2839 Ty = Context.UnsignedInt128Ty;
2840 else
2841 Ty = Context.Int128Ty;
2842 Width = 128;
2843 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002844
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 // If we still couldn't decide a type, we probably have something that
2846 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002847 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002849 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002850 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002851 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002852
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002853 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002854 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002855 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002856 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002858
Chris Lattner5d661452007-08-26 03:42:43 +00002859 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2860 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002861 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002862 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002863
2864 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002865}
2866
Richard Trieuccd891a2011-09-09 01:45:06 +00002867ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002868 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002869 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002870}
2871
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002872static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2873 SourceLocation Loc,
2874 SourceRange ArgRange) {
2875 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2876 // scalar or vector data type argument..."
2877 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2878 // type (C99 6.2.5p18) or void.
2879 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2880 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2881 << T << ArgRange;
2882 return true;
2883 }
2884
2885 assert((T->isVoidType() || !T->isIncompleteType()) &&
2886 "Scalar types should always be complete");
2887 return false;
2888}
2889
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002890static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2891 SourceLocation Loc,
2892 SourceRange ArgRange,
2893 UnaryExprOrTypeTrait TraitKind) {
2894 // C99 6.5.3.4p1:
2895 if (T->isFunctionType()) {
2896 // alignof(function) is allowed as an extension.
2897 if (TraitKind == UETT_SizeOf)
2898 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2899 return false;
2900 }
2901
2902 // Allow sizeof(void)/alignof(void) as an extension.
2903 if (T->isVoidType()) {
2904 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2905 return false;
2906 }
2907
2908 return true;
2909}
2910
2911static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2912 SourceLocation Loc,
2913 SourceRange ArgRange,
2914 UnaryExprOrTypeTrait TraitKind) {
2915 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2916 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2917 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2918 << T << (TraitKind == UETT_SizeOf)
2919 << ArgRange;
2920 return true;
2921 }
2922
2923 return false;
2924}
2925
Chandler Carruth9d342d02011-05-26 08:53:10 +00002926/// \brief Check the constrains on expression operands to unary type expression
2927/// and type traits.
2928///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002929/// Completes any types necessary and validates the constraints on the operand
2930/// expression. The logic mostly mirrors the type-based overload, but may modify
2931/// the expression as it completes the type for that expression through template
2932/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002933bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002934 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002935 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002936
2937 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2938 // the result is the size of the referenced type."
2939 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2940 // result shall be the alignment of the referenced type."
2941 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2942 ExprTy = Ref->getPointeeType();
2943
2944 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002945 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2946 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002947
2948 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002949 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2950 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002951 return false;
2952
Richard Trieuccd891a2011-09-09 01:45:06 +00002953 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00002954 diag::err_sizeof_alignof_incomplete_type,
2955 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002956 return true;
2957
2958 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002959 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002960 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2961 ExprTy = Ref->getPointeeType();
2962
Richard Trieuccd891a2011-09-09 01:45:06 +00002963 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2964 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002965 return true;
2966
Nico Webercf739922011-06-15 02:47:03 +00002967 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002968 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002969 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2970 QualType OType = PVD->getOriginalType();
2971 QualType Type = PVD->getType();
2972 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002973 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002974 << Type << OType;
2975 Diag(PVD->getLocation(), diag::note_declared_at);
2976 }
2977 }
2978 }
2979 }
2980
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002981 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002982}
2983
2984/// \brief Check the constraints on operands to unary expression and type
2985/// traits.
2986///
2987/// This will complete any types necessary, and validate the various constraints
2988/// on those operands.
2989///
Reid Spencer5f016e22007-07-11 17:01:13 +00002990/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002991/// C99 6.3.2.1p[2-4] all state:
2992/// Except when it is the operand of the sizeof operator ...
2993///
2994/// C++ [expr.sizeof]p4
2995/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2996/// standard conversions are not applied to the operand of sizeof.
2997///
2998/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002999bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003000 SourceLocation OpLoc,
3001 SourceRange ExprRange,
3002 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003003 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003004 return false;
3005
Sebastian Redl5d484e82009-11-23 17:18:46 +00003006 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3007 // the result is the size of the referenced type."
3008 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3009 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003010 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3011 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003012
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003013 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003014 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003015
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003016 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003017 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003018 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003019 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003020
Richard Trieuccd891a2011-09-09 01:45:06 +00003021 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003022 diag::err_sizeof_alignof_incomplete_type,
3023 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003024 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Richard Trieuccd891a2011-09-09 01:45:06 +00003026 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003027 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003028 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003029
Chris Lattner1efaa952009-04-24 00:30:45 +00003030 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003031}
3032
Chandler Carruth9d342d02011-05-26 08:53:10 +00003033static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003034 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003035
Mike Stump1eb44332009-09-09 15:08:12 +00003036 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003037 if (isa<DeclRefExpr>(E))
3038 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003039
3040 // Cannot know anything else if the expression is dependent.
3041 if (E->isTypeDependent())
3042 return false;
3043
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003044 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003045 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3046 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003047 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003048 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003049
3050 // Alignment of a field access is always okay, so long as it isn't a
3051 // bit-field.
3052 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003053 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003054 return false;
3055
Chandler Carruth9d342d02011-05-26 08:53:10 +00003056 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003057}
3058
Chandler Carruth9d342d02011-05-26 08:53:10 +00003059bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003060 E = E->IgnoreParens();
3061
3062 // Cannot know anything else if the expression is dependent.
3063 if (E->isTypeDependent())
3064 return false;
3065
Chandler Carruth9d342d02011-05-26 08:53:10 +00003066 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003067}
3068
Douglas Gregorba498172009-03-13 21:01:28 +00003069/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003070ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003071Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3072 SourceLocation OpLoc,
3073 UnaryExprOrTypeTrait ExprKind,
3074 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003075 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003076 return ExprError();
3077
John McCalla93c9342009-12-07 02:54:59 +00003078 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003079
Douglas Gregorba498172009-03-13 21:01:28 +00003080 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003081 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003082 return ExprError();
3083
3084 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003085 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3086 Context.getSizeType(),
3087 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003088}
3089
3090/// \brief Build a sizeof or alignof expression given an expression
3091/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003092ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003093Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3094 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003095 ExprResult PE = CheckPlaceholderExpr(E);
3096 if (PE.isInvalid())
3097 return ExprError();
3098
3099 E = PE.get();
3100
Douglas Gregorba498172009-03-13 21:01:28 +00003101 // Verify that the operand is valid.
3102 bool isInvalid = false;
3103 if (E->isTypeDependent()) {
3104 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003105 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003106 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003107 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003108 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003109 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003110 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003111 isInvalid = true;
3112 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003113 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003114 }
3115
3116 if (isInvalid)
3117 return ExprError();
3118
Eli Friedman71b8fb52012-01-21 01:01:51 +00003119 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3120 PE = TranformToPotentiallyEvaluated(E);
3121 if (PE.isInvalid()) return ExprError();
3122 E = PE.take();
3123 }
3124
Douglas Gregorba498172009-03-13 21:01:28 +00003125 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003126 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003127 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003128 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003129}
3130
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003131/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3132/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003133/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003134ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003135Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003136 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003137 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003138 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003139 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003140
Richard Trieuccd891a2011-09-09 01:45:06 +00003141 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003142 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003143 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003144 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003145 }
Sebastian Redl05189992008-11-11 17:56:53 +00003146
Douglas Gregorba498172009-03-13 21:01:28 +00003147 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003148 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003149 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003150}
3151
John Wiegley429bb272011-04-08 18:41:53 +00003152static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003153 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003154 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003155 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003156
John McCallf6a16482010-12-04 03:47:34 +00003157 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003158 if (V.get()->getObjectKind() != OK_Ordinary) {
3159 V = S.DefaultLvalueConversion(V.take());
3160 if (V.isInvalid())
3161 return QualType();
3162 }
John McCallf6a16482010-12-04 03:47:34 +00003163
Chris Lattnercc26ed72007-08-26 05:39:26 +00003164 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003165 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003166 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003167
Chris Lattnercc26ed72007-08-26 05:39:26 +00003168 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003169 if (V.get()->getType()->isArithmeticType())
3170 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003171
John McCall2cd11fe2010-10-12 02:09:17 +00003172 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003173 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003174 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003175 if (PR.get() != V.get()) {
3176 V = move(PR);
Richard Trieuccd891a2011-09-09 01:45:06 +00003177 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003178 }
3179
Chris Lattnercc26ed72007-08-26 05:39:26 +00003180 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003181 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003182 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003183 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003184}
3185
3186
Reid Spencer5f016e22007-07-11 17:01:13 +00003187
John McCall60d7b3a2010-08-24 06:29:42 +00003188ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003189Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003190 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003191 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003192 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003193 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003194 case tok::plusplus: Opc = UO_PostInc; break;
3195 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003196 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003197
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003198 // Since this might is a postfix expression, get rid of ParenListExprs.
3199 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3200 if (Result.isInvalid()) return ExprError();
3201 Input = Result.take();
3202
John McCall9ae2f072010-08-23 23:25:46 +00003203 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003204}
3205
John McCall60d7b3a2010-08-24 06:29:42 +00003206ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003207Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3208 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003209 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003210 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003211 if (Result.isInvalid()) return ExprError();
3212 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003213
John McCall9ae2f072010-08-23 23:25:46 +00003214 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003215
David Blaikie4e4d0842012-03-11 07:00:24 +00003216 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003217 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003218 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003219 Context.DependentTy,
3220 VK_LValue, OK_Ordinary,
3221 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003222 }
3223
David Blaikie4e4d0842012-03-11 07:00:24 +00003224 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003225 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003226 LHSExp->getType()->isEnumeralType() ||
3227 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003228 RHSExp->getType()->isEnumeralType()) &&
3229 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003230 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003231 }
3232
John McCall9ae2f072010-08-23 23:25:46 +00003233 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003234}
3235
3236
John McCall60d7b3a2010-08-24 06:29:42 +00003237ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003238Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003239 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003240 Expr *LHSExp = Base;
3241 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003242
Chris Lattner12d9ff62007-07-16 00:14:47 +00003243 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003244 if (!LHSExp->getType()->getAs<VectorType>()) {
3245 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3246 if (Result.isInvalid())
3247 return ExprError();
3248 LHSExp = Result.take();
3249 }
3250 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3251 if (Result.isInvalid())
3252 return ExprError();
3253 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003254
Chris Lattner12d9ff62007-07-16 00:14:47 +00003255 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003256 ExprValueKind VK = VK_LValue;
3257 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003258
Reid Spencer5f016e22007-07-11 17:01:13 +00003259 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003260 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003261 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003262 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003263 Expr *BaseExpr, *IndexExpr;
3264 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003265 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3266 BaseExpr = LHSExp;
3267 IndexExpr = RHSExp;
3268 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003269 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003270 BaseExpr = LHSExp;
3271 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003272 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003273 } else if (const ObjCObjectPointerType *PTy =
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003274 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003275 BaseExpr = LHSExp;
3276 IndexExpr = RHSExp;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003277 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3278 if (!Result.isInvalid())
3279 return Owned(Result.take());
Steve Naroff14108da2009-07-10 23:34:53 +00003280 ResultType = PTy->getPointeeType();
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003281 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3282 // Handle the uncommon case of "123[Ptr]".
3283 BaseExpr = RHSExp;
3284 IndexExpr = LHSExp;
3285 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003286 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003287 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003288 // Handle the uncommon case of "123[Ptr]".
3289 BaseExpr = RHSExp;
3290 IndexExpr = LHSExp;
3291 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003292 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003293 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003294 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003295 VK = LHSExp->getValueKind();
3296 if (VK != VK_RValue)
3297 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003298
Chris Lattner12d9ff62007-07-16 00:14:47 +00003299 // FIXME: need to deal with const...
3300 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003301 } else if (LHSTy->isArrayType()) {
3302 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003303 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003304 // wasn't promoted because of the C90 rule that doesn't
3305 // allow promoting non-lvalue arrays. Warn, then
3306 // force the promotion here.
3307 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3308 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003309 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3310 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003311 LHSTy = LHSExp->getType();
3312
3313 BaseExpr = LHSExp;
3314 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003315 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003316 } else if (RHSTy->isArrayType()) {
3317 // Same as previous, except for 123[f().a] case
3318 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3319 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003320 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3321 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003322 RHSTy = RHSExp->getType();
3323
3324 BaseExpr = RHSExp;
3325 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003326 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003327 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003328 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3329 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003330 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003331 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003332 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003333 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3334 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003335
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003336 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003337 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3338 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003339 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3340
Douglas Gregore7450f52009-03-24 19:52:54 +00003341 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003342 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3343 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003344 // incomplete types are not object types.
3345 if (ResultType->isFunctionType()) {
3346 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3347 << ResultType << BaseExpr->getSourceRange();
3348 return ExprError();
3349 }
Mike Stump1eb44332009-09-09 15:08:12 +00003350
David Blaikie4e4d0842012-03-11 07:00:24 +00003351 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003352 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003353 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3354 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003355
3356 // C forbids expressions of unqualified void type from being l-values.
3357 // See IsCForbiddenLValueType.
3358 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003359 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003360 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003361 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003362 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Chris Lattner1efaa952009-04-24 00:30:45 +00003364 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003365 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003366 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3367 << ResultType << BaseExpr->getSourceRange();
3368 return ExprError();
3369 }
Mike Stump1eb44332009-09-09 15:08:12 +00003370
John McCall09431682010-11-18 19:01:18 +00003371 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003372 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003373
Mike Stumpeed9cac2009-02-19 03:04:26 +00003374 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003375 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003376}
3377
John McCall60d7b3a2010-08-24 06:29:42 +00003378ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003379 FunctionDecl *FD,
3380 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003381 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003382 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003383 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003384 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003385 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003386 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003387 return ExprError();
3388 }
3389
3390 if (Param->hasUninstantiatedDefaultArg()) {
3391 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003392
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003393 // Instantiate the expression.
3394 MultiLevelTemplateArgumentList ArgList
3395 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003396
Nico Weber08e41a62010-11-29 18:19:25 +00003397 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003398 = ArgList.getInnermost();
3399 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3400 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003401
Nico Weber08e41a62010-11-29 18:19:25 +00003402 ExprResult Result;
3403 {
3404 // C++ [dcl.fct.default]p5:
3405 // The names in the [default argument] expression are bound, and
3406 // the semantic constraints are checked, at the point where the
3407 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003408 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003409 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003410 Result = SubstExpr(UninstExpr, ArgList);
3411 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003412 if (Result.isInvalid())
3413 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003415 // Check the expression as an initializer for the parameter.
3416 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003417 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003418 InitializationKind Kind
3419 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003420 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003421 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003422
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003423 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3424 Result = InitSeq.Perform(*this, Entity, Kind,
3425 MultiExprArg(*this, &ResultE, 1));
3426 if (Result.isInvalid())
3427 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003428
David Blaikiec1c07252012-04-30 18:21:31 +00003429 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003430 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003431 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003432 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003433 }
3434
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003435 // If the default expression creates temporaries, we need to
3436 // push them to the current stack of expression temporaries so they'll
3437 // be properly destroyed.
3438 // FIXME: We should really be rebuilding the default argument with new
3439 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003440 // We don't need to do that with block decls, though, because
3441 // blocks in default argument expression can never capture anything.
3442 if (isa<ExprWithCleanups>(Param->getInit())) {
3443 // Set the "needs cleanups" bit regardless of whether there are
3444 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003445 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003446
3447 // Append all the objects to the cleanup list. Right now, this
3448 // should always be a no-op, because blocks in default argument
3449 // expressions should never be able to capture anything.
3450 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3451 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003452 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003453
3454 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003455 // Just mark all of the declarations in this potentially-evaluated expression
3456 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003457 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3458 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003459 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003460}
3461
Douglas Gregor88a35142008-12-22 05:46:06 +00003462/// ConvertArgumentsForCall - Converts the arguments specified in
3463/// Args/NumArgs to the parameter types of the function FDecl with
3464/// function prototype Proto. Call is the call expression itself, and
3465/// Fn is the function expression. For a C++ member function, this
3466/// routine does not attempt to convert the object argument. Returns
3467/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003468bool
3469Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003470 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003471 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003472 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003473 SourceLocation RParenLoc,
3474 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003475 // Bail out early if calling a builtin with custom typechecking.
3476 // We don't need to do this in the
3477 if (FDecl)
3478 if (unsigned ID = FDecl->getBuiltinID())
3479 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3480 return false;
3481
Mike Stumpeed9cac2009-02-19 03:04:26 +00003482 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003483 // assignment, to the types of the corresponding parameter, ...
3484 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003485 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003486 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003487 unsigned FnKind = Fn->getType()->isBlockPointerType()
3488 ? 1 /* block */
3489 : (IsExecConfig ? 3 /* kernel function (exec config) */
3490 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003491
Douglas Gregor88a35142008-12-22 05:46:06 +00003492 // If too few arguments are available (and we don't have default
3493 // arguments for the remaining parameters), don't make the call.
3494 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003495 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003496 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3497 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3498 ? diag::err_typecheck_call_too_few_args_one
3499 : diag::err_typecheck_call_too_few_args_at_least_one)
3500 << FnKind
3501 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3502 else
3503 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3504 ? diag::err_typecheck_call_too_few_args
3505 : diag::err_typecheck_call_too_few_args_at_least)
3506 << FnKind
3507 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003508
3509 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003510 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003511 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3512 << FDecl;
3513
3514 return true;
3515 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003516 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003517 }
3518
3519 // If too many are passed and not variadic, error on the extras and drop
3520 // them.
3521 if (NumArgs > NumArgsInProto) {
3522 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003523 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3524 Diag(Args[NumArgsInProto]->getLocStart(),
3525 MinArgs == NumArgsInProto
3526 ? diag::err_typecheck_call_too_many_args_one
3527 : diag::err_typecheck_call_too_many_args_at_most_one)
3528 << FnKind
3529 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3530 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3531 Args[NumArgs-1]->getLocEnd());
3532 else
3533 Diag(Args[NumArgsInProto]->getLocStart(),
3534 MinArgs == NumArgsInProto
3535 ? diag::err_typecheck_call_too_many_args
3536 : diag::err_typecheck_call_too_many_args_at_most)
3537 << FnKind
3538 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3539 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3540 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003541
3542 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003543 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003544 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3545 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003546
Douglas Gregor88a35142008-12-22 05:46:06 +00003547 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003548 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003549 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003550 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003551 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003552 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003553 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003554 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3555 if (Fn->getType()->isBlockPointerType())
3556 CallType = VariadicBlock; // Block
3557 else if (isa<MemberExpr>(Fn))
3558 CallType = VariadicMethod;
Daniel Dunbar96a00142012-03-09 18:35:03 +00003559 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003560 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003561 if (Invalid)
3562 return true;
3563 unsigned TotalNumArgs = AllArgs.size();
3564 for (unsigned i = 0; i < TotalNumArgs; ++i)
3565 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003566
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003567 return false;
3568}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003569
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003570bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3571 FunctionDecl *FDecl,
3572 const FunctionProtoType *Proto,
3573 unsigned FirstProtoArg,
3574 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003575 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003576 VariadicCallType CallType,
3577 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003578 unsigned NumArgsInProto = Proto->getNumArgs();
3579 unsigned NumArgsToCheck = NumArgs;
3580 bool Invalid = false;
3581 if (NumArgs != NumArgsInProto)
3582 // Use default arguments for missing arguments
3583 NumArgsToCheck = NumArgsInProto;
3584 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003585 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003586 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003587 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003588
Douglas Gregor88a35142008-12-22 05:46:06 +00003589 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003590 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003591 if (ArgIx < NumArgs) {
3592 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003593
Daniel Dunbar96a00142012-03-09 18:35:03 +00003594 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003595 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003596 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003597 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003598
Douglas Gregora188ff22009-12-22 16:09:06 +00003599 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003600 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003601 if (FDecl && i < FDecl->getNumParams())
3602 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003603
John McCall5acb0c92011-10-17 18:40:02 +00003604 // Strip the unbridged-cast placeholder expression off, if applicable.
3605 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3606 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3607 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3608 Arg = stripARCUnbridgedCast(Arg);
3609
Douglas Gregora188ff22009-12-22 16:09:06 +00003610 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003611 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003612 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3613 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003614 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003615 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003616 Owned(Arg),
3617 /*TopLevelOfInitList=*/false,
3618 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003619 if (ArgE.isInvalid())
3620 return true;
3621
3622 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003623 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003624 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003625
John McCall60d7b3a2010-08-24 06:29:42 +00003626 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003627 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003628 if (ArgExpr.isInvalid())
3629 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003630
Anders Carlsson56c5e332009-08-25 03:49:14 +00003631 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003632 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003633
3634 // Check for array bounds violations for each argument to the call. This
3635 // check only triggers warnings when the argument isn't a more complex Expr
3636 // with its own checking, such as a BinaryOperator.
3637 CheckArrayAccess(Arg);
3638
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003639 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3640 CheckStaticArrayArgument(CallLoc, Param, Arg);
3641
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003642 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003643 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003644
Douglas Gregor88a35142008-12-22 05:46:06 +00003645 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003646 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003647
3648 // Assume that extern "C" functions with variadic arguments that
3649 // return __unknown_anytype aren't *really* variadic.
3650 if (Proto->getResultType() == Context.UnknownAnyTy &&
3651 FDecl && FDecl->isExternC()) {
3652 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3653 ExprResult arg;
3654 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3655 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3656 else
3657 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3658 Invalid |= arg.isInvalid();
3659 AllArgs.push_back(arg.take());
3660 }
3661
3662 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3663 } else {
3664 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003665 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3666 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003667 Invalid |= Arg.isInvalid();
3668 AllArgs.push_back(Arg.take());
3669 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003670 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003671
3672 // Check for array bounds violations.
3673 for (unsigned i = ArgIx; i != NumArgs; ++i)
3674 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003675 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003676 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003677}
3678
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003679static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3680 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3681 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3682 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3683 << ATL->getLocalSourceRange();
3684}
3685
3686/// CheckStaticArrayArgument - If the given argument corresponds to a static
3687/// array parameter, check that it is non-null, and that if it is formed by
3688/// array-to-pointer decay, the underlying array is sufficiently large.
3689///
3690/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3691/// array type derivation, then for each call to the function, the value of the
3692/// corresponding actual argument shall provide access to the first element of
3693/// an array with at least as many elements as specified by the size expression.
3694void
3695Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3696 ParmVarDecl *Param,
3697 const Expr *ArgExpr) {
3698 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003699 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003700 return;
3701
3702 QualType OrigTy = Param->getOriginalType();
3703
3704 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3705 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3706 return;
3707
3708 if (ArgExpr->isNullPointerConstant(Context,
3709 Expr::NPC_NeverValueDependent)) {
3710 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3711 DiagnoseCalleeStaticArrayParam(*this, Param);
3712 return;
3713 }
3714
3715 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3716 if (!CAT)
3717 return;
3718
3719 const ConstantArrayType *ArgCAT =
3720 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3721 if (!ArgCAT)
3722 return;
3723
3724 if (ArgCAT->getSize().ult(CAT->getSize())) {
3725 Diag(CallLoc, diag::warn_static_array_too_small)
3726 << ArgExpr->getSourceRange()
3727 << (unsigned) ArgCAT->getSize().getZExtValue()
3728 << (unsigned) CAT->getSize().getZExtValue();
3729 DiagnoseCalleeStaticArrayParam(*this, Param);
3730 }
3731}
3732
John McCall755d8492011-04-12 00:42:48 +00003733/// Given a function expression of unknown-any type, try to rebuild it
3734/// to have a function type.
3735static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3736
Steve Narofff69936d2007-09-16 03:34:24 +00003737/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003738/// This provides the location of the left/right parens and a list of comma
3739/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003740ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003741Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003742 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003743 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003744 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003745
3746 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003747 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003748 if (Result.isInvalid()) return ExprError();
3749 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Richard Trieuccd891a2011-09-09 01:45:06 +00003751 Expr **Args = ArgExprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003752
David Blaikie4e4d0842012-03-11 07:00:24 +00003753 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003754 // If this is a pseudo-destructor expression, build the call immediately.
3755 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3756 if (NumArgs > 0) {
3757 // Pseudo-destructor calls should not have any arguments.
3758 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003759 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003760 SourceRange(Args[0]->getLocStart(),
3761 Args[NumArgs-1]->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003762 }
Mike Stump1eb44332009-09-09 15:08:12 +00003763
Douglas Gregora71d8192009-09-04 17:36:40 +00003764 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003765 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003766 }
Mike Stump1eb44332009-09-09 15:08:12 +00003767
Douglas Gregor17330012009-02-04 15:01:18 +00003768 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003769 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003770 // FIXME: Will need to cache the results of name lookup (including ADL) in
3771 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003772 bool Dependent = false;
3773 if (Fn->isTypeDependent())
3774 Dependent = true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003775 else if (Expr::hasAnyTypeDependentArguments(
3776 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregor17330012009-02-04 15:01:18 +00003777 Dependent = true;
3778
Peter Collingbournee08ce652011-02-09 21:07:24 +00003779 if (Dependent) {
3780 if (ExecConfig) {
3781 return Owned(new (Context) CUDAKernelCallExpr(
3782 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3783 Context.DependentTy, VK_RValue, RParenLoc));
3784 } else {
3785 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3786 Context.DependentTy, VK_RValue,
3787 RParenLoc));
3788 }
3789 }
Douglas Gregor17330012009-02-04 15:01:18 +00003790
3791 // Determine whether this is a call to an object (C++ [over.call.object]).
3792 if (Fn->getType()->isRecordType())
3793 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003794 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003795
John McCall755d8492011-04-12 00:42:48 +00003796 if (Fn->getType() == Context.UnknownAnyTy) {
3797 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3798 if (result.isInvalid()) return ExprError();
3799 Fn = result.take();
3800 }
3801
John McCall864c0412011-04-26 20:42:42 +00003802 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003803 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003804 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003805 }
John McCall864c0412011-04-26 20:42:42 +00003806 }
John McCall129e2df2009-11-30 22:42:35 +00003807
John McCall864c0412011-04-26 20:42:42 +00003808 // Check for overloaded calls. This can happen even in C due to extensions.
3809 if (Fn->getType() == Context.OverloadTy) {
3810 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3811
Douglas Gregoree697e62011-10-13 18:10:35 +00003812 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003813 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003814 OverloadExpr *ovl = find.Expression;
3815 if (isa<UnresolvedLookupExpr>(ovl)) {
3816 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3817 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3818 RParenLoc, ExecConfig);
3819 } else {
John McCallaa81e162009-12-01 22:10:20 +00003820 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003821 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003822 }
3823 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003824 }
3825
Douglas Gregorfa047642009-02-04 00:32:51 +00003826 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003827 if (Fn->getType() == Context.UnknownAnyTy) {
3828 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3829 if (result.isInvalid()) return ExprError();
3830 Fn = result.take();
3831 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003832
Eli Friedmanefa42f72009-12-26 03:35:45 +00003833 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003834
John McCall3b4294e2009-12-16 12:17:52 +00003835 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003836 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3837 if (UnOp->getOpcode() == UO_AddrOf)
3838 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3839
John McCall3b4294e2009-12-16 12:17:52 +00003840 if (isa<DeclRefExpr>(NakedFn))
3841 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003842 else if (isa<MemberExpr>(NakedFn))
3843 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003844
Peter Collingbournee08ce652011-02-09 21:07:24 +00003845 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003846 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003847}
3848
3849ExprResult
3850Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003851 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003852 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3853 if (!ConfigDecl)
3854 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3855 << "cudaConfigureCall");
3856 QualType ConfigQTy = ConfigDecl->getType();
3857
3858 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003859 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003860 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003861
Peter Collingbourne1f240762011-10-02 23:49:29 +00003862 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3863 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003864}
3865
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003866/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3867///
3868/// __builtin_astype( value, dst type )
3869///
Richard Trieuccd891a2011-09-09 01:45:06 +00003870ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003871 SourceLocation BuiltinLoc,
3872 SourceLocation RParenLoc) {
3873 ExprValueKind VK = VK_RValue;
3874 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003875 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3876 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003877 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3878 return ExprError(Diag(BuiltinLoc,
3879 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003880 << DstTy
3881 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003882 << E->getSourceRange());
3883 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003884 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003885}
3886
John McCall3b4294e2009-12-16 12:17:52 +00003887/// BuildResolvedCallExpr - Build a call to a resolved expression,
3888/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003889/// unary-convert to an expression of function-pointer or
3890/// block-pointer type.
3891///
3892/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003893ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003894Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3895 SourceLocation LParenLoc,
3896 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003897 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003898 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003899 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3900
Chris Lattner04421082008-04-08 04:40:51 +00003901 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003902 ExprResult Result = UsualUnaryConversions(Fn);
3903 if (Result.isInvalid())
3904 return ExprError();
3905 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003906
Chris Lattner925e60d2007-12-28 05:29:59 +00003907 // Make the call expr early, before semantic checks. This guarantees cleanup
3908 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003909 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00003910 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00003911 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3912 cast<CallExpr>(Config),
3913 Args, NumArgs,
3914 Context.BoolTy,
3915 VK_RValue,
3916 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00003917 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00003918 TheCall = new (Context) CallExpr(Context, Fn,
3919 Args, NumArgs,
3920 Context.BoolTy,
3921 VK_RValue,
3922 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003923
John McCall8e10f3b2011-02-26 05:39:39 +00003924 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3925
3926 // Bail out early if calling a builtin with custom typechecking.
3927 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3928 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3929
John McCall1de4d4e2011-04-07 08:22:57 +00003930 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003931 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003932 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003933 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3934 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003935 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003936 if (FuncT == 0)
3937 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3938 << Fn->getType() << Fn->getSourceRange());
3939 } else if (const BlockPointerType *BPT =
3940 Fn->getType()->getAs<BlockPointerType>()) {
3941 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3942 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003943 // Handle calls to expressions of unknown-any type.
3944 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003945 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003946 if (rewrite.isInvalid()) return ExprError();
3947 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003948 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003949 goto retry;
3950 }
3951
Sebastian Redl0eb23302009-01-19 00:08:26 +00003952 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3953 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003954 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003955
David Blaikie4e4d0842012-03-11 07:00:24 +00003956 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003957 if (Config) {
3958 // CUDA: Kernel calls must be to global functions
3959 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3960 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3961 << FDecl->getName() << Fn->getSourceRange());
3962
3963 // CUDA: Kernel function must have 'void' return type
3964 if (!FuncT->getResultType()->isVoidType())
3965 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3966 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00003967 } else {
3968 // CUDA: Calls to global functions must be configured
3969 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3970 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3971 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003972 }
3973 }
3974
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003975 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003976 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003977 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003978 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003979 return ExprError();
3980
Chris Lattner925e60d2007-12-28 05:29:59 +00003981 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003982 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003983 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003984
Douglas Gregor72564e72009-02-26 23:50:07 +00003985 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003986 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003987 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003988 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003989 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003990 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003991
Douglas Gregor74734d52009-04-02 15:37:10 +00003992 if (FDecl) {
3993 // Check if we have too few/too many template arguments, based
3994 // on our knowledge of the function definition.
3995 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003996 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003997 const FunctionProtoType *Proto
3998 = Def->getType()->getAs<FunctionProtoType>();
3999 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004000 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4001 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004002 }
Douglas Gregor46542412010-10-25 20:39:23 +00004003
4004 // If the function we're calling isn't a function prototype, but we have
4005 // a function prototype from a prior declaratiom, use that prototype.
4006 if (!FDecl->hasPrototype())
4007 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004008 }
4009
Steve Naroffb291ab62007-08-28 23:30:39 +00004010 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004011 for (unsigned i = 0; i != NumArgs; i++) {
4012 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004013
4014 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004015 InitializedEntity Entity
4016 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004017 Proto->getArgType(i),
4018 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004019 ExprResult ArgE = PerformCopyInitialization(Entity,
4020 SourceLocation(),
4021 Owned(Arg));
4022 if (ArgE.isInvalid())
4023 return true;
4024
4025 Arg = ArgE.takeAs<Expr>();
4026
4027 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004028 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4029
4030 if (ArgE.isInvalid())
4031 return true;
4032
4033 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004034 }
4035
Daniel Dunbar96a00142012-03-09 18:35:03 +00004036 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004037 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004038 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004039 return ExprError();
4040
Chris Lattner925e60d2007-12-28 05:29:59 +00004041 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004042 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004043 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004044
Douglas Gregor88a35142008-12-22 05:46:06 +00004045 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4046 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004047 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4048 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004049
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004050 // Check for sentinels
4051 if (NDecl)
4052 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Chris Lattner59907c42007-08-10 20:18:51 +00004054 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004055 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004056 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004057 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004058
John McCall8e10f3b2011-02-26 05:39:39 +00004059 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004060 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004061 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004062 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004063 return ExprError();
4064 }
Chris Lattner59907c42007-08-10 20:18:51 +00004065
John McCall9ae2f072010-08-23 23:25:46 +00004066 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004067}
4068
John McCall60d7b3a2010-08-24 06:29:42 +00004069ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004070Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004071 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004072 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004073 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004074 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004075
4076 TypeSourceInfo *TInfo;
4077 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4078 if (!TInfo)
4079 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4080
John McCall9ae2f072010-08-23 23:25:46 +00004081 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004082}
4083
John McCall60d7b3a2010-08-24 06:29:42 +00004084ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004085Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004086 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004087 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004088
Eli Friedman6223c222008-05-20 05:22:08 +00004089 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004090 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004091 diag::err_illegal_decl_array_incomplete_type,
4092 SourceRange(LParenLoc,
4093 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004094 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004095 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004096 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004097 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004098 } else if (!literalType->isDependentType() &&
4099 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004100 diag::err_typecheck_decl_incomplete_type,
4101 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004102 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004103
Douglas Gregor99a2e602009-12-16 01:38:02 +00004104 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004105 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004106 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004107 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004108 SourceRange(LParenLoc, RParenLoc),
4109 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004110 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004111 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuccd891a2011-09-09 01:45:06 +00004112 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004113 &literalType);
4114 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004115 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004116 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004117
Chris Lattner371f2582008-12-04 23:50:19 +00004118 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004119 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004120 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004121 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004122 }
Eli Friedman08544622009-12-22 02:35:53 +00004123
John McCallf89e55a2010-11-18 06:31:45 +00004124 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004125 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004126
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004127 return MaybeBindToTemporary(
4128 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004129 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004130}
4131
John McCall60d7b3a2010-08-24 06:29:42 +00004132ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004133Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004134 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004135 unsigned NumInit = InitArgList.size();
4136 Expr **InitList = InitArgList.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004137
John McCall3c3b7f92011-10-25 17:37:35 +00004138 // Immediately handle non-overload placeholders. Overloads can be
4139 // resolved contextually, but everything else here can't.
4140 for (unsigned I = 0; I != NumInit; ++I) {
John McCall32509f12011-11-15 01:35:18 +00004141 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00004142 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4143
4144 // Ignore failures; dropping the entire initializer list because
4145 // of one failure would be terrible for indexing/etc.
4146 if (result.isInvalid()) continue;
4147
4148 InitList[I] = result.take();
4149 }
4150 }
4151
Steve Naroff08d92e42007-09-15 18:49:24 +00004152 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004153 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004154
Ted Kremenek709210f2010-04-13 23:39:13 +00004155 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4156 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004157 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004158 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004159}
4160
John McCalldc05b112011-09-10 01:16:55 +00004161/// Do an explicit extend of the given block pointer if we're in ARC.
4162static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4163 assert(E.get()->getType()->isBlockPointerType());
4164 assert(E.get()->isRValue());
4165
4166 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004167 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004168
4169 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004170 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004171 /*base path*/ 0, VK_RValue);
4172 S.ExprNeedsCleanups = true;
4173}
4174
4175/// Prepare a conversion of the given expression to an ObjC object
4176/// pointer type.
4177CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4178 QualType type = E.get()->getType();
4179 if (type->isObjCObjectPointerType()) {
4180 return CK_BitCast;
4181 } else if (type->isBlockPointerType()) {
4182 maybeExtendBlockObject(*this, E);
4183 return CK_BlockPointerToObjCPointerCast;
4184 } else {
4185 assert(type->isPointerType());
4186 return CK_CPointerToObjCPointerCast;
4187 }
4188}
4189
John McCallf3ea8cf2010-11-14 08:17:51 +00004190/// Prepares for a scalar cast, performing all the necessary stages
4191/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004192CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004193 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4194 // Also, callers should have filtered out the invalid cases with
4195 // pointers. Everything else should be possible.
4196
John Wiegley429bb272011-04-08 18:41:53 +00004197 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004198 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004199 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004200
John McCall1d9b3b22011-09-09 05:25:32 +00004201 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004202 case Type::STK_MemberPointer:
4203 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004204
John McCall1d9b3b22011-09-09 05:25:32 +00004205 case Type::STK_CPointer:
4206 case Type::STK_BlockPointer:
4207 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004208 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004209 case Type::STK_CPointer:
4210 return CK_BitCast;
4211 case Type::STK_BlockPointer:
4212 return (SrcKind == Type::STK_BlockPointer
4213 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4214 case Type::STK_ObjCObjectPointer:
4215 if (SrcKind == Type::STK_ObjCObjectPointer)
4216 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004217 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004218 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004219 maybeExtendBlockObject(*this, Src);
4220 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004221 case Type::STK_Bool:
4222 return CK_PointerToBoolean;
4223 case Type::STK_Integral:
4224 return CK_PointerToIntegral;
4225 case Type::STK_Floating:
4226 case Type::STK_FloatingComplex:
4227 case Type::STK_IntegralComplex:
4228 case Type::STK_MemberPointer:
4229 llvm_unreachable("illegal cast from pointer");
4230 }
David Blaikie7530c032012-01-17 06:56:22 +00004231 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004232
John McCalldaa8e4e2010-11-15 09:13:47 +00004233 case Type::STK_Bool: // casting from bool is like casting from an integer
4234 case Type::STK_Integral:
4235 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004236 case Type::STK_CPointer:
4237 case Type::STK_ObjCObjectPointer:
4238 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004239 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004240 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004241 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004242 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004243 case Type::STK_Bool:
4244 return CK_IntegralToBoolean;
4245 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004246 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004247 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004248 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004249 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004250 Src = ImpCastExprToType(Src.take(),
4251 DestTy->castAs<ComplexType>()->getElementType(),
4252 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004253 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004254 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004255 Src = ImpCastExprToType(Src.take(),
4256 DestTy->castAs<ComplexType>()->getElementType(),
4257 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004258 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004259 case Type::STK_MemberPointer:
4260 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004261 }
David Blaikie7530c032012-01-17 06:56:22 +00004262 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004263
John McCalldaa8e4e2010-11-15 09:13:47 +00004264 case Type::STK_Floating:
4265 switch (DestTy->getScalarTypeKind()) {
4266 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004267 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004268 case Type::STK_Bool:
4269 return CK_FloatingToBoolean;
4270 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004271 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004272 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004273 Src = ImpCastExprToType(Src.take(),
4274 DestTy->castAs<ComplexType>()->getElementType(),
4275 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004276 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004277 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004278 Src = ImpCastExprToType(Src.take(),
4279 DestTy->castAs<ComplexType>()->getElementType(),
4280 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004281 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004282 case Type::STK_CPointer:
4283 case Type::STK_ObjCObjectPointer:
4284 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004285 llvm_unreachable("valid float->pointer cast?");
4286 case Type::STK_MemberPointer:
4287 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004288 }
David Blaikie7530c032012-01-17 06:56:22 +00004289 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004290
John McCalldaa8e4e2010-11-15 09:13:47 +00004291 case Type::STK_FloatingComplex:
4292 switch (DestTy->getScalarTypeKind()) {
4293 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004294 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004295 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004296 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004297 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004298 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4299 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004300 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004301 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004302 return CK_FloatingCast;
4303 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004304 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004305 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004306 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004307 Src = ImpCastExprToType(Src.take(),
4308 SrcTy->castAs<ComplexType>()->getElementType(),
4309 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004310 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004311 case Type::STK_CPointer:
4312 case Type::STK_ObjCObjectPointer:
4313 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004314 llvm_unreachable("valid complex float->pointer cast?");
4315 case Type::STK_MemberPointer:
4316 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004317 }
David Blaikie7530c032012-01-17 06:56:22 +00004318 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004319
John McCalldaa8e4e2010-11-15 09:13:47 +00004320 case Type::STK_IntegralComplex:
4321 switch (DestTy->getScalarTypeKind()) {
4322 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004323 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004324 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004325 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004326 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004327 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4328 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004329 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004330 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004331 return CK_IntegralCast;
4332 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004333 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004334 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004335 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004336 Src = ImpCastExprToType(Src.take(),
4337 SrcTy->castAs<ComplexType>()->getElementType(),
4338 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004339 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004340 case Type::STK_CPointer:
4341 case Type::STK_ObjCObjectPointer:
4342 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004343 llvm_unreachable("valid complex int->pointer cast?");
4344 case Type::STK_MemberPointer:
4345 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004346 }
David Blaikie7530c032012-01-17 06:56:22 +00004347 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004348 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004349
John McCallf3ea8cf2010-11-14 08:17:51 +00004350 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004351}
4352
Anders Carlssonc3516322009-10-16 02:48:28 +00004353bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004354 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004355 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004356
Anders Carlssona64db8f2007-11-27 05:51:55 +00004357 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004358 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004359 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004360 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004361 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004362 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004363 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004364 } else
4365 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004366 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004367 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004368
John McCall2de56d12010-08-25 11:45:40 +00004369 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004370 return false;
4371}
4372
John Wiegley429bb272011-04-08 18:41:53 +00004373ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4374 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004375 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004376
Anders Carlsson16a89042009-10-16 05:23:41 +00004377 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004378
Nate Begeman9b10da62009-06-27 22:05:55 +00004379 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4380 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004381 // In OpenCL, casts between vectors of different types are not allowed.
4382 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004383 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004384 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004385 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004386 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004387 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004388 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004389 return ExprError();
4390 }
John McCall2de56d12010-08-25 11:45:40 +00004391 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004392 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004393 }
4394
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004395 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004396 // conversion will take place first from scalar to elt type, and then
4397 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004398 if (SrcTy->isPointerType())
4399 return Diag(R.getBegin(),
4400 diag::err_invalid_conversion_between_vector_and_scalar)
4401 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004402
4403 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004404 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004405 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004406 if (CastExprRes.isInvalid())
4407 return ExprError();
4408 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004409
John McCall2de56d12010-08-25 11:45:40 +00004410 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004411 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004412}
4413
John McCall60d7b3a2010-08-24 06:29:42 +00004414ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004415Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4416 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004417 SourceLocation RParenLoc, Expr *CastExpr) {
4418 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004419 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004420
Richard Trieuccd891a2011-09-09 01:45:06 +00004421 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004422 if (D.isInvalidType())
4423 return ExprError();
4424
David Blaikie4e4d0842012-03-11 07:00:24 +00004425 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004426 // Check that there are no default arguments (C++ only).
4427 CheckExtraCXXDefaultArguments(D);
4428 }
4429
John McCalle82247a2011-10-01 05:17:03 +00004430 checkUnusedDeclAttributes(D);
4431
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004432 QualType castType = castTInfo->getType();
4433 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004434
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004435 bool isVectorLiteral = false;
4436
4437 // Check for an altivec or OpenCL literal,
4438 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004439 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4440 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004441 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004442 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004443 if (PLE && PLE->getNumExprs() == 0) {
4444 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4445 return ExprError();
4446 }
4447 if (PE || PLE->getNumExprs() == 1) {
4448 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4449 if (!E->getType()->isVectorType())
4450 isVectorLiteral = true;
4451 }
4452 else
4453 isVectorLiteral = true;
4454 }
4455
4456 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4457 // then handle it as such.
4458 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004459 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004460
Nate Begeman2ef13e52009-08-10 23:49:36 +00004461 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004462 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4463 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004464 if (isa<ParenListExpr>(CastExpr)) {
4465 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004466 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004467 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004468 }
John McCallb042fdf2010-01-15 18:56:44 +00004469
Richard Trieuccd891a2011-09-09 01:45:06 +00004470 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004471}
4472
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004473ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4474 SourceLocation RParenLoc, Expr *E,
4475 TypeSourceInfo *TInfo) {
4476 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4477 "Expected paren or paren list expression");
4478
4479 Expr **exprs;
4480 unsigned numExprs;
4481 Expr *subExpr;
4482 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4483 exprs = PE->getExprs();
4484 numExprs = PE->getNumExprs();
4485 } else {
4486 subExpr = cast<ParenExpr>(E)->getSubExpr();
4487 exprs = &subExpr;
4488 numExprs = 1;
4489 }
4490
4491 QualType Ty = TInfo->getType();
4492 assert(Ty->isVectorType() && "Expected vector type");
4493
Chris Lattner5f9e2722011-07-23 10:55:15 +00004494 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004495 const VectorType *VTy = Ty->getAs<VectorType>();
4496 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4497
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004498 // '(...)' form of vector initialization in AltiVec: the number of
4499 // initializers must be one or must match the size of the vector.
4500 // If a single value is specified in the initializer then it will be
4501 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004502 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004503 // The number of initializers must be one or must match the size of the
4504 // vector. If a single value is specified in the initializer then it will
4505 // be replicated to all the components of the vector
4506 if (numExprs == 1) {
4507 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004508 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4509 if (Literal.isInvalid())
4510 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004511 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004512 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004513 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4514 }
4515 else if (numExprs < numElems) {
4516 Diag(E->getExprLoc(),
4517 diag::err_incorrect_number_of_vector_initializers);
4518 return ExprError();
4519 }
4520 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004521 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004522 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004523 else {
4524 // For OpenCL, when the number of initializers is a single value,
4525 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004526 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004527 VTy->getVectorKind() == VectorType::GenericVector &&
4528 numExprs == 1) {
4529 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004530 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4531 if (Literal.isInvalid())
4532 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004533 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004534 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004535 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4536 }
4537
Benjamin Kramer14c59822012-02-14 12:06:21 +00004538 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004539 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004540 // FIXME: This means that pretty-printing the final AST will produce curly
4541 // braces instead of the original commas.
4542 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4543 &initExprs[0],
4544 initExprs.size(), RParenLoc);
4545 initE->setType(Ty);
4546 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4547}
4548
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004549/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4550/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004551ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004552Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4553 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004554 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004555 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004556
John McCall60d7b3a2010-08-24 06:29:42 +00004557 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004558
Nate Begeman2ef13e52009-08-10 23:49:36 +00004559 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004560 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4561 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004562
John McCall9ae2f072010-08-23 23:25:46 +00004563 if (Result.isInvalid()) return ExprError();
4564
4565 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004566}
4567
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004568ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4569 SourceLocation R,
4570 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004571 unsigned nexprs = Val.size();
4572 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004573 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004574 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004575 return Owned(expr);
4576}
4577
Chandler Carruth82214a82011-02-18 23:54:50 +00004578/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004579/// constant and the other is not a pointer. Returns true if a diagnostic is
4580/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004581bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004582 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004583 Expr *NullExpr = LHSExpr;
4584 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004585 Expr::NullPointerConstantKind NullKind =
4586 NullExpr->isNullPointerConstant(Context,
4587 Expr::NPC_ValueDependentIsNotNull);
4588
4589 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004590 NullExpr = RHSExpr;
4591 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004592 NullKind =
4593 NullExpr->isNullPointerConstant(Context,
4594 Expr::NPC_ValueDependentIsNotNull);
4595 }
4596
4597 if (NullKind == Expr::NPCK_NotNull)
4598 return false;
4599
4600 if (NullKind == Expr::NPCK_ZeroInteger) {
4601 // In this case, check to make sure that we got here from a "NULL"
4602 // string in the source code.
4603 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004604 SourceLocation loc = NullExpr->getExprLoc();
4605 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004606 return false;
4607 }
4608
4609 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4610 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4611 << NonPointerExpr->getType() << DiagType
4612 << NonPointerExpr->getSourceRange();
4613 return true;
4614}
4615
Richard Trieu26f96072011-09-02 01:51:02 +00004616/// \brief Return false if the condition expression is valid, true otherwise.
4617static bool checkCondition(Sema &S, Expr *Cond) {
4618 QualType CondTy = Cond->getType();
4619
4620 // C99 6.5.15p2
4621 if (CondTy->isScalarType()) return false;
4622
4623 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004624 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004625 return false;
4626
4627 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004628 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004629 diag::err_typecheck_cond_expect_scalar :
4630 diag::err_typecheck_cond_expect_scalar_or_vector)
4631 << CondTy;
4632 return true;
4633}
4634
4635/// \brief Return false if the two expressions can be converted to a vector,
4636/// true otherwise
4637static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4638 ExprResult &RHS,
4639 QualType CondTy) {
4640 // Both operands should be of scalar type.
4641 if (!LHS.get()->getType()->isScalarType()) {
4642 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4643 << CondTy;
4644 return true;
4645 }
4646 if (!RHS.get()->getType()->isScalarType()) {
4647 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4648 << CondTy;
4649 return true;
4650 }
4651
4652 // Implicity convert these scalars to the type of the condition.
4653 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4654 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4655 return false;
4656}
4657
4658/// \brief Handle when one or both operands are void type.
4659static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4660 ExprResult &RHS) {
4661 Expr *LHSExpr = LHS.get();
4662 Expr *RHSExpr = RHS.get();
4663
4664 if (!LHSExpr->getType()->isVoidType())
4665 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4666 << RHSExpr->getSourceRange();
4667 if (!RHSExpr->getType()->isVoidType())
4668 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4669 << LHSExpr->getSourceRange();
4670 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4671 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4672 return S.Context.VoidTy;
4673}
4674
4675/// \brief Return false if the NullExpr can be promoted to PointerTy,
4676/// true otherwise.
4677static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4678 QualType PointerTy) {
4679 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4680 !NullExpr.get()->isNullPointerConstant(S.Context,
4681 Expr::NPC_ValueDependentIsNull))
4682 return true;
4683
4684 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4685 return false;
4686}
4687
4688/// \brief Checks compatibility between two pointers and return the resulting
4689/// type.
4690static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4691 ExprResult &RHS,
4692 SourceLocation Loc) {
4693 QualType LHSTy = LHS.get()->getType();
4694 QualType RHSTy = RHS.get()->getType();
4695
4696 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4697 // Two identical pointers types are always compatible.
4698 return LHSTy;
4699 }
4700
4701 QualType lhptee, rhptee;
4702
4703 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004704 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4705 lhptee = LHSBTy->getPointeeType();
4706 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004707 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004708 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4709 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004710 }
4711
Eli Friedmanae916a12012-04-05 22:30:04 +00004712 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4713 // differently qualified versions of compatible types, the result type is
4714 // a pointer to an appropriately qualified version of the composite
4715 // type.
4716
4717 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4718 // clause doesn't make sense for our extensions. E.g. address space 2 should
4719 // be incompatible with address space 3: they may live on different devices or
4720 // anything.
4721 Qualifiers lhQual = lhptee.getQualifiers();
4722 Qualifiers rhQual = rhptee.getQualifiers();
4723
4724 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4725 lhQual.removeCVRQualifiers();
4726 rhQual.removeCVRQualifiers();
4727
4728 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4729 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4730
4731 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4732
4733 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004734 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4735 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4736 << RHS.get()->getSourceRange();
4737 // In this situation, we assume void* type. No especially good
4738 // reason, but this is what gcc does, and we do have to pick
4739 // to get a consistent AST.
4740 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4741 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4742 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4743 return incompatTy;
4744 }
4745
4746 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004747 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4748 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004749
Eli Friedmanae916a12012-04-05 22:30:04 +00004750 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4751 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4752 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004753}
4754
4755/// \brief Return the resulting type when the operands are both block pointers.
4756static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4757 ExprResult &LHS,
4758 ExprResult &RHS,
4759 SourceLocation Loc) {
4760 QualType LHSTy = LHS.get()->getType();
4761 QualType RHSTy = RHS.get()->getType();
4762
4763 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4764 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4765 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4766 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4767 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4768 return destType;
4769 }
4770 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4771 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4772 << RHS.get()->getSourceRange();
4773 return QualType();
4774 }
4775
4776 // We have 2 block pointer types.
4777 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4778}
4779
4780/// \brief Return the resulting type when the operands are both pointers.
4781static QualType
4782checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4783 ExprResult &RHS,
4784 SourceLocation Loc) {
4785 // get the pointer types
4786 QualType LHSTy = LHS.get()->getType();
4787 QualType RHSTy = RHS.get()->getType();
4788
4789 // get the "pointed to" types
4790 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4791 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4792
4793 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4794 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4795 // Figure out necessary qualifiers (C99 6.5.15p6)
4796 QualType destPointee
4797 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4798 QualType destType = S.Context.getPointerType(destPointee);
4799 // Add qualifiers if necessary.
4800 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4801 // Promote to void*.
4802 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4803 return destType;
4804 }
4805 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4806 QualType destPointee
4807 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4808 QualType destType = S.Context.getPointerType(destPointee);
4809 // Add qualifiers if necessary.
4810 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4811 // Promote to void*.
4812 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4813 return destType;
4814 }
4815
4816 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4817}
4818
4819/// \brief Return false if the first expression is not an integer and the second
4820/// expression is not a pointer, true otherwise.
4821static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4822 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004823 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004824 if (!PointerExpr->getType()->isPointerType() ||
4825 !Int.get()->getType()->isIntegerType())
4826 return false;
4827
Richard Trieuccd891a2011-09-09 01:45:06 +00004828 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4829 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004830
4831 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4832 << Expr1->getType() << Expr2->getType()
4833 << Expr1->getSourceRange() << Expr2->getSourceRange();
4834 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4835 CK_IntegralToPointer);
4836 return true;
4837}
4838
Richard Trieu33fc7572011-09-06 20:06:39 +00004839/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4840/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004841/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004842QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4843 ExprResult &RHS, ExprValueKind &VK,
4844 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004845 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004846
Richard Trieu33fc7572011-09-06 20:06:39 +00004847 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4848 if (!LHSResult.isUsable()) return QualType();
4849 LHS = move(LHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004850
Richard Trieu33fc7572011-09-06 20:06:39 +00004851 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4852 if (!RHSResult.isUsable()) return QualType();
4853 RHS = move(RHSResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004854
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004855 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004856 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004857 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004858
4859 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004860 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004861
John Wiegley429bb272011-04-08 18:41:53 +00004862 Cond = UsualUnaryConversions(Cond.take());
4863 if (Cond.isInvalid())
4864 return QualType();
4865 LHS = UsualUnaryConversions(LHS.take());
4866 if (LHS.isInvalid())
4867 return QualType();
4868 RHS = UsualUnaryConversions(RHS.take());
4869 if (RHS.isInvalid())
4870 return QualType();
4871
4872 QualType CondTy = Cond.get()->getType();
4873 QualType LHSTy = LHS.get()->getType();
4874 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004875
Reid Spencer5f016e22007-07-11 17:01:13 +00004876 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004877 if (checkCondition(*this, Cond.get()))
4878 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004879
Chris Lattner70d67a92008-01-06 22:42:25 +00004880 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004881 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004882 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004883
Nate Begeman6155d732010-09-20 22:41:17 +00004884 // OpenCL: If the condition is a vector, and both operands are scalar,
4885 // attempt to implicity convert them to the vector type to act like the
4886 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004887 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004888 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004889 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004890
Chris Lattner70d67a92008-01-06 22:42:25 +00004891 // If both operands have arithmetic type, do the usual arithmetic conversions
4892 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004893 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4894 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004895 if (LHS.isInvalid() || RHS.isInvalid())
4896 return QualType();
4897 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004898 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004899
Chris Lattner70d67a92008-01-06 22:42:25 +00004900 // If both operands are the same structure or union type, the result is that
4901 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004902 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4903 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004904 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004905 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004906 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004907 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004908 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004909 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004910
Chris Lattner70d67a92008-01-06 22:42:25 +00004911 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004912 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004913 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004914 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004915 }
Richard Trieu26f96072011-09-02 01:51:02 +00004916
Steve Naroffb6d54e52008-01-08 01:11:38 +00004917 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4918 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004919 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4920 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004921
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004922 // All objective-c pointer type analysis is done here.
4923 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4924 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004925 if (LHS.isInvalid() || RHS.isInvalid())
4926 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004927 if (!compositeType.isNull())
4928 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004929
4930
Steve Naroff7154a772009-07-01 14:36:47 +00004931 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004932 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4933 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4934 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004935
Steve Naroff7154a772009-07-01 14:36:47 +00004936 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004937 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4938 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4939 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004940
John McCall404cd162010-11-13 01:35:44 +00004941 // GCC compatibility: soften pointer/integer mismatch. Note that
4942 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004943 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4944 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004945 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004946 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4947 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004948 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004949
Chandler Carruth82214a82011-02-18 23:54:50 +00004950 // Emit a better diagnostic if one of the expressions is a null pointer
4951 // constant and the other is not a pointer type. In this case, the user most
4952 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004953 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004954 return QualType();
4955
Chris Lattner70d67a92008-01-06 22:42:25 +00004956 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004957 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004958 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4959 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004960 return QualType();
4961}
4962
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004963/// FindCompositeObjCPointerType - Helper method to find composite type of
4964/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004965QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004966 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004967 QualType LHSTy = LHS.get()->getType();
4968 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004969
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004970 // Handle things like Class and struct objc_class*. Here we case the result
4971 // to the pseudo-builtin, because that will be implicitly cast back to the
4972 // redefinition type if an attempt is made to access its fields.
4973 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004974 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004975 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004976 return LHSTy;
4977 }
4978 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004979 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004980 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004981 return RHSTy;
4982 }
4983 // And the same for struct objc_object* / id
4984 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004985 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004986 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004987 return LHSTy;
4988 }
4989 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004990 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00004991 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004992 return RHSTy;
4993 }
4994 // And the same for struct objc_selector* / SEL
4995 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00004996 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004997 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004998 return LHSTy;
4999 }
5000 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005001 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005002 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005003 return RHSTy;
5004 }
5005 // Check constraints for Objective-C object pointers types.
5006 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005007
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005008 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5009 // Two identical object pointer types are always compatible.
5010 return LHSTy;
5011 }
John McCall1d9b3b22011-09-09 05:25:32 +00005012 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5013 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005014 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005015
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005016 // If both operands are interfaces and either operand can be
5017 // assigned to the other, use that type as the composite
5018 // type. This allows
5019 // xxx ? (A*) a : (B*) b
5020 // where B is a subclass of A.
5021 //
5022 // Additionally, as for assignment, if either type is 'id'
5023 // allow silent coercion. Finally, if the types are
5024 // incompatible then make sure to use 'id' as the composite
5025 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005026
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005027 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5028 // It could return the composite type.
5029 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5030 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5031 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5032 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5033 } else if ((LHSTy->isObjCQualifiedIdType() ||
5034 RHSTy->isObjCQualifiedIdType()) &&
5035 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5036 // Need to handle "id<xx>" explicitly.
5037 // GCC allows qualified id and any Objective-C type to devolve to
5038 // id. Currently localizing to here until clear this should be
5039 // part of ObjCQualifiedIdTypesAreCompatible.
5040 compositeType = Context.getObjCIdType();
5041 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5042 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005043 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005044 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5045 ;
5046 else {
5047 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5048 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005049 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005050 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005051 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5052 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005053 return incompatTy;
5054 }
5055 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005056 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5057 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005058 return compositeType;
5059 }
5060 // Check Objective-C object pointer types and 'void *'
5061 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005062 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005063 // ARC forbids the implicit conversion of object pointers to 'void *',
5064 // so these types are not compatible.
5065 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5066 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5067 LHS = RHS = true;
5068 return QualType();
5069 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005070 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5071 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5072 QualType destPointee
5073 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5074 QualType destType = Context.getPointerType(destPointee);
5075 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005076 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005077 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005078 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005079 return destType;
5080 }
5081 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005082 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005083 // ARC forbids the implicit conversion of object pointers to 'void *',
5084 // so these types are not compatible.
5085 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5086 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5087 LHS = RHS = true;
5088 return QualType();
5089 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005090 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5091 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5092 QualType destPointee
5093 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5094 QualType destType = Context.getPointerType(destPointee);
5095 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005096 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005097 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005098 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005099 return destType;
5100 }
5101 return QualType();
5102}
5103
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005104/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005105/// ParenRange in parentheses.
5106static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005107 const PartialDiagnostic &Note,
5108 SourceRange ParenRange) {
5109 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5110 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5111 EndLoc.isValid()) {
5112 Self.Diag(Loc, Note)
5113 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5114 << FixItHint::CreateInsertion(EndLoc, ")");
5115 } else {
5116 // We can't display the parentheses, so just show the bare note.
5117 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005118 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005119}
5120
5121static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5122 return Opc >= BO_Mul && Opc <= BO_Shr;
5123}
5124
Hans Wennborg2f072b42011-06-09 17:06:51 +00005125/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5126/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005127/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5128/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005129static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005130 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005131 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5132 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005133 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005134 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005135
5136 // Built-in binary operator.
5137 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5138 if (IsArithmeticOp(OP->getOpcode())) {
5139 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005140 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005141 return true;
5142 }
5143 }
5144
5145 // Overloaded operator.
5146 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5147 if (Call->getNumArgs() != 2)
5148 return false;
5149
5150 // Make sure this is really a binary operator that is safe to pass into
5151 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5152 OverloadedOperatorKind OO = Call->getOperator();
5153 if (OO < OO_Plus || OO > OO_Arrow)
5154 return false;
5155
5156 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5157 if (IsArithmeticOp(OpKind)) {
5158 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005159 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005160 return true;
5161 }
5162 }
5163
5164 return false;
5165}
5166
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005167static bool IsLogicOp(BinaryOperatorKind Opc) {
5168 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5169}
5170
Hans Wennborg2f072b42011-06-09 17:06:51 +00005171/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5172/// or is a logical expression such as (x==y) which has int type, but is
5173/// commonly interpreted as boolean.
5174static bool ExprLooksBoolean(Expr *E) {
5175 E = E->IgnoreParenImpCasts();
5176
5177 if (E->getType()->isBooleanType())
5178 return true;
5179 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5180 return IsLogicOp(OP->getOpcode());
5181 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5182 return OP->getOpcode() == UO_LNot;
5183
5184 return false;
5185}
5186
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005187/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5188/// and binary operator are mixed in a way that suggests the programmer assumed
5189/// the conditional operator has higher precedence, for example:
5190/// "int x = a + someBinaryCondition ? 1 : 2".
5191static void DiagnoseConditionalPrecedence(Sema &Self,
5192 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005193 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005194 Expr *LHSExpr,
5195 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005196 BinaryOperatorKind CondOpcode;
5197 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005198
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005199 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005200 return;
5201 if (!ExprLooksBoolean(CondRHS))
5202 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005203
Hans Wennborg2f072b42011-06-09 17:06:51 +00005204 // The condition is an arithmetic binary expression, with a right-
5205 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005206
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005207 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005208 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005209 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005210
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005211 SuggestParentheses(Self, OpLoc,
5212 Self.PDiag(diag::note_precedence_conditional_silence)
5213 << BinaryOperator::getOpcodeStr(CondOpcode),
5214 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005215
5216 SuggestParentheses(Self, OpLoc,
5217 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005218 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005219}
5220
Steve Narofff69936d2007-09-16 03:34:24 +00005221/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005222/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005223ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005224 SourceLocation ColonLoc,
5225 Expr *CondExpr, Expr *LHSExpr,
5226 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005227 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5228 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005229 OpaqueValueExpr *opaqueValue = 0;
5230 Expr *commonExpr = 0;
5231 if (LHSExpr == 0) {
5232 commonExpr = CondExpr;
5233
5234 // We usually want to apply unary conversions *before* saving, except
5235 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005236 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005237 && !commonExpr->isTypeDependent()
5238 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5239 && commonExpr->isGLValue()
5240 && commonExpr->isOrdinaryOrBitFieldObject()
5241 && RHSExpr->isOrdinaryOrBitFieldObject()
5242 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005243 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5244 if (commonRes.isInvalid())
5245 return ExprError();
5246 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005247 }
5248
5249 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5250 commonExpr->getType(),
5251 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005252 commonExpr->getObjectKind(),
5253 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005254 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005255 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005256
John McCallf89e55a2010-11-18 06:31:45 +00005257 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005258 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005259 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5260 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005261 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005262 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5263 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005264 return ExprError();
5265
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005266 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5267 RHS.get());
5268
John McCall56ca35d2011-02-17 10:25:35 +00005269 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005270 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5271 LHS.take(), ColonLoc,
5272 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005273
5274 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005275 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005276 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5277 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005278}
5279
John McCalle4be87e2011-01-31 23:13:11 +00005280// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005281// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005282// routine is it effectively iqnores the qualifiers on the top level pointee.
5283// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5284// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005285static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005286checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5287 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5288 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005289
Reid Spencer5f016e22007-07-11 17:01:13 +00005290 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005291 const Type *lhptee, *rhptee;
5292 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005293 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5294 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005295
John McCalle4be87e2011-01-31 23:13:11 +00005296 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005297
5298 // C99 6.5.16.1p1: This following citation is common to constraints
5299 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5300 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005301 Qualifiers lq;
5302
John McCallf85e1932011-06-15 23:02:42 +00005303 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5304 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5305 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5306 // Ignore lifetime for further calculation.
5307 lhq.removeObjCLifetime();
5308 rhq.removeObjCLifetime();
5309 }
5310
John McCall86c05f32011-02-01 00:10:29 +00005311 if (!lhq.compatiblyIncludes(rhq)) {
5312 // Treat address-space mismatches as fatal. TODO: address subspaces
5313 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5314 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5315
John McCallf85e1932011-06-15 23:02:42 +00005316 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005317 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005318 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005319 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005320 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005321 && (lhptee->isVoidType() || rhptee->isVoidType()))
5322 ; // keep old
5323
John McCallf85e1932011-06-15 23:02:42 +00005324 // Treat lifetime mismatches as fatal.
5325 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5326 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5327
John McCall86c05f32011-02-01 00:10:29 +00005328 // For GCC compatibility, other qualifier mismatches are treated
5329 // as still compatible in C.
5330 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5331 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005332
Mike Stumpeed9cac2009-02-19 03:04:26 +00005333 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5334 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005335 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005336 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005337 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005338 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005339
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005340 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005341 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005342 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005343 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005344
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005345 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005346 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005347 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005348
5349 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005350 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005351 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005352 }
John McCall86c05f32011-02-01 00:10:29 +00005353
Mike Stumpeed9cac2009-02-19 03:04:26 +00005354 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005355 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005356 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5357 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005358 // Check if the pointee types are compatible ignoring the sign.
5359 // We explicitly check for char so that we catch "char" vs
5360 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005361 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005362 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005363 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005364 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005365
Chris Lattner6a2b9262009-10-17 20:33:28 +00005366 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005367 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005368 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005369 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005370
John McCall86c05f32011-02-01 00:10:29 +00005371 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005372 // Types are compatible ignoring the sign. Qualifier incompatibility
5373 // takes priority over sign incompatibility because the sign
5374 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005375 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005376 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005377
John McCalle4be87e2011-01-31 23:13:11 +00005378 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005379 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005380
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005381 // If we are a multi-level pointer, it's possible that our issue is simply
5382 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5383 // the eventual target type is the same and the pointers have the same
5384 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005385 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005386 do {
John McCall86c05f32011-02-01 00:10:29 +00005387 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5388 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005389 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005390
John McCall86c05f32011-02-01 00:10:29 +00005391 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005392 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005393 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005394
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005395 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005396 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005397 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005398 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005399 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5400 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005401 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005402}
5403
John McCalle4be87e2011-01-31 23:13:11 +00005404/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005405/// block pointer types are compatible or whether a block and normal pointer
5406/// are compatible. It is more restrict than comparing two function pointer
5407// types.
John McCalle4be87e2011-01-31 23:13:11 +00005408static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005409checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5410 QualType RHSType) {
5411 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5412 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005413
Steve Naroff1c7d0672008-09-04 15:10:53 +00005414 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005415
Steve Naroff1c7d0672008-09-04 15:10:53 +00005416 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005417 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5418 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005419
John McCalle4be87e2011-01-31 23:13:11 +00005420 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005421 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005422 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005423
John McCalle4be87e2011-01-31 23:13:11 +00005424 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005425
Steve Naroff1c7d0672008-09-04 15:10:53 +00005426 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005427 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5428 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005429
Richard Trieu1da27a12011-09-06 20:21:22 +00005430 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005431 return Sema::IncompatibleBlockPointer;
5432
Steve Naroff1c7d0672008-09-04 15:10:53 +00005433 return ConvTy;
5434}
5435
John McCalle4be87e2011-01-31 23:13:11 +00005436/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005437/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005438static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005439checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5440 QualType RHSType) {
5441 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5442 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005443
Richard Trieu1da27a12011-09-06 20:21:22 +00005444 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005445 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005446 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5447 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005448 return Sema::IncompatiblePointer;
5449 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005450 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005451 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005452 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5453 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005454 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005455 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005456 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005457 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5458 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005459
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005460 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5461 // make an exception for id<P>
5462 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005463 return Sema::CompatiblePointerDiscardsQualifiers;
5464
Richard Trieu1da27a12011-09-06 20:21:22 +00005465 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005466 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005467 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005468 return Sema::IncompatibleObjCQualifiedId;
5469 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005470}
5471
John McCall1c23e912010-11-16 02:32:08 +00005472Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005473Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005474 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005475 // Fake up an opaque expression. We don't actually care about what
5476 // cast operations are required, so if CheckAssignmentConstraints
5477 // adds casts to this they'll be wasted, but fortunately that doesn't
5478 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005479 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5480 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005481 CastKind K = CK_Invalid;
5482
Richard Trieu1da27a12011-09-06 20:21:22 +00005483 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005484}
5485
Mike Stumpeed9cac2009-02-19 03:04:26 +00005486/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5487/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005488/// pointers. Here are some objectionable examples that GCC considers warnings:
5489///
5490/// int a, *pint;
5491/// short *pshort;
5492/// struct foo *pfoo;
5493///
5494/// pint = pshort; // warning: assignment from incompatible pointer type
5495/// a = pint; // warning: assignment makes integer from pointer without a cast
5496/// pint = a; // warning: assignment makes pointer from integer without a cast
5497/// pint = pfoo; // warning: assignment from incompatible pointer type
5498///
5499/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005500/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005501///
John McCalldaa8e4e2010-11-15 09:13:47 +00005502/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005503Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005504Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005505 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005506 QualType RHSType = RHS.get()->getType();
5507 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005508
Chris Lattnerfc144e22008-01-04 23:18:45 +00005509 // Get canonical types. We're not formatting these types, just comparing
5510 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005511 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5512 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005513
Eli Friedmanb001de72011-10-06 23:00:33 +00005514
John McCallb6cfa242011-01-31 22:28:28 +00005515 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005516 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005517 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005518 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005519 }
5520
Eli Friedman860a3192012-06-16 02:19:17 +00005521 // If we have an atomic type, try a non-atomic assignment, then just add an
5522 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005523 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005524 Sema::AssignConvertType result =
5525 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5526 if (result != Compatible)
5527 return result;
5528 if (Kind != CK_NoOp)
5529 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5530 Kind = CK_NonAtomicToAtomic;
5531 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005532 }
5533
Douglas Gregor9d293df2008-10-28 00:22:11 +00005534 // If the left-hand side is a reference type, then we are in a
5535 // (rare!) case where we've allowed the use of references in C,
5536 // e.g., as a parameter type in a built-in function. In this case,
5537 // just make sure that the type referenced is compatible with the
5538 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005539 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005540 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005541 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5542 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005543 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005544 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005545 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005546 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005547 }
John McCallb6cfa242011-01-31 22:28:28 +00005548
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005549 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5550 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005551 if (LHSType->isExtVectorType()) {
5552 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005553 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005554 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005555 // CK_VectorSplat does T -> vector T, so first cast to the
5556 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005557 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5558 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005559 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005560 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005561 }
5562 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005563 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005564 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005565 }
Mike Stump1eb44332009-09-09 15:08:12 +00005566
John McCallb6cfa242011-01-31 22:28:28 +00005567 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005568 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5569 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005570 // Allow assignments of an AltiVec vector type to an equivalent GCC
5571 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005572 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005573 Kind = CK_BitCast;
5574 return Compatible;
5575 }
5576
Douglas Gregor255210e2010-08-06 10:14:59 +00005577 // If we are allowing lax vector conversions, and LHS and RHS are both
5578 // vectors, the total size only needs to be the same. This is a bitcast;
5579 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005580 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005581 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005582 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005583 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005584 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005585 }
5586 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005587 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005588
John McCallb6cfa242011-01-31 22:28:28 +00005589 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005590 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005591 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005592 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005593 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005594 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005595
John McCallb6cfa242011-01-31 22:28:28 +00005596 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005597 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005598 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005599 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005600 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005601 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005602 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005603
John McCallb6cfa242011-01-31 22:28:28 +00005604 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005605 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005606 Kind = CK_IntegralToPointer; // FIXME: null?
5607 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005608 }
John McCallb6cfa242011-01-31 22:28:28 +00005609
5610 // C pointers are not compatible with ObjC object pointers,
5611 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005612 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005613 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005614 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005615 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005616 return Compatible;
5617 }
5618
5619 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005620 if (RHSType->isObjCClassType() &&
5621 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005622 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005623 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005624 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005625 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005626
John McCallb6cfa242011-01-31 22:28:28 +00005627 Kind = CK_BitCast;
5628 return IncompatiblePointer;
5629 }
5630
5631 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005632 if (RHSType->getAs<BlockPointerType>()) {
5633 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005634 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005635 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005636 }
Steve Naroffb4406862008-09-29 18:10:17 +00005637 }
John McCallb6cfa242011-01-31 22:28:28 +00005638
Steve Naroff1c7d0672008-09-04 15:10:53 +00005639 return Incompatible;
5640 }
5641
John McCallb6cfa242011-01-31 22:28:28 +00005642 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005643 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005644 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005645 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005646 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005647 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005648 }
5649
5650 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005651 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005652 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005653 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005654 }
5655
John McCallb6cfa242011-01-31 22:28:28 +00005656 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005657 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005658 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005659 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005660 }
Steve Naroffb4406862008-09-29 18:10:17 +00005661
John McCallb6cfa242011-01-31 22:28:28 +00005662 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005663 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005664 if (RHSPT->getPointeeType()->isVoidType()) {
5665 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005666 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005667 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005668
Chris Lattnerfc144e22008-01-04 23:18:45 +00005669 return Incompatible;
5670 }
5671
John McCallb6cfa242011-01-31 22:28:28 +00005672 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005673 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005674 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005675 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005676 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005677 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005678 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005679 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005680 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005681 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005682 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005683 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005684 }
5685
5686 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005687 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005688 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005689 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005690 }
5691
John McCallb6cfa242011-01-31 22:28:28 +00005692 // In general, C pointers are not compatible with ObjC object pointers,
5693 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005694 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005695 Kind = CK_CPointerToObjCPointerCast;
5696
John McCallb6cfa242011-01-31 22:28:28 +00005697 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005698 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005699 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005700 }
5701
5702 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005703 if (LHSType->isObjCClassType() &&
5704 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005705 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005706 return Compatible;
5707 }
5708
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005709 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005710 }
John McCallb6cfa242011-01-31 22:28:28 +00005711
5712 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005713 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005714 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005715 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005716 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005717 }
5718
Steve Naroff14108da2009-07-10 23:34:53 +00005719 return Incompatible;
5720 }
John McCallb6cfa242011-01-31 22:28:28 +00005721
5722 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005723 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005724 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005725 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005726 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005727 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005728 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005729
John McCallb6cfa242011-01-31 22:28:28 +00005730 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005731 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005732 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005733 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005734 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005735
Chris Lattnerfc144e22008-01-04 23:18:45 +00005736 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005737 }
John McCallb6cfa242011-01-31 22:28:28 +00005738
5739 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005740 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005741 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005742 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005743 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005744 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005745 }
Steve Naroff14108da2009-07-10 23:34:53 +00005746
John McCallb6cfa242011-01-31 22:28:28 +00005747 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005748 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005749 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005750 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005751 }
5752
Steve Naroff14108da2009-07-10 23:34:53 +00005753 return Incompatible;
5754 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005755
John McCallb6cfa242011-01-31 22:28:28 +00005756 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005757 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5758 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005759 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005760 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005761 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005762 }
John McCallb6cfa242011-01-31 22:28:28 +00005763
Reid Spencer5f016e22007-07-11 17:01:13 +00005764 return Incompatible;
5765}
5766
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005767/// \brief Constructs a transparent union from an expression that is
5768/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005769static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5770 ExprResult &EResult, QualType UnionType,
5771 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005772 // Build an initializer list that designates the appropriate member
5773 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005774 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005775 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005776 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005777 SourceLocation());
5778 Initializer->setType(UnionType);
5779 Initializer->setInitializedFieldInUnion(Field);
5780
5781 // Build a compound literal constructing a value of the transparent
5782 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005783 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005784 EResult = S.Owned(
5785 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5786 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005787}
5788
5789Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005790Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005791 ExprResult &RHS) {
5792 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005793
Mike Stump1eb44332009-09-09 15:08:12 +00005794 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005795 // transparent_union GCC extension.
5796 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005797 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005798 return Incompatible;
5799
5800 // The field to initialize within the transparent union.
5801 RecordDecl *UD = UT->getDecl();
5802 FieldDecl *InitField = 0;
5803 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005804 for (RecordDecl::field_iterator it = UD->field_begin(),
5805 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005806 it != itend; ++it) {
5807 if (it->getType()->isPointerType()) {
5808 // If the transparent union contains a pointer type, we allow:
5809 // 1) void pointer
5810 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005811 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005812 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005813 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005814 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005815 break;
5816 }
Mike Stump1eb44332009-09-09 15:08:12 +00005817
Richard Trieuf7720da2011-09-06 20:40:12 +00005818 if (RHS.get()->isNullPointerConstant(Context,
5819 Expr::NPC_ValueDependentIsNull)) {
5820 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5821 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005822 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005823 break;
5824 }
5825 }
5826
John McCalldaa8e4e2010-11-15 09:13:47 +00005827 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005828 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005829 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005830 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005831 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005832 break;
5833 }
5834 }
5835
5836 if (!InitField)
5837 return Incompatible;
5838
Richard Trieuf7720da2011-09-06 20:40:12 +00005839 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005840 return Compatible;
5841}
5842
Chris Lattner5cf216b2008-01-04 18:04:52 +00005843Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005844Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5845 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005846 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005847 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005848 // C++ 5.17p3: If the left operand is not of class type, the
5849 // expression is implicitly converted (C++ 4) to the
5850 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005851 ExprResult Res;
5852 if (Diagnose) {
5853 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5854 AA_Assigning);
5855 } else {
5856 ImplicitConversionSequence ICS =
5857 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5858 /*SuppressUserConversions=*/false,
5859 /*AllowExplicit=*/false,
5860 /*InOverloadResolution=*/false,
5861 /*CStyle=*/false,
5862 /*AllowObjCWritebackConversion=*/false);
5863 if (ICS.isFailure())
5864 return Incompatible;
5865 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5866 ICS, AA_Assigning);
5867 }
John Wiegley429bb272011-04-08 18:41:53 +00005868 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005869 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005870 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005871 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005872 !CheckObjCARCUnavailableWeakConversion(LHSType,
5873 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005874 result = IncompatibleObjCWeakRef;
Richard Trieuf7720da2011-09-06 20:40:12 +00005875 RHS = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005876 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005877 }
5878
5879 // FIXME: Currently, we fall through and treat C++ classes like C
5880 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005881 // FIXME: We also fall through for atomics; not sure what should
5882 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005883 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005884
Steve Naroff529a4ad2007-11-27 17:58:44 +00005885 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5886 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005887 if ((LHSType->isPointerType() ||
5888 LHSType->isObjCObjectPointerType() ||
5889 LHSType->isBlockPointerType())
5890 && RHS.get()->isNullPointerConstant(Context,
5891 Expr::NPC_ValueDependentIsNull)) {
5892 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005893 return Compatible;
5894 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005895
Chris Lattner943140e2007-10-16 02:55:40 +00005896 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005897 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005898 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005899 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005900 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005901 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005902 if (!LHSType->isReferenceType()) {
5903 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5904 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005905 return Incompatible;
5906 }
Steve Narofff1120de2007-08-24 22:33:52 +00005907
John McCalldaa8e4e2010-11-15 09:13:47 +00005908 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005909 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005910 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005911
Steve Narofff1120de2007-08-24 22:33:52 +00005912 // C99 6.5.16.1p2: The value of the right operand is converted to the
5913 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005914 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5915 // so that we can use references in built-in functions even in C.
5916 // The getNonReferenceType() call makes sure that the resulting expression
5917 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005918 if (result != Incompatible && RHS.get()->getType() != LHSType)
5919 RHS = ImpCastExprToType(RHS.take(),
5920 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005921 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005922}
5923
Richard Trieuf7720da2011-09-06 20:40:12 +00005924QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5925 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005926 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005927 << LHS.get()->getType() << RHS.get()->getType()
5928 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005929 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005930}
5931
Richard Trieu08062aa2011-09-06 21:01:04 +00005932QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005933 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005934 if (!IsCompAssign) {
5935 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5936 if (LHS.isInvalid())
5937 return QualType();
5938 }
5939 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5940 if (RHS.isInvalid())
5941 return QualType();
5942
Mike Stumpeed9cac2009-02-19 03:04:26 +00005943 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005944 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005945 QualType LHSType =
5946 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5947 QualType RHSType =
5948 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005949
Nate Begemanbe2341d2008-07-14 18:02:46 +00005950 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005951 if (LHSType == RHSType)
5952 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005953
Douglas Gregor255210e2010-08-06 10:14:59 +00005954 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005955 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5956 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5957 if (LHSType->isExtVectorType()) {
5958 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5959 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005960 }
5961
Richard Trieuccd891a2011-09-09 01:45:06 +00005962 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005963 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5964 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005965 }
5966
David Blaikie4e4d0842012-03-11 07:00:24 +00005967 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00005968 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005969 // If we are allowing lax vector conversions, and LHS and RHS are both
5970 // vectors, the total size only needs to be the same. This is a
5971 // bitcast; no bits are changed but the result type is different.
5972 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00005973 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5974 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005975 }
5976
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005977 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5978 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5979 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00005980 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005981 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00005982 std::swap(RHS, LHS);
5983 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005984 }
Mike Stump1eb44332009-09-09 15:08:12 +00005985
Nate Begemandde25982009-06-28 19:12:57 +00005986 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00005987 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005988 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00005989 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5990 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005991 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00005992 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005993 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00005994 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5995 if (swapped) std::swap(RHS, LHS);
5996 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005997 }
5998 }
Richard Trieu08062aa2011-09-06 21:01:04 +00005999 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6000 RHSType->isRealFloatingType()) {
6001 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006002 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006003 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006004 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006005 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6006 if (swapped) std::swap(RHS, LHS);
6007 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006008 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006009 }
6010 }
Mike Stump1eb44332009-09-09 15:08:12 +00006011
Nate Begemandde25982009-06-28 19:12:57 +00006012 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006013 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006014 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006015 << LHS.get()->getType() << RHS.get()->getType()
6016 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006017 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006018}
6019
Richard Trieu481037f2011-09-16 00:53:10 +00006020// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6021// expression. These are mainly cases where the null pointer is used as an
6022// integer instead of a pointer.
6023static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6024 SourceLocation Loc, bool IsCompare) {
6025 // The canonical way to check for a GNU null is with isNullPointerConstant,
6026 // but we use a bit of a hack here for speed; this is a relatively
6027 // hot path, and isNullPointerConstant is slow.
6028 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6029 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6030
6031 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6032
6033 // Avoid analyzing cases where the result will either be invalid (and
6034 // diagnosed as such) or entirely valid and not something to warn about.
6035 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6036 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6037 return;
6038
6039 // Comparison operations would not make sense with a null pointer no matter
6040 // what the other expression is.
6041 if (!IsCompare) {
6042 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6043 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6044 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6045 return;
6046 }
6047
6048 // The rest of the operations only make sense with a null pointer
6049 // if the other expression is a pointer.
6050 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6051 NonNullType->canDecayToPointerType())
6052 return;
6053
6054 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6055 << LHSNull /* LHS is NULL */ << NonNullType
6056 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6057}
6058
Richard Trieu08062aa2011-09-06 21:01:04 +00006059QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006060 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006061 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006062 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6063
Richard Trieu08062aa2011-09-06 21:01:04 +00006064 if (LHS.get()->getType()->isVectorType() ||
6065 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006066 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006067
Richard Trieuccd891a2011-09-09 01:45:06 +00006068 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006069 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006070 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006071
David Chisnall7a7ee302012-01-16 17:27:18 +00006072
Eli Friedman860a3192012-06-16 02:19:17 +00006073 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006074 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006075
Chris Lattner7ef655a2010-01-12 21:23:57 +00006076 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006077 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006078 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006079 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006080 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6081 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006082
Chris Lattner7ef655a2010-01-12 21:23:57 +00006083 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006084}
6085
Chris Lattner7ef655a2010-01-12 21:23:57 +00006086QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006087 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006088 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6089
Richard Trieu08062aa2011-09-06 21:01:04 +00006090 if (LHS.get()->getType()->isVectorType() ||
6091 RHS.get()->getType()->isVectorType()) {
6092 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6093 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006094 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006095 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006096 }
Steve Naroff90045e82007-07-13 23:32:42 +00006097
Richard Trieuccd891a2011-09-09 01:45:06 +00006098 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006099 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006100 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006101
Eli Friedman860a3192012-06-16 02:19:17 +00006102 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006103 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006104
Chris Lattner7ef655a2010-01-12 21:23:57 +00006105 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006106 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006107 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006108 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6109 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006110
Chris Lattner7ef655a2010-01-12 21:23:57 +00006111 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006112}
6113
Chandler Carruth13b21be2011-06-27 08:02:19 +00006114/// \brief Diagnose invalid arithmetic on two void pointers.
6115static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006116 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006117 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006118 ? diag::err_typecheck_pointer_arith_void_type
6119 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006120 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6121 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006122}
6123
6124/// \brief Diagnose invalid arithmetic on a void pointer.
6125static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6126 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006127 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006128 ? diag::err_typecheck_pointer_arith_void_type
6129 : diag::ext_gnu_void_ptr)
6130 << 0 /* one pointer */ << Pointer->getSourceRange();
6131}
6132
6133/// \brief Diagnose invalid arithmetic on two function pointers.
6134static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6135 Expr *LHS, Expr *RHS) {
6136 assert(LHS->getType()->isAnyPointerType());
6137 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006138 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006139 ? diag::err_typecheck_pointer_arith_function_type
6140 : diag::ext_gnu_ptr_func_arith)
6141 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6142 // We only show the second type if it differs from the first.
6143 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6144 RHS->getType())
6145 << RHS->getType()->getPointeeType()
6146 << LHS->getSourceRange() << RHS->getSourceRange();
6147}
6148
6149/// \brief Diagnose invalid arithmetic on a function pointer.
6150static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6151 Expr *Pointer) {
6152 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006153 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006154 ? diag::err_typecheck_pointer_arith_function_type
6155 : diag::ext_gnu_ptr_func_arith)
6156 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6157 << 0 /* one pointer, so only one type */
6158 << Pointer->getSourceRange();
6159}
6160
Richard Trieud9f19342011-09-12 18:08:02 +00006161/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006162///
6163/// \returns True if pointer has incomplete type
6164static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6165 Expr *Operand) {
6166 if ((Operand->getType()->isPointerType() &&
6167 !Operand->getType()->isDependentType()) ||
6168 Operand->getType()->isObjCObjectPointerType()) {
6169 QualType PointeeTy = Operand->getType()->getPointeeType();
6170 if (S.RequireCompleteType(
6171 Loc, PointeeTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00006172 diag::err_typecheck_arithmetic_incomplete_type,
6173 PointeeTy, Operand->getSourceRange()))
Richard Trieu097ecd22011-09-02 02:15:37 +00006174 return true;
6175 }
6176 return false;
6177}
6178
Chandler Carruth13b21be2011-06-27 08:02:19 +00006179/// \brief Check the validity of an arithmetic pointer operand.
6180///
6181/// If the operand has pointer type, this code will check for pointer types
6182/// which are invalid in arithmetic operations. These will be diagnosed
6183/// appropriately, including whether or not the use is supported as an
6184/// extension.
6185///
6186/// \returns True when the operand is valid to use (even if as an extension).
6187static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6188 Expr *Operand) {
6189 if (!Operand->getType()->isAnyPointerType()) return true;
6190
6191 QualType PointeeTy = Operand->getType()->getPointeeType();
6192 if (PointeeTy->isVoidType()) {
6193 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006194 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006195 }
6196 if (PointeeTy->isFunctionType()) {
6197 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006198 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006199 }
6200
Richard Trieu097ecd22011-09-02 02:15:37 +00006201 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006202
6203 return true;
6204}
6205
6206/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6207/// operands.
6208///
6209/// This routine will diagnose any invalid arithmetic on pointer operands much
6210/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6211/// for emitting a single diagnostic even for operations where both LHS and RHS
6212/// are (potentially problematic) pointers.
6213///
6214/// \returns True when the operand is valid to use (even if as an extension).
6215static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006216 Expr *LHSExpr, Expr *RHSExpr) {
6217 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6218 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006219 if (!isLHSPointer && !isRHSPointer) return true;
6220
6221 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006222 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6223 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006224
6225 // Check for arithmetic on pointers to incomplete types.
6226 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6227 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6228 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006229 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6230 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6231 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006232
David Blaikie4e4d0842012-03-11 07:00:24 +00006233 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006234 }
6235
6236 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6237 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6238 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006239 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6240 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6241 RHSExpr);
6242 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006243
David Blaikie4e4d0842012-03-11 07:00:24 +00006244 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006245 }
6246
Richard Trieudef75842011-09-06 21:13:51 +00006247 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6248 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006249
Chandler Carruth13b21be2011-06-27 08:02:19 +00006250 return true;
6251}
6252
Richard Trieudb44a6b2011-09-01 22:53:23 +00006253/// \brief Check bad cases where we step over interface counts.
6254static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6255 SourceLocation OpLoc,
6256 Expr *Op) {
6257 assert(Op->getType()->isAnyPointerType());
6258 QualType PointeeTy = Op->getType()->getPointeeType();
6259 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6260 return true;
6261
6262 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6263 << PointeeTy << Op->getSourceRange();
6264 return false;
6265}
6266
Nico Weber1cb2d742012-03-02 22:01:22 +00006267/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6268/// literal.
6269static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6270 Expr *LHSExpr, Expr *RHSExpr) {
6271 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6272 Expr* IndexExpr = RHSExpr;
6273 if (!StrExpr) {
6274 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6275 IndexExpr = LHSExpr;
6276 }
6277
6278 bool IsStringPlusInt = StrExpr &&
6279 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6280 if (!IsStringPlusInt)
6281 return;
6282
6283 llvm::APSInt index;
6284 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6285 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6286 if (index.isNonNegative() &&
6287 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6288 index.isUnsigned()))
6289 return;
6290 }
6291
6292 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6293 Self.Diag(OpLoc, diag::warn_string_plus_int)
6294 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6295
6296 // Only print a fixit for "str" + int, not for int + "str".
6297 if (IndexExpr == RHSExpr) {
6298 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6299 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6300 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6301 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6302 << FixItHint::CreateInsertion(EndLoc, "]");
6303 } else
6304 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6305}
6306
Richard Trieud9f19342011-09-12 18:08:02 +00006307/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006308static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006309 Expr *LHSExpr, Expr *RHSExpr) {
6310 assert(LHSExpr->getType()->isAnyPointerType());
6311 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006312 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006313 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6314 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006315}
6316
Chris Lattner7ef655a2010-01-12 21:23:57 +00006317QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006318 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6319 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006320 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6321
Richard Trieudef75842011-09-06 21:13:51 +00006322 if (LHS.get()->getType()->isVectorType() ||
6323 RHS.get()->getType()->isVectorType()) {
6324 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006325 if (CompLHSTy) *CompLHSTy = compType;
6326 return compType;
6327 }
Steve Naroff49b45262007-07-13 16:58:59 +00006328
Richard Trieudef75842011-09-06 21:13:51 +00006329 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6330 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006331 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006332
Nico Weber1cb2d742012-03-02 22:01:22 +00006333 // Diagnose "string literal" '+' int.
6334 if (Opc == BO_Add)
6335 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6336
Reid Spencer5f016e22007-07-11 17:01:13 +00006337 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006338 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006339 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006340 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006341 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006342
Eli Friedmand72d16e2008-05-18 18:08:51 +00006343 // Put any potential pointer into PExp
Richard Trieudef75842011-09-06 21:13:51 +00006344 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006345 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006346 std::swap(PExp, IExp);
6347
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006348 if (!PExp->getType()->isAnyPointerType())
6349 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006350
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006351 if (!IExp->getType()->isIntegerType())
6352 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006353
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006354 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6355 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006356
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006357 // Diagnose bad cases where we step over interface counts.
6358 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6359 return QualType();
6360
6361 // Check array bounds for pointer arithemtic
6362 CheckArrayAccess(PExp, IExp);
6363
6364 if (CompLHSTy) {
6365 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6366 if (LHSTy.isNull()) {
6367 LHSTy = LHS.get()->getType();
6368 if (LHSTy->isPromotableIntegerType())
6369 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006370 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006371 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006372 }
6373
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006374 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006375}
6376
Chris Lattnereca7be62008-04-07 05:30:13 +00006377// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006378QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006379 SourceLocation Loc,
6380 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006381 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6382
Richard Trieudef75842011-09-06 21:13:51 +00006383 if (LHS.get()->getType()->isVectorType() ||
6384 RHS.get()->getType()->isVectorType()) {
6385 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006386 if (CompLHSTy) *CompLHSTy = compType;
6387 return compType;
6388 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006389
Richard Trieudef75842011-09-06 21:13:51 +00006390 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6391 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006392 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006393
Chris Lattner6e4ab612007-12-09 21:53:25 +00006394 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006395
Chris Lattner6e4ab612007-12-09 21:53:25 +00006396 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006397 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006398 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006399 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006400 }
Mike Stump1eb44332009-09-09 15:08:12 +00006401
Chris Lattner6e4ab612007-12-09 21:53:25 +00006402 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006403 if (LHS.get()->getType()->isAnyPointerType()) {
6404 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006405
Chris Lattnerb5f15622009-04-24 23:50:08 +00006406 // Diagnose bad cases where we step over interface counts.
Richard Trieudef75842011-09-06 21:13:51 +00006407 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006408 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006409
Chris Lattner6e4ab612007-12-09 21:53:25 +00006410 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006411 if (RHS.get()->getType()->isIntegerType()) {
6412 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006413 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006414
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006415 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006416 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6417 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006418
Richard Trieudef75842011-09-06 21:13:51 +00006419 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6420 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006421 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006422
Chris Lattner6e4ab612007-12-09 21:53:25 +00006423 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006424 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006425 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006426 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006427
David Blaikie4e4d0842012-03-11 07:00:24 +00006428 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006429 // Pointee types must be the same: C++ [expr.add]
6430 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006431 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006432 }
6433 } else {
6434 // Pointee types must be compatible C99 6.5.6p3
6435 if (!Context.typesAreCompatible(
6436 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6437 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006438 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006439 return QualType();
6440 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006441 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006442
Chandler Carruth13b21be2011-06-27 08:02:19 +00006443 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006444 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006445 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006446
Richard Trieudef75842011-09-06 21:13:51 +00006447 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006448 return Context.getPointerDiffType();
6449 }
6450 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006451
Richard Trieudef75842011-09-06 21:13:51 +00006452 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006453}
6454
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006455static bool isScopedEnumerationType(QualType T) {
6456 if (const EnumType *ET = dyn_cast<EnumType>(T))
6457 return ET->getDecl()->isScoped();
6458 return false;
6459}
6460
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006461static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006462 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006463 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006464 llvm::APSInt Right;
6465 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006466 if (RHS.get()->isValueDependent() ||
6467 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006468 return;
6469
6470 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006471 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006472 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006473 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006474 return;
6475 }
6476 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006477 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006478 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006479 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006480 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006481 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006482 return;
6483 }
6484 if (Opc != BO_Shl)
6485 return;
6486
6487 // When left shifting an ICE which is signed, we can check for overflow which
6488 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6489 // integers have defined behavior modulo one more than the maximum value
6490 // representable in the result type, so never warn for those.
6491 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006492 if (LHS.get()->isValueDependent() ||
6493 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6494 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006495 return;
6496 llvm::APInt ResultBits =
6497 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6498 if (LeftBits.uge(ResultBits))
6499 return;
6500 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6501 Result = Result.shl(Right);
6502
Ted Kremenekfa821382011-06-15 00:54:52 +00006503 // Print the bit representation of the signed integer as an unsigned
6504 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006505 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006506 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6507
Chandler Carruth21206d52011-02-23 23:34:11 +00006508 // If we are only missing a sign bit, this is less likely to result in actual
6509 // bugs -- if the result is cast back to an unsigned type, it will have the
6510 // expected value. Thus we place this behind a different warning that can be
6511 // turned off separately if needed.
6512 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006513 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006514 << HexResult.str() << LHSType
6515 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006516 return;
6517 }
6518
6519 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006520 << HexResult.str() << Result.getMinSignedBits() << LHSType
6521 << Left.getBitWidth() << LHS.get()->getSourceRange()
6522 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006523}
6524
Chris Lattnereca7be62008-04-07 05:30:13 +00006525// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006526QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006527 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006528 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006529 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6530
Chris Lattnerca5eede2007-12-12 05:47:28 +00006531 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006532 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6533 !RHS.get()->getType()->hasIntegerRepresentation())
6534 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006535
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006536 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6537 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006538 if (isScopedEnumerationType(LHS.get()->getType()) ||
6539 isScopedEnumerationType(RHS.get()->getType())) {
6540 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006541 }
6542
Nate Begeman2207d792009-10-25 02:26:48 +00006543 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006544 if (LHS.get()->getType()->isVectorType() ||
6545 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006546 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006547
Chris Lattnerca5eede2007-12-12 05:47:28 +00006548 // Shifts don't perform usual arithmetic conversions, they just do integer
6549 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006550
John McCall1bc80af2010-12-16 19:28:59 +00006551 // For the LHS, do usual unary conversions, but then reset them away
6552 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006553 ExprResult OldLHS = LHS;
6554 LHS = UsualUnaryConversions(LHS.take());
6555 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006556 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006557 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006558 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006559
6560 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006561 RHS = UsualUnaryConversions(RHS.take());
6562 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006563 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006564
Ryan Flynnd0439682009-08-07 16:20:20 +00006565 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006566 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006567
Chris Lattnerca5eede2007-12-12 05:47:28 +00006568 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006569 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006570}
6571
Chandler Carruth99919472010-07-10 12:30:03 +00006572static bool IsWithinTemplateSpecialization(Decl *D) {
6573 if (DeclContext *DC = D->getDeclContext()) {
6574 if (isa<ClassTemplateSpecializationDecl>(DC))
6575 return true;
6576 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6577 return FD->isFunctionTemplateSpecialization();
6578 }
6579 return false;
6580}
6581
Richard Trieue648ac32011-09-02 03:48:46 +00006582/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006583static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6584 ExprResult &RHS) {
6585 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6586 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006587
6588 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6589 if (!LHSEnumType)
6590 return;
6591 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6592 if (!RHSEnumType)
6593 return;
6594
6595 // Ignore anonymous enums.
6596 if (!LHSEnumType->getDecl()->getIdentifier())
6597 return;
6598 if (!RHSEnumType->getDecl()->getIdentifier())
6599 return;
6600
6601 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6602 return;
6603
6604 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6605 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006606 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006607}
6608
Richard Trieu7be1be02011-09-02 02:55:45 +00006609/// \brief Diagnose bad pointer comparisons.
6610static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006611 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006612 bool IsError) {
6613 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006614 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006615 << LHS.get()->getType() << RHS.get()->getType()
6616 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006617}
6618
6619/// \brief Returns false if the pointers are converted to a composite type,
6620/// true otherwise.
6621static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006622 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006623 // C++ [expr.rel]p2:
6624 // [...] Pointer conversions (4.10) and qualification
6625 // conversions (4.4) are performed on pointer operands (or on
6626 // a pointer operand and a null pointer constant) to bring
6627 // them to their composite pointer type. [...]
6628 //
6629 // C++ [expr.eq]p1 uses the same notion for (in)equality
6630 // comparisons of pointers.
6631
6632 // C++ [expr.eq]p2:
6633 // In addition, pointers to members can be compared, or a pointer to
6634 // member and a null pointer constant. Pointer to member conversions
6635 // (4.11) and qualification conversions (4.4) are performed to bring
6636 // them to a common type. If one operand is a null pointer constant,
6637 // the common type is the type of the other operand. Otherwise, the
6638 // common type is a pointer to member type similar (4.4) to the type
6639 // of one of the operands, with a cv-qualification signature (4.4)
6640 // that is the union of the cv-qualification signatures of the operand
6641 // types.
6642
Richard Trieuba261492011-09-06 21:27:33 +00006643 QualType LHSType = LHS.get()->getType();
6644 QualType RHSType = RHS.get()->getType();
6645 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6646 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006647
6648 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006649 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006650 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006651 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006652 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006653 return true;
6654 }
6655
6656 if (NonStandardCompositeType)
6657 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006658 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6659 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006660
Richard Trieuba261492011-09-06 21:27:33 +00006661 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6662 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006663 return false;
6664}
6665
6666static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006667 ExprResult &LHS,
6668 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006669 bool IsError) {
6670 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6671 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006672 << LHS.get()->getType() << RHS.get()->getType()
6673 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006674}
6675
Jordan Rose9f63a452012-06-08 21:14:25 +00006676static bool isObjCObjectLiteral(ExprResult &E) {
6677 switch (E.get()->getStmtClass()) {
6678 case Stmt::ObjCArrayLiteralClass:
6679 case Stmt::ObjCDictionaryLiteralClass:
6680 case Stmt::ObjCStringLiteralClass:
6681 case Stmt::ObjCBoxedExprClass:
6682 return true;
6683 default:
6684 // Note that ObjCBoolLiteral is NOT an object literal!
6685 return false;
6686 }
6687}
6688
6689static DiagnosticBuilder diagnoseObjCLiteralComparison(Sema &S,
6690 SourceLocation Loc,
6691 ExprResult &LHS,
6692 ExprResult &RHS,
6693 bool CanFix = false) {
6694 Expr *Literal = (isObjCObjectLiteral(LHS) ? LHS : RHS).get();
6695
6696 unsigned LiteralKind;
6697 switch (Literal->getStmtClass()) {
6698 case Stmt::ObjCStringLiteralClass:
6699 // "string literal"
6700 LiteralKind = 0;
6701 break;
6702 case Stmt::ObjCArrayLiteralClass:
6703 // "array literal"
6704 LiteralKind = 1;
6705 break;
6706 case Stmt::ObjCDictionaryLiteralClass:
6707 // "dictionary literal"
6708 LiteralKind = 2;
6709 break;
6710 case Stmt::ObjCBoxedExprClass: {
6711 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6712 switch (Inner->getStmtClass()) {
6713 case Stmt::IntegerLiteralClass:
6714 case Stmt::FloatingLiteralClass:
6715 case Stmt::CharacterLiteralClass:
6716 case Stmt::ObjCBoolLiteralExprClass:
6717 case Stmt::CXXBoolLiteralExprClass:
6718 // "numeric literal"
6719 LiteralKind = 3;
6720 break;
6721 case Stmt::ImplicitCastExprClass: {
6722 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6723 // Boolean literals can be represented by implicit casts.
6724 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6725 LiteralKind = 3;
6726 break;
6727 }
6728 // FALLTHROUGH
6729 }
6730 default:
6731 // "boxed expression"
6732 LiteralKind = 4;
6733 break;
6734 }
6735 break;
6736 }
6737 default:
6738 llvm_unreachable("Unknown Objective-C object literal kind");
6739 }
6740
6741 return S.Diag(Loc, diag::err_objc_literal_comparison)
6742 << LiteralKind << CanFix << Literal->getSourceRange();
6743}
6744
6745static ExprResult fixObjCLiteralComparison(Sema &S, SourceLocation OpLoc,
6746 ExprResult &LHS,
6747 ExprResult &RHS,
6748 BinaryOperatorKind Op) {
6749 assert((Op == BO_EQ || Op == BO_NE) && "Cannot fix other operations.");
6750
6751 // Get the LHS object's interface type.
6752 QualType Type = LHS.get()->getType();
6753 QualType InterfaceType;
6754 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6755 InterfaceType = PTy->getPointeeType();
6756 if (const ObjCObjectType *iQFaceTy =
6757 InterfaceType->getAsObjCQualifiedInterfaceType())
6758 InterfaceType = iQFaceTy->getBaseType();
6759 } else {
6760 // If this is not actually an Objective-C object, bail out.
6761 return ExprEmpty();
6762 }
6763
6764 // If the RHS isn't an Objective-C object, bail out.
6765 if (!RHS.get()->getType()->isObjCObjectPointerType())
6766 return ExprEmpty();
6767
6768 // Try to find the -isEqual: method.
6769 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6770 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6771 InterfaceType,
6772 /*instance=*/true);
6773 bool ReceiverIsId = (Type->isObjCIdType() || Type->isObjCQualifiedIdType());
6774
6775 if (!Method && ReceiverIsId) {
6776 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6777 /*receiverId=*/true,
6778 /*warn=*/false);
6779 }
6780
6781 if (!Method)
6782 return ExprEmpty();
6783
6784 QualType T = Method->param_begin()[0]->getType();
6785 if (!T->isObjCObjectPointerType())
6786 return ExprEmpty();
6787
6788 QualType R = Method->getResultType();
6789 if (!R->isScalarType())
6790 return ExprEmpty();
6791
6792 // At this point we know we have a good -isEqual: method.
6793 // Emit the diagnostic and fixit.
6794 DiagnosticBuilder Diag = diagnoseObjCLiteralComparison(S, OpLoc,
6795 LHS, RHS, true);
6796
6797 Expr *LHSExpr = LHS.take();
6798 Expr *RHSExpr = RHS.take();
6799
6800 SourceLocation Start = LHSExpr->getLocStart();
6801 SourceLocation End = S.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6802 SourceRange OpRange(OpLoc, S.PP.getLocForEndOfToken(OpLoc));
6803
6804 Diag << FixItHint::CreateInsertion(Start, Op == BO_EQ ? "[" : "![")
6805 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6806 << FixItHint::CreateInsertion(End, "]");
6807
6808 // Finally, build the call to -isEqual: (and possible logical not).
6809 ExprResult Call = S.BuildInstanceMessage(LHSExpr, LHSExpr->getType(),
6810 /*SuperLoc=*/SourceLocation(),
6811 IsEqualSel, Method,
6812 OpLoc, OpLoc, OpLoc,
6813 MultiExprArg(S, &RHSExpr, 1),
6814 /*isImplicit=*/false);
6815
6816 ExprResult CallCond = S.CheckBooleanCondition(Call.get(), OpLoc);
6817
6818 if (Op == BO_NE)
6819 return S.CreateBuiltinUnaryOp(OpLoc, UO_LNot, CallCond.get());
6820 return CallCond;
6821}
6822
Douglas Gregor0c6db942009-05-04 06:07:12 +00006823// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006824QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006825 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006826 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006827 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6828
John McCall2de56d12010-08-25 11:45:40 +00006829 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006830
Chris Lattner02dd4b12009-12-05 05:40:13 +00006831 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006832 if (LHS.get()->getType()->isVectorType() ||
6833 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006834 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006835
Richard Trieuf1775fb2011-09-06 21:43:51 +00006836 QualType LHSType = LHS.get()->getType();
6837 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006838
Richard Trieuf1775fb2011-09-06 21:43:51 +00006839 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6840 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006841
Richard Trieuf1775fb2011-09-06 21:43:51 +00006842 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006843
Richard Trieuf1775fb2011-09-06 21:43:51 +00006844 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006845 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006846 !LHS.get()->getLocStart().isMacroID() &&
6847 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006848 // For non-floating point types, check for self-comparisons of the form
6849 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6850 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006851 //
6852 // NOTE: Don't warn about comparison expressions resulting from macro
6853 // expansion. Also don't warn about comparisons which are only self
6854 // comparisons within a template specialization. The warnings should catch
6855 // obvious cases in the definition of the template anyways. The idea is to
6856 // warn when the typed comparison operator will always evaluate to the same
6857 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006858 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006859 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006860 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006861 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006862 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006863 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006864 << (Opc == BO_EQ
6865 || Opc == BO_LE
6866 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006867 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006868 !DRL->getDecl()->getType()->isReferenceType() &&
6869 !DRR->getDecl()->getType()->isReferenceType()) {
6870 // what is it always going to eval to?
6871 char always_evals_to;
6872 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006873 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006874 always_evals_to = 0; // false
6875 break;
John McCall2de56d12010-08-25 11:45:40 +00006876 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006877 always_evals_to = 1; // true
6878 break;
6879 default:
6880 // best we can say is 'a constant'
6881 always_evals_to = 2; // e.g. array1 <= array2
6882 break;
6883 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006884 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006885 << 1 // array
6886 << always_evals_to);
6887 }
6888 }
Chandler Carruth99919472010-07-10 12:30:03 +00006889 }
Mike Stump1eb44332009-09-09 15:08:12 +00006890
Chris Lattner55660a72009-03-08 19:39:53 +00006891 if (isa<CastExpr>(LHSStripped))
6892 LHSStripped = LHSStripped->IgnoreParenCasts();
6893 if (isa<CastExpr>(RHSStripped))
6894 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006895
Chris Lattner55660a72009-03-08 19:39:53 +00006896 // Warn about comparisons against a string constant (unless the other
6897 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006898 Expr *literalString = 0;
6899 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006900 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006901 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006902 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006903 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006904 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006905 } else if ((isa<StringLiteral>(RHSStripped) ||
6906 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006907 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006908 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006909 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006910 literalStringStripped = RHSStripped;
6911 }
6912
6913 if (literalString) {
6914 std::string resultComparison;
6915 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006916 case BO_LT: resultComparison = ") < 0"; break;
6917 case BO_GT: resultComparison = ") > 0"; break;
6918 case BO_LE: resultComparison = ") <= 0"; break;
6919 case BO_GE: resultComparison = ") >= 0"; break;
6920 case BO_EQ: resultComparison = ") == 0"; break;
6921 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006922 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006923 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006924
Ted Kremenek351ba912011-02-23 01:52:04 +00006925 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006926 PDiag(diag::warn_stringcompare)
6927 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006928 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006929 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006930 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006931
Douglas Gregord64fdd02010-06-08 19:50:34 +00006932 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006933 if (LHS.get()->getType()->isArithmeticType() &&
6934 RHS.get()->getType()->isArithmeticType()) {
6935 UsualArithmeticConversions(LHS, RHS);
6936 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006937 return QualType();
6938 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006939 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006940 LHS = UsualUnaryConversions(LHS.take());
6941 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006942 return QualType();
6943
Richard Trieuf1775fb2011-09-06 21:43:51 +00006944 RHS = UsualUnaryConversions(RHS.take());
6945 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006946 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006947 }
6948
Richard Trieuf1775fb2011-09-06 21:43:51 +00006949 LHSType = LHS.get()->getType();
6950 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006951
Douglas Gregor447b69e2008-11-19 03:25:36 +00006952 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006953 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006954
Richard Trieuccd891a2011-09-09 01:45:06 +00006955 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006956 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006957 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006958 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006959 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006960 if (LHSType->hasFloatingRepresentation())
6961 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006962
Richard Trieuf1775fb2011-09-06 21:43:51 +00006963 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006964 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006965 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006966
Richard Trieuf1775fb2011-09-06 21:43:51 +00006967 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006968 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00006969 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006970 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006971
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006972 // All of the following pointer-related warnings are GCC extensions, except
6973 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006974 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006975 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006976 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00006977 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00006978 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006979
David Blaikie4e4d0842012-03-11 07:00:24 +00006980 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006981 if (LCanPointeeTy == RCanPointeeTy)
6982 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00006983 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006984 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6985 // Valid unless comparison between non-null pointer and function pointer
6986 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006987 // In a SFINAE context, we treat this as a hard error to maintain
6988 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006989 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6990 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006991 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00006992 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006993
6994 if (isSFINAEContext())
6995 return QualType();
6996
Richard Trieuf1775fb2011-09-06 21:43:51 +00006997 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006998 return ResultTy;
6999 }
7000 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007001
Richard Trieuf1775fb2011-09-06 21:43:51 +00007002 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007003 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007004 else
7005 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007006 }
Eli Friedman3075e762009-08-23 00:27:47 +00007007 // C99 6.5.9p2 and C99 6.5.8p2
7008 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7009 RCanPointeeTy.getUnqualifiedType())) {
7010 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007011 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007012 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007013 << LHSType << RHSType << LHS.get()->getSourceRange()
7014 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007015 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007016 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007017 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7018 // Valid unless comparison between non-null pointer and function pointer
7019 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007020 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007021 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007022 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007023 } else {
7024 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007025 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007026 }
John McCall34d6f932011-03-11 04:25:25 +00007027 if (LCanPointeeTy != RCanPointeeTy) {
7028 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007029 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007030 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007031 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007032 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007033 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007034 }
Mike Stump1eb44332009-09-09 15:08:12 +00007035
David Blaikie4e4d0842012-03-11 07:00:24 +00007036 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007037 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007038 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007039 return ResultTy;
7040
Mike Stump1eb44332009-09-09 15:08:12 +00007041 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007042 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007043 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007044 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007045 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007046 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7047 RHS = ImpCastExprToType(RHS.take(), LHSType,
7048 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007049 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007050 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007051 return ResultTy;
7052 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007053 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007054 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007055 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007056 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7057 LHS = ImpCastExprToType(LHS.take(), RHSType,
7058 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007059 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007060 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007061 return ResultTy;
7062 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007063
7064 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007065 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007066 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7067 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007068 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007069 else
7070 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007071 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007072
7073 // Handle scoped enumeration types specifically, since they don't promote
7074 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007075 if (LHS.get()->getType()->isEnumeralType() &&
7076 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7077 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007078 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007079 }
Mike Stump1eb44332009-09-09 15:08:12 +00007080
Steve Naroff1c7d0672008-09-04 15:10:53 +00007081 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007082 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007083 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007084 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7085 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007086
Steve Naroff1c7d0672008-09-04 15:10:53 +00007087 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007088 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007089 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007090 << LHSType << RHSType << LHS.get()->getSourceRange()
7091 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007092 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007093 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007094 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007095 }
John Wiegley429bb272011-04-08 18:41:53 +00007096
Steve Naroff59f53942008-09-28 01:11:11 +00007097 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007098 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007099 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7100 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007101 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007102 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007103 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007104 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007105 ->getPointeeType()->isVoidType())))
7106 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007107 << LHSType << RHSType << LHS.get()->getSourceRange()
7108 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007109 }
John McCall34d6f932011-03-11 04:25:25 +00007110 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007111 LHS = ImpCastExprToType(LHS.take(), RHSType,
7112 RHSType->isPointerType() ? CK_BitCast
7113 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007114 else
John McCall1d9b3b22011-09-09 05:25:32 +00007115 RHS = ImpCastExprToType(RHS.take(), LHSType,
7116 LHSType->isPointerType() ? CK_BitCast
7117 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007118 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007119 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007120
Richard Trieuf1775fb2011-09-06 21:43:51 +00007121 if (LHSType->isObjCObjectPointerType() ||
7122 RHSType->isObjCObjectPointerType()) {
7123 const PointerType *LPT = LHSType->getAs<PointerType>();
7124 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007125 if (LPT || RPT) {
7126 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7127 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007128
Steve Naroffa8069f12008-11-17 19:49:16 +00007129 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007130 !Context.typesAreCompatible(LHSType, RHSType)) {
7131 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007132 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007133 }
John McCall34d6f932011-03-11 04:25:25 +00007134 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007135 LHS = ImpCastExprToType(LHS.take(), RHSType,
7136 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007137 else
John McCall1d9b3b22011-09-09 05:25:32 +00007138 RHS = ImpCastExprToType(RHS.take(), LHSType,
7139 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007140 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007141 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007142 if (LHSType->isObjCObjectPointerType() &&
7143 RHSType->isObjCObjectPointerType()) {
7144 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7145 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007146 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007147 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7148 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS);
7149
John McCall34d6f932011-03-11 04:25:25 +00007150 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007151 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007152 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007153 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007154 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007155 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007156 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007157 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7158 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007159 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007160 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00007161 if ((LHSIsNull && LHSType->isIntegerType()) ||
7162 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007163 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007164 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007165 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007166 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007167 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007168 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7169 isError = true;
7170 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007171 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007172
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007173 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007174 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007175 << LHSType << RHSType << LHS.get()->getSourceRange()
7176 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007177 if (isError)
7178 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007179 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007180
Richard Trieuf1775fb2011-09-06 21:43:51 +00007181 if (LHSType->isIntegerType())
7182 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007183 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007184 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007185 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007186 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007187 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007188 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007189
Steve Naroff39218df2008-09-04 16:56:14 +00007190 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007191 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007192 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7193 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007194 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007195 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007196 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007197 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7198 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007199 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007200 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007201
Richard Trieuf1775fb2011-09-06 21:43:51 +00007202 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007203}
7204
Tanya Lattner4f692c22012-01-16 21:02:28 +00007205
7206// Return a signed type that is of identical size and number of elements.
7207// For floating point vectors, return an integer type of identical size
7208// and number of elements.
7209QualType Sema::GetSignedVectorType(QualType V) {
7210 const VectorType *VTy = V->getAs<VectorType>();
7211 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7212 if (TypeSize == Context.getTypeSize(Context.CharTy))
7213 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7214 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7215 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7216 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7217 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7218 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7219 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7220 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7221 "Unhandled vector element size in vector compare");
7222 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7223}
7224
Nate Begemanbe2341d2008-07-14 18:02:46 +00007225/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007226/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007227/// like a scalar comparison, a vector comparison produces a vector of integer
7228/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007229QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007230 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007231 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007232 // Check to make sure we're operating on vectors of the same type and width,
7233 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007234 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007235 if (vType.isNull())
7236 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007237
Richard Trieu9f60dee2011-09-07 01:19:57 +00007238 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007239
Anton Yartsev7870b132011-03-27 15:36:07 +00007240 // If AltiVec, the comparison results in a numeric type, i.e.
7241 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007242 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007243 return Context.getLogicalOperationType();
7244
Nate Begemanbe2341d2008-07-14 18:02:46 +00007245 // For non-floating point types, check for self-comparisons of the form
7246 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7247 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007248 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007249 if (DeclRefExpr* DRL
7250 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7251 if (DeclRefExpr* DRR
7252 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007253 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007254 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007255 PDiag(diag::warn_comparison_always)
7256 << 0 // self-
7257 << 2 // "a constant"
7258 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007259 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007260
Nate Begemanbe2341d2008-07-14 18:02:46 +00007261 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007262 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007263 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007264 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007265 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007266
7267 // Return a signed type for the vector.
7268 return GetSignedVectorType(LHSType);
7269}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007270
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007271QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7272 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007273 // Ensure that either both operands are of the same vector type, or
7274 // one operand is of a vector type and the other is of its element type.
7275 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7276 if (vType.isNull() || vType->isFloatingType())
7277 return InvalidOperands(Loc, LHS, RHS);
7278
7279 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007280}
7281
Reid Spencer5f016e22007-07-11 17:01:13 +00007282inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007283 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007284 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7285
Richard Trieu9f60dee2011-09-07 01:19:57 +00007286 if (LHS.get()->getType()->isVectorType() ||
7287 RHS.get()->getType()->isVectorType()) {
7288 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7289 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007290 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007291
Richard Trieu9f60dee2011-09-07 01:19:57 +00007292 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007293 }
Steve Naroff90045e82007-07-13 23:32:42 +00007294
Richard Trieu9f60dee2011-09-07 01:19:57 +00007295 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7296 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007297 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007298 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007299 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007300 LHS = LHSResult.take();
7301 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007302
Eli Friedman860a3192012-06-16 02:19:17 +00007303 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007304 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007305 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007306}
7307
7308inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007309 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007310
Tanya Lattner4f692c22012-01-16 21:02:28 +00007311 // Check vector operands differently.
7312 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7313 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7314
Chris Lattner90a8f272010-07-13 19:41:32 +00007315 // Diagnose cases where the user write a logical and/or but probably meant a
7316 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7317 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007318 if (LHS.get()->getType()->isIntegerType() &&
7319 !LHS.get()->getType()->isBooleanType() &&
7320 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007321 // Don't warn in macros or template instantiations.
7322 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007323 // If the RHS can be constant folded, and if it constant folds to something
7324 // that isn't 0 or 1 (which indicate a potential logical operation that
7325 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007326 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007327 llvm::APSInt Result;
7328 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007329 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007330 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007331 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007332 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007333 << (Opc == BO_LAnd ? "&&" : "||");
7334 // Suggest replacing the logical operator with the bitwise version
7335 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7336 << (Opc == BO_LAnd ? "&" : "|")
7337 << FixItHint::CreateReplacement(SourceRange(
7338 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007339 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007340 Opc == BO_LAnd ? "&" : "|");
7341 if (Opc == BO_LAnd)
7342 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7343 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7344 << FixItHint::CreateRemoval(
7345 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007346 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007347 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007348 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007349 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007350 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007351 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007352
David Blaikie4e4d0842012-03-11 07:00:24 +00007353 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007354 LHS = UsualUnaryConversions(LHS.take());
7355 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007356 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007357
Richard Trieu9f60dee2011-09-07 01:19:57 +00007358 RHS = UsualUnaryConversions(RHS.take());
7359 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007360 return QualType();
7361
Richard Trieu9f60dee2011-09-07 01:19:57 +00007362 if (!LHS.get()->getType()->isScalarType() ||
7363 !RHS.get()->getType()->isScalarType())
7364 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007365
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007366 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007367 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007368
John McCall75f7c0f2010-06-04 00:29:51 +00007369 // The following is safe because we only use this method for
7370 // non-overloadable operands.
7371
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007372 // C++ [expr.log.and]p1
7373 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007374 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007375 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7376 if (LHSRes.isInvalid())
7377 return InvalidOperands(Loc, LHS, RHS);
7378 LHS = move(LHSRes);
John Wiegley429bb272011-04-08 18:41:53 +00007379
Richard Trieu9f60dee2011-09-07 01:19:57 +00007380 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7381 if (RHSRes.isInvalid())
7382 return InvalidOperands(Loc, LHS, RHS);
7383 RHS = move(RHSRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007384
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007385 // C++ [expr.log.and]p2
7386 // C++ [expr.log.or]p2
7387 // The result is a bool.
7388 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007389}
7390
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007391/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7392/// is a read-only property; return true if so. A readonly property expression
7393/// depends on various declarations and thus must be treated specially.
7394///
Mike Stump1eb44332009-09-09 15:08:12 +00007395static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007396 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7397 if (!PropExpr) return false;
7398 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007399
John McCall3c3b7f92011-10-25 17:37:35 +00007400 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7401 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007402 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007403 PropExpr->getBase()->getType();
7404
John McCall3c3b7f92011-10-25 17:37:35 +00007405 if (const ObjCObjectPointerType *OPT =
7406 BaseType->getAsObjCInterfacePointerType())
7407 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7408 if (S.isPropertyReadonly(PDecl, IFace))
7409 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007410 return false;
7411}
7412
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007413static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007414 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7415 if (!ME) return false;
7416 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7417 ObjCMessageExpr *Base =
7418 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7419 if (!Base) return false;
7420 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007421}
7422
John McCall78dae242012-03-13 00:37:01 +00007423/// Is the given expression (which must be 'const') a reference to a
7424/// variable which was originally non-const, but which has become
7425/// 'const' due to being captured within a block?
7426enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7427static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7428 assert(E->isLValue() && E->getType().isConstQualified());
7429 E = E->IgnoreParens();
7430
7431 // Must be a reference to a declaration from an enclosing scope.
7432 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7433 if (!DRE) return NCCK_None;
7434 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7435
7436 // The declaration must be a variable which is not declared 'const'.
7437 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7438 if (!var) return NCCK_None;
7439 if (var->getType().isConstQualified()) return NCCK_None;
7440 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7441
7442 // Decide whether the first capture was for a block or a lambda.
7443 DeclContext *DC = S.CurContext;
7444 while (DC->getParent() != var->getDeclContext())
7445 DC = DC->getParent();
7446 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7447}
7448
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007449/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7450/// emit an error and return true. If so, return false.
7451static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007452 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007453 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007454 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007455 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007456 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7457 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007458 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7459 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007460 if (IsLV == Expr::MLV_Valid)
7461 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007462
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007463 unsigned Diag = 0;
7464 bool NeedType = false;
7465 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007466 case Expr::MLV_ConstQualified:
7467 Diag = diag::err_typecheck_assign_const;
7468
John McCall78dae242012-03-13 00:37:01 +00007469 // Use a specialized diagnostic when we're assigning to an object
7470 // from an enclosing function or block.
7471 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7472 if (NCCK == NCCK_Block)
7473 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7474 else
7475 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7476 break;
7477 }
7478
John McCall7acddac2011-06-17 06:42:21 +00007479 // In ARC, use some specialized diagnostics for occasions where we
7480 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007481 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007482 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7483 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7484 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7485
John McCall7acddac2011-06-17 06:42:21 +00007486 // Use the normal diagnostic if it's pseudo-__strong but the
7487 // user actually wrote 'const'.
7488 if (var->isARCPseudoStrong() &&
7489 (!var->getTypeSourceInfo() ||
7490 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7491 // There are two pseudo-strong cases:
7492 // - self
John McCallf85e1932011-06-15 23:02:42 +00007493 ObjCMethodDecl *method = S.getCurMethodDecl();
7494 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007495 Diag = method->isClassMethod()
7496 ? diag::err_typecheck_arc_assign_self_class_method
7497 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007498
7499 // - fast enumeration variables
7500 else
John McCallf85e1932011-06-15 23:02:42 +00007501 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007502
John McCallf85e1932011-06-15 23:02:42 +00007503 SourceRange Assign;
7504 if (Loc != OrigLoc)
7505 Assign = SourceRange(OrigLoc, OrigLoc);
7506 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7507 // We need to preserve the AST regardless, so migration tool
7508 // can do its job.
7509 return false;
7510 }
7511 }
7512 }
7513
7514 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007515 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007516 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007517 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7518 NeedType = true;
7519 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007520 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007521 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7522 NeedType = true;
7523 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007524 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007525 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7526 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007527 case Expr::MLV_Valid:
7528 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007529 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007530 case Expr::MLV_MemberFunction:
7531 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007532 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7533 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007534 case Expr::MLV_IncompleteType:
7535 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007536 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007537 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007538 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007539 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7540 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007541 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007542 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007543 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007544 case Expr::MLV_InvalidMessageExpression:
7545 Diag = diag::error_readonly_message_assignment;
7546 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007547 case Expr::MLV_SubObjCPropertySetting:
7548 Diag = diag::error_no_subobject_property_setting;
7549 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007550 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007551
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007552 SourceRange Assign;
7553 if (Loc != OrigLoc)
7554 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007555 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007556 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007557 else
Mike Stump1eb44332009-09-09 15:08:12 +00007558 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007559 return true;
7560}
7561
7562
7563
7564// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007565QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007566 SourceLocation Loc,
7567 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007568 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7569
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007570 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007571 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007572 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007573
Richard Trieu268942b2011-09-07 01:33:52 +00007574 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007575 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7576 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007577 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007578 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007579 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007580 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007581 if (RHS.isInvalid())
7582 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007583 // Special case of NSObject attributes on c-style pointer types.
7584 if (ConvTy == IncompatiblePointer &&
7585 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007586 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007587 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007588 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007589 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007590
John McCallf89e55a2010-11-18 06:31:45 +00007591 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007592 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007593 Diag(Loc, diag::err_objc_object_assignment)
7594 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007595
Chris Lattner2c156472008-08-21 18:04:13 +00007596 // If the RHS is a unary plus or minus, check to see if they = and + are
7597 // right next to each other. If so, the user may have typo'd "x =+ 4"
7598 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007599 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007600 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7601 RHSCheck = ICE->getSubExpr();
7602 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007603 if ((UO->getOpcode() == UO_Plus ||
7604 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007605 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007606 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007607 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007608 // And there is a space or other character before the subexpr of the
7609 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007610 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007611 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007612 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007613 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007614 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007615 }
Chris Lattner2c156472008-08-21 18:04:13 +00007616 }
John McCallf85e1932011-06-15 23:02:42 +00007617
7618 if (ConvTy == Compatible) {
7619 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007620 checkRetainCycles(LHSExpr, RHS.get());
David Blaikie4e4d0842012-03-11 07:00:24 +00007621 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007622 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007623 }
Chris Lattner2c156472008-08-21 18:04:13 +00007624 } else {
7625 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007626 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007627 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007628
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007629 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007630 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007631 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007632
Richard Trieu268942b2011-09-07 01:33:52 +00007633 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007634
Reid Spencer5f016e22007-07-11 17:01:13 +00007635 // C99 6.5.16p3: The type of an assignment expression is the type of the
7636 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007637 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007638 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7639 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007640 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007641 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007642 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007643 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007644}
7645
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007646// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007647static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007648 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007649 LHS = S.CheckPlaceholderExpr(LHS.take());
7650 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007651 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007652 return QualType();
7653
John McCallcf2e5062010-10-12 07:14:40 +00007654 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7655 // operands, but not unary promotions.
7656 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007657
John McCallf6a16482010-12-04 03:47:34 +00007658 // So we treat the LHS as a ignored value, and in C++ we allow the
7659 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007660 LHS = S.IgnoredValueConversions(LHS.take());
7661 if (LHS.isInvalid())
7662 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007663
Eli Friedmana6115062012-05-24 00:47:05 +00007664 S.DiagnoseUnusedExprResult(LHS.get());
7665
David Blaikie4e4d0842012-03-11 07:00:24 +00007666 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007667 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7668 if (RHS.isInvalid())
7669 return QualType();
7670 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007671 S.RequireCompleteType(Loc, RHS.get()->getType(),
7672 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007673 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007674
John Wiegley429bb272011-04-08 18:41:53 +00007675 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007676}
7677
Steve Naroff49b45262007-07-13 16:58:59 +00007678/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7679/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007680static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7681 ExprValueKind &VK,
7682 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007683 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007684 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007685 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007686
Chris Lattner3528d352008-11-21 07:05:48 +00007687 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007688 // Atomic types can be used for increment / decrement where the non-atomic
7689 // versions can, so ignore the _Atomic() specifier for the purpose of
7690 // checking.
7691 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7692 ResType = ResAtomicType->getValueType();
7693
Chris Lattner3528d352008-11-21 07:05:48 +00007694 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007695
David Blaikie4e4d0842012-03-11 07:00:24 +00007696 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007697 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007698 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007699 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007700 return QualType();
7701 }
7702 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007703 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007704 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007705 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007706 } else if (ResType->isAnyPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007707 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007708 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007709 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007710
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007711 // Diagnose bad cases where we step over interface counts.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007712 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007713 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007714 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007715 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007716 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007717 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007718 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007719 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007720 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007721 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007722 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007723 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007724 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007725 } else {
John McCall09431682010-11-18 19:01:18 +00007726 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007727 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007728 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007729 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007730 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007731 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007732 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007733 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007734 // In C++, a prefix increment is the same type as the operand. Otherwise
7735 // (in C or with postfix), the increment is the unqualified type of the
7736 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007737 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007738 VK = VK_LValue;
7739 return ResType;
7740 } else {
7741 VK = VK_RValue;
7742 return ResType.getUnqualifiedType();
7743 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007744}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007745
7746
Anders Carlsson369dee42008-02-01 07:15:58 +00007747/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007748/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007749/// where the declaration is needed for type checking. We only need to
7750/// handle cases when the expression references a function designator
7751/// or is an lvalue. Here are some examples:
7752/// - &(x) => x
7753/// - &*****f => f for f a function designator.
7754/// - &s.xx => s
7755/// - &s.zz[1].yy -> s, if zz is an array
7756/// - *(x + 1) -> x, if x is an array
7757/// - &"123"[2] -> 0
7758/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007759static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007760 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007761 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007762 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007763 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007764 // If this is an arrow operator, the address is an offset from
7765 // the base's value, so the object the base refers to is
7766 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007767 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007768 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007769 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007770 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007771 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007772 // FIXME: This code shouldn't be necessary! We should catch the implicit
7773 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007774 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7775 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7776 if (ICE->getSubExpr()->getType()->isArrayType())
7777 return getPrimaryDecl(ICE->getSubExpr());
7778 }
7779 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007780 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007781 case Stmt::UnaryOperatorClass: {
7782 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007783
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007784 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007785 case UO_Real:
7786 case UO_Imag:
7787 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007788 return getPrimaryDecl(UO->getSubExpr());
7789 default:
7790 return 0;
7791 }
7792 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007793 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007794 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007795 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007796 // If the result of an implicit cast is an l-value, we care about
7797 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007798 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007799 default:
7800 return 0;
7801 }
7802}
7803
Richard Trieu5520f232011-09-07 21:46:33 +00007804namespace {
7805 enum {
7806 AO_Bit_Field = 0,
7807 AO_Vector_Element = 1,
7808 AO_Property_Expansion = 2,
7809 AO_Register_Variable = 3,
7810 AO_No_Error = 4
7811 };
7812}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007813/// \brief Diagnose invalid operand for address of operations.
7814///
7815/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007816static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7817 Expr *E, unsigned Type) {
7818 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7819}
7820
Reid Spencer5f016e22007-07-11 17:01:13 +00007821/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007822/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007823/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007824/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007825/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007826/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007827/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007828static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007829 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007830 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7831 if (PTy->getKind() == BuiltinType::Overload) {
7832 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7833 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7834 << OrigOp.get()->getSourceRange();
7835 return QualType();
7836 }
7837
7838 return S.Context.OverloadTy;
7839 }
7840
7841 if (PTy->getKind() == BuiltinType::UnknownAny)
7842 return S.Context.UnknownAnyTy;
7843
7844 if (PTy->getKind() == BuiltinType::BoundMember) {
7845 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7846 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007847 return QualType();
7848 }
John McCall3c3b7f92011-10-25 17:37:35 +00007849
7850 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7851 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007852 }
John McCall9c72c602010-08-27 09:08:28 +00007853
John McCall3c3b7f92011-10-25 17:37:35 +00007854 if (OrigOp.get()->isTypeDependent())
7855 return S.Context.DependentTy;
7856
7857 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007858
John McCall9c72c602010-08-27 09:08:28 +00007859 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007860 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007861
David Blaikie4e4d0842012-03-11 07:00:24 +00007862 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007863 // Implement C99-only parts of addressof rules.
7864 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007865 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007866 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7867 // (assuming the deref expression is valid).
7868 return uOp->getSubExpr()->getType();
7869 }
7870 // Technically, there should be a check for array subscript
7871 // expressions here, but the result of one is always an lvalue anyway.
7872 }
John McCall5808ce42011-02-03 08:15:49 +00007873 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007874 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007875 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007876
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007877 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007878 bool sfinae = S.isSFINAEContext();
7879 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7880 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007881 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007882 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007883 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007884 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007885 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007886 } else if (lval == Expr::LV_MemberFunction) {
7887 // If it's an instance method, make a member pointer.
7888 // The expression must have exactly the form &A::foo.
7889
7890 // If the underlying expression isn't a decl ref, give up.
7891 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007892 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007893 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007894 return QualType();
7895 }
7896 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7897 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7898
7899 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007900 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007901 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007902 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007903
7904 // The method was named without a qualifier.
7905 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007906 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007907 << op->getSourceRange();
7908 }
7909
John McCall09431682010-11-18 19:01:18 +00007910 return S.Context.getMemberPointerType(op->getType(),
7911 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007912 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007913 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007914 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007915 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007916 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007917 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007918 AddressOfError = AO_Property_Expansion;
7919 } else {
7920 // FIXME: emit more specific diag...
7921 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7922 << op->getSourceRange();
7923 return QualType();
7924 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007925 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007926 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007927 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007928 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007929 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007930 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007931 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007932 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007933 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007934 // with the register storage-class specifier.
7935 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007936 // in C++ it is not error to take address of a register
7937 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007938 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007939 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00007940 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00007941 }
John McCallba135432009-11-21 08:51:07 +00007942 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007943 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007944 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007945 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007946 // Could be a pointer to member, though, if there is an explicit
7947 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007948 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007949 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007950 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007951 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007952 S.Diag(OpLoc,
7953 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007954 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007955 return QualType();
7956 }
Mike Stump1eb44332009-09-09 15:08:12 +00007957
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007958 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7959 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007960 return S.Context.getMemberPointerType(op->getType(),
7961 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007962 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007963 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00007964 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00007965 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007966 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007967
Richard Trieu5520f232011-09-07 21:46:33 +00007968 if (AddressOfError != AO_No_Error) {
7969 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7970 return QualType();
7971 }
7972
Eli Friedman441cf102009-05-16 23:27:50 +00007973 if (lval == Expr::LV_IncompleteVoidType) {
7974 // Taking the address of a void variable is technically illegal, but we
7975 // allow it in cases which are otherwise valid.
7976 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007977 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007978 }
7979
Reid Spencer5f016e22007-07-11 17:01:13 +00007980 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007981 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007982 return S.Context.getObjCObjectPointerType(op->getType());
7983 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007984}
7985
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007986/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007987static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7988 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007989 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007990 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007991
John Wiegley429bb272011-04-08 18:41:53 +00007992 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7993 if (ConvResult.isInvalid())
7994 return QualType();
7995 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007996 QualType OpTy = Op->getType();
7997 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007998
7999 if (isa<CXXReinterpretCastExpr>(Op)) {
8000 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8001 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8002 Op->getSourceRange());
8003 }
8004
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008005 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8006 // is an incomplete type or void. It would be possible to warn about
8007 // dereferencing a void pointer, but it's completely well-defined, and such a
8008 // warning is unlikely to catch any mistakes.
8009 if (const PointerType *PT = OpTy->getAs<PointerType>())
8010 Result = PT->getPointeeType();
8011 else if (const ObjCObjectPointerType *OPT =
8012 OpTy->getAs<ObjCObjectPointerType>())
8013 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008014 else {
John McCallfb8721c2011-04-10 19:13:55 +00008015 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008016 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008017 if (PR.take() != Op)
8018 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008019 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008020
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008021 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008022 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008023 << OpTy << Op->getSourceRange();
8024 return QualType();
8025 }
John McCall09431682010-11-18 19:01:18 +00008026
8027 // Dereferences are usually l-values...
8028 VK = VK_LValue;
8029
8030 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008031 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008032 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008033
8034 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008035}
8036
John McCall2de56d12010-08-25 11:45:40 +00008037static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008038 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008039 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008040 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008041 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008042 case tok::periodstar: Opc = BO_PtrMemD; break;
8043 case tok::arrowstar: Opc = BO_PtrMemI; break;
8044 case tok::star: Opc = BO_Mul; break;
8045 case tok::slash: Opc = BO_Div; break;
8046 case tok::percent: Opc = BO_Rem; break;
8047 case tok::plus: Opc = BO_Add; break;
8048 case tok::minus: Opc = BO_Sub; break;
8049 case tok::lessless: Opc = BO_Shl; break;
8050 case tok::greatergreater: Opc = BO_Shr; break;
8051 case tok::lessequal: Opc = BO_LE; break;
8052 case tok::less: Opc = BO_LT; break;
8053 case tok::greaterequal: Opc = BO_GE; break;
8054 case tok::greater: Opc = BO_GT; break;
8055 case tok::exclaimequal: Opc = BO_NE; break;
8056 case tok::equalequal: Opc = BO_EQ; break;
8057 case tok::amp: Opc = BO_And; break;
8058 case tok::caret: Opc = BO_Xor; break;
8059 case tok::pipe: Opc = BO_Or; break;
8060 case tok::ampamp: Opc = BO_LAnd; break;
8061 case tok::pipepipe: Opc = BO_LOr; break;
8062 case tok::equal: Opc = BO_Assign; break;
8063 case tok::starequal: Opc = BO_MulAssign; break;
8064 case tok::slashequal: Opc = BO_DivAssign; break;
8065 case tok::percentequal: Opc = BO_RemAssign; break;
8066 case tok::plusequal: Opc = BO_AddAssign; break;
8067 case tok::minusequal: Opc = BO_SubAssign; break;
8068 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8069 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8070 case tok::ampequal: Opc = BO_AndAssign; break;
8071 case tok::caretequal: Opc = BO_XorAssign; break;
8072 case tok::pipeequal: Opc = BO_OrAssign; break;
8073 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008074 }
8075 return Opc;
8076}
8077
John McCall2de56d12010-08-25 11:45:40 +00008078static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008079 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008080 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008081 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008082 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008083 case tok::plusplus: Opc = UO_PreInc; break;
8084 case tok::minusminus: Opc = UO_PreDec; break;
8085 case tok::amp: Opc = UO_AddrOf; break;
8086 case tok::star: Opc = UO_Deref; break;
8087 case tok::plus: Opc = UO_Plus; break;
8088 case tok::minus: Opc = UO_Minus; break;
8089 case tok::tilde: Opc = UO_Not; break;
8090 case tok::exclaim: Opc = UO_LNot; break;
8091 case tok::kw___real: Opc = UO_Real; break;
8092 case tok::kw___imag: Opc = UO_Imag; break;
8093 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008094 }
8095 return Opc;
8096}
8097
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008098/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8099/// This warning is only emitted for builtin assignment operations. It is also
8100/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008101static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008102 SourceLocation OpLoc) {
8103 if (!S.ActiveTemplateInstantiations.empty())
8104 return;
8105 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8106 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008107 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8108 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8109 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8110 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8111 if (!LHSDeclRef || !RHSDeclRef ||
8112 LHSDeclRef->getLocation().isMacroID() ||
8113 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008114 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008115 const ValueDecl *LHSDecl =
8116 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8117 const ValueDecl *RHSDecl =
8118 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8119 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008120 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008121 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008122 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008123 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008124 if (RefTy->getPointeeType().isVolatileQualified())
8125 return;
8126
8127 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008128 << LHSDeclRef->getType()
8129 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008130}
8131
Douglas Gregoreaebc752008-11-06 23:29:22 +00008132/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8133/// operator @p Opc at location @c TokLoc. This routine only supports
8134/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008135ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008136 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008137 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008138 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008139 // The syntax only allows initializer lists on the RHS of assignment,
8140 // so we don't need to worry about accepting invalid code for
8141 // non-assignment operators.
8142 // C++11 5.17p9:
8143 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8144 // of x = {} is x = T().
8145 InitializationKind Kind =
8146 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8147 InitializedEntity Entity =
8148 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8149 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8150 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8151 MultiExprArg(&RHSExpr, 1));
8152 if (Init.isInvalid())
8153 return Init;
8154 RHSExpr = Init.take();
8155 }
8156
Richard Trieu78ea78b2011-09-07 01:49:20 +00008157 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008158 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008159 // The following two variables are used for compound assignment operators
8160 QualType CompLHSTy; // Type of LHS after promotions for computation
8161 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008162 ExprValueKind VK = VK_RValue;
8163 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008164
8165 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008166 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008167 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008168 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008169 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8170 VK = LHS.get()->getValueKind();
8171 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008172 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008173 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008174 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008175 break;
John McCall2de56d12010-08-25 11:45:40 +00008176 case BO_PtrMemD:
8177 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008178 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008179 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008180 break;
John McCall2de56d12010-08-25 11:45:40 +00008181 case BO_Mul:
8182 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008183 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008184 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008185 break;
John McCall2de56d12010-08-25 11:45:40 +00008186 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008187 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008188 break;
John McCall2de56d12010-08-25 11:45:40 +00008189 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008190 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008191 break;
John McCall2de56d12010-08-25 11:45:40 +00008192 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008193 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008194 break;
John McCall2de56d12010-08-25 11:45:40 +00008195 case BO_Shl:
8196 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008197 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008198 break;
John McCall2de56d12010-08-25 11:45:40 +00008199 case BO_LE:
8200 case BO_LT:
8201 case BO_GE:
8202 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008203 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008204 break;
John McCall2de56d12010-08-25 11:45:40 +00008205 case BO_EQ:
8206 case BO_NE:
Jordan Rose9f63a452012-06-08 21:14:25 +00008207 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) {
8208 ExprResult IsEqualCall = fixObjCLiteralComparison(*this, OpLoc,
8209 LHS, RHS, Opc);
8210 if (IsEqualCall.isUsable())
8211 return IsEqualCall;
8212 // Otherwise, fall back to the normal diagnostic in CheckCompareOperands.
8213 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008214 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008215 break;
John McCall2de56d12010-08-25 11:45:40 +00008216 case BO_And:
8217 case BO_Xor:
8218 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008219 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008220 break;
John McCall2de56d12010-08-25 11:45:40 +00008221 case BO_LAnd:
8222 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008223 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008224 break;
John McCall2de56d12010-08-25 11:45:40 +00008225 case BO_MulAssign:
8226 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008227 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008228 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008229 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008230 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8231 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008232 break;
John McCall2de56d12010-08-25 11:45:40 +00008233 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008234 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008235 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008236 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8237 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008238 break;
John McCall2de56d12010-08-25 11:45:40 +00008239 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008240 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008241 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8242 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008243 break;
John McCall2de56d12010-08-25 11:45:40 +00008244 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008245 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8246 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8247 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008248 break;
John McCall2de56d12010-08-25 11:45:40 +00008249 case BO_ShlAssign:
8250 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008251 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008252 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008253 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8254 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008255 break;
John McCall2de56d12010-08-25 11:45:40 +00008256 case BO_AndAssign:
8257 case BO_XorAssign:
8258 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008259 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008260 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008261 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8262 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008263 break;
John McCall2de56d12010-08-25 11:45:40 +00008264 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008265 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008266 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008267 VK = RHS.get()->getValueKind();
8268 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008269 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008270 break;
8271 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008272 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008273 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008274
8275 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008276 CheckArrayAccess(LHS.get());
8277 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008278
Eli Friedmanab3a8522009-03-28 01:22:36 +00008279 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008280 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008281 ResultTy, VK, OK, OpLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00008282 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008283 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008284 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008285 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008286 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008287 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008288 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008289 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008290}
8291
Sebastian Redlaee3c932009-10-27 12:10:02 +00008292/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8293/// operators are mixed in a way that suggests that the programmer forgot that
8294/// comparison operators have higher precedence. The most typical example of
8295/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008296static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008297 SourceLocation OpLoc, Expr *LHSExpr,
8298 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008299 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008300 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8301 RHSopc = static_cast<BinOp::Opcode>(-1);
8302 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8303 LHSopc = BO->getOpcode();
8304 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8305 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008306
8307 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008308 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008309 return;
8310
8311 // Bitwise operations are sometimes used as eager logical ops.
8312 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008313 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8314 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008315 return;
8316
Richard Trieu78ea78b2011-09-07 01:49:20 +00008317 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8318 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008319 if (!isLeftComp && !isRightComp) return;
8320
Richard Trieu78ea78b2011-09-07 01:49:20 +00008321 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8322 OpLoc)
8323 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8324 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8325 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008326 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008327 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8328 RHSExpr->getLocEnd())
8329 : SourceRange(LHSExpr->getLocStart(),
8330 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008331
8332 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8333 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8334 SuggestParentheses(Self, OpLoc,
8335 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008336 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008337 SuggestParentheses(Self, OpLoc,
8338 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8339 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008340}
8341
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008342/// \brief It accepts a '&' expr that is inside a '|' one.
8343/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8344/// in parentheses.
8345static void
8346EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8347 BinaryOperator *Bop) {
8348 assert(Bop->getOpcode() == BO_And);
8349 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8350 << Bop->getSourceRange() << OpLoc;
8351 SuggestParentheses(Self, Bop->getOperatorLoc(),
8352 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8353 Bop->getSourceRange());
8354}
8355
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008356/// \brief It accepts a '&&' expr that is inside a '||' one.
8357/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8358/// in parentheses.
8359static void
8360EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008361 BinaryOperator *Bop) {
8362 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008363 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8364 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008365 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008366 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008367 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008368}
8369
8370/// \brief Returns true if the given expression can be evaluated as a constant
8371/// 'true'.
8372static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8373 bool Res;
8374 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8375}
8376
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008377/// \brief Returns true if the given expression can be evaluated as a constant
8378/// 'false'.
8379static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8380 bool Res;
8381 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8382}
8383
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008384/// \brief Look for '&&' in the left hand of a '||' expr.
8385static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008386 Expr *LHSExpr, Expr *RHSExpr) {
8387 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008388 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008389 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008390 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008391 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008392 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8393 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8394 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8395 } else if (Bop->getOpcode() == BO_LOr) {
8396 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8397 // If it's "a || b && 1 || c" we didn't warn earlier for
8398 // "a || b && 1", but warn now.
8399 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8400 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8401 }
8402 }
8403 }
8404}
8405
8406/// \brief Look for '&&' in the right hand of a '||' expr.
8407static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008408 Expr *LHSExpr, Expr *RHSExpr) {
8409 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008410 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008411 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008412 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008413 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008414 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8415 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8416 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008417 }
8418 }
8419}
8420
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008421/// \brief Look for '&' in the left or right hand of a '|' expr.
8422static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8423 Expr *OrArg) {
8424 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8425 if (Bop->getOpcode() == BO_And)
8426 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8427 }
8428}
8429
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008430/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008431/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008432static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008433 SourceLocation OpLoc, Expr *LHSExpr,
8434 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008435 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008436 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008437 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008438
8439 // Diagnose "arg1 & arg2 | arg3"
8440 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008441 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8442 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008443 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008444
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008445 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8446 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008447 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008448 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8449 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008450 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008451}
8452
Reid Spencer5f016e22007-07-11 17:01:13 +00008453// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008454ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008455 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008456 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008457 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008458 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8459 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008460
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008461 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008462 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008463
Richard Trieubefece12011-09-07 02:02:10 +00008464 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008465}
8466
John McCall3c3b7f92011-10-25 17:37:35 +00008467/// Build an overloaded binary operator expression in the given scope.
8468static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8469 BinaryOperatorKind Opc,
8470 Expr *LHS, Expr *RHS) {
8471 // Find all of the overloaded operators visible from this
8472 // point. We perform both an operator-name lookup from the local
8473 // scope and an argument-dependent lookup based on the types of
8474 // the arguments.
8475 UnresolvedSet<16> Functions;
8476 OverloadedOperatorKind OverOp
8477 = BinaryOperator::getOverloadedOperator(Opc);
8478 if (Sc && OverOp != OO_None)
8479 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8480 RHS->getType(), Functions);
8481
8482 // Build the (potentially-overloaded, potentially-dependent)
8483 // binary operation.
8484 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8485}
8486
John McCall60d7b3a2010-08-24 06:29:42 +00008487ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008488 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008489 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008490 // We want to end up calling one of checkPseudoObjectAssignment
8491 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8492 // both expressions are overloadable or either is type-dependent),
8493 // or CreateBuiltinBinOp (in any other case). We also want to get
8494 // any placeholder types out of the way.
8495
John McCall3c3b7f92011-10-25 17:37:35 +00008496 // Handle pseudo-objects in the LHS.
8497 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8498 // Assignments with a pseudo-object l-value need special analysis.
8499 if (pty->getKind() == BuiltinType::PseudoObject &&
8500 BinaryOperator::isAssignmentOp(Opc))
8501 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8502
8503 // Don't resolve overloads if the other type is overloadable.
8504 if (pty->getKind() == BuiltinType::Overload) {
8505 // We can't actually test that if we still have a placeholder,
8506 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008507 // code below are valid when the LHS is an overload set. Note
8508 // that an overload set can be dependently-typed, but it never
8509 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008510 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8511 if (resolvedRHS.isInvalid()) return ExprError();
8512 RHSExpr = resolvedRHS.take();
8513
John McCallac516502011-10-28 01:04:34 +00008514 if (RHSExpr->isTypeDependent() ||
8515 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008516 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8517 }
8518
8519 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8520 if (LHS.isInvalid()) return ExprError();
8521 LHSExpr = LHS.take();
8522 }
8523
8524 // Handle pseudo-objects in the RHS.
8525 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8526 // An overload in the RHS can potentially be resolved by the type
8527 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008528 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8529 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8530 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8531
Eli Friedman87884912012-01-17 21:27:43 +00008532 if (LHSExpr->getType()->isOverloadableType())
8533 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8534
John McCall3c3b7f92011-10-25 17:37:35 +00008535 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008536 }
John McCall3c3b7f92011-10-25 17:37:35 +00008537
8538 // Don't resolve overloads if the other type is overloadable.
8539 if (pty->getKind() == BuiltinType::Overload &&
8540 LHSExpr->getType()->isOverloadableType())
8541 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8542
8543 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8544 if (!resolvedRHS.isUsable()) return ExprError();
8545 RHSExpr = resolvedRHS.take();
8546 }
8547
David Blaikie4e4d0842012-03-11 07:00:24 +00008548 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008549 // If either expression is type-dependent, always build an
8550 // overloaded op.
8551 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8552 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008553
John McCallac516502011-10-28 01:04:34 +00008554 // Otherwise, build an overloaded op if either expression has an
8555 // overloadable type.
8556 if (LHSExpr->getType()->isOverloadableType() ||
8557 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008558 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008559 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008560
Douglas Gregoreaebc752008-11-06 23:29:22 +00008561 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008562 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008563}
8564
John McCall60d7b3a2010-08-24 06:29:42 +00008565ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008566 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008567 Expr *InputExpr) {
8568 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008569 ExprValueKind VK = VK_RValue;
8570 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008571 QualType resultType;
8572 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008573 case UO_PreInc:
8574 case UO_PreDec:
8575 case UO_PostInc:
8576 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008577 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008578 Opc == UO_PreInc ||
8579 Opc == UO_PostInc,
8580 Opc == UO_PreInc ||
8581 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008582 break;
John McCall2de56d12010-08-25 11:45:40 +00008583 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008584 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008585 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008586 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008587 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8588 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008589 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008590 }
John McCall2de56d12010-08-25 11:45:40 +00008591 case UO_Plus:
8592 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008593 Input = UsualUnaryConversions(Input.take());
8594 if (Input.isInvalid()) return ExprError();
8595 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008596 if (resultType->isDependentType())
8597 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008598 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8599 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008600 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008601 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008602 resultType->isEnumeralType())
8603 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008604 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008605 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008606 resultType->isPointerType())
8607 break;
8608
Sebastian Redl0eb23302009-01-19 00:08:26 +00008609 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008610 << resultType << Input.get()->getSourceRange());
8611
John McCall2de56d12010-08-25 11:45:40 +00008612 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008613 Input = UsualUnaryConversions(Input.take());
8614 if (Input.isInvalid()) return ExprError();
8615 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008616 if (resultType->isDependentType())
8617 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008618 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8619 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8620 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008621 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008622 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008623 else if (resultType->hasIntegerRepresentation())
8624 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008625 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008626 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008627 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008628 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008629 break;
John Wiegley429bb272011-04-08 18:41:53 +00008630
John McCall2de56d12010-08-25 11:45:40 +00008631 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008632 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008633 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8634 if (Input.isInvalid()) return ExprError();
8635 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008636
8637 // Though we still have to promote half FP to float...
8638 if (resultType->isHalfType()) {
8639 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8640 resultType = Context.FloatTy;
8641 }
8642
Sebastian Redl28507842009-02-26 14:39:58 +00008643 if (resultType->isDependentType())
8644 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008645 if (resultType->isScalarType()) {
8646 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008647 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008648 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8649 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008650 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8651 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008652 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008653 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008654 // Vector logical not returns the signed variant of the operand type.
8655 resultType = GetSignedVectorType(resultType);
8656 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008657 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008658 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008659 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008660 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008661
Reid Spencer5f016e22007-07-11 17:01:13 +00008662 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008663 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008664 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008665 break;
John McCall2de56d12010-08-25 11:45:40 +00008666 case UO_Real:
8667 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008668 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008669 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8670 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008671 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008672 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8673 if (Input.get()->getValueKind() != VK_RValue &&
8674 Input.get()->getObjectKind() == OK_Ordinary)
8675 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008676 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008677 // In C, a volatile scalar is read by __imag. In C++, it is not.
8678 Input = DefaultLvalueConversion(Input.take());
8679 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008680 break;
John McCall2de56d12010-08-25 11:45:40 +00008681 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008682 resultType = Input.get()->getType();
8683 VK = Input.get()->getValueKind();
8684 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008685 break;
8686 }
John Wiegley429bb272011-04-08 18:41:53 +00008687 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008688 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008689
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008690 // Check for array bounds violations in the operand of the UnaryOperator,
8691 // except for the '*' and '&' operators that have to be handled specially
8692 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8693 // that are explicitly defined as valid by the standard).
8694 if (Opc != UO_AddrOf && Opc != UO_Deref)
8695 CheckArrayAccess(Input.get());
8696
John Wiegley429bb272011-04-08 18:41:53 +00008697 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008698 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008699}
8700
Douglas Gregord3d08532011-12-14 21:23:13 +00008701/// \brief Determine whether the given expression is a qualified member
8702/// access expression, of a form that could be turned into a pointer to member
8703/// with the address-of operator.
8704static bool isQualifiedMemberAccess(Expr *E) {
8705 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8706 if (!DRE->getQualifier())
8707 return false;
8708
8709 ValueDecl *VD = DRE->getDecl();
8710 if (!VD->isCXXClassMember())
8711 return false;
8712
8713 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8714 return true;
8715 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8716 return Method->isInstance();
8717
8718 return false;
8719 }
8720
8721 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8722 if (!ULE->getQualifier())
8723 return false;
8724
8725 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8726 DEnd = ULE->decls_end();
8727 D != DEnd; ++D) {
8728 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8729 if (Method->isInstance())
8730 return true;
8731 } else {
8732 // Overload set does not contain methods.
8733 break;
8734 }
8735 }
8736
8737 return false;
8738 }
8739
8740 return false;
8741}
8742
John McCall60d7b3a2010-08-24 06:29:42 +00008743ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008744 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008745 // First things first: handle placeholders so that the
8746 // overloaded-operator check considers the right type.
8747 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8748 // Increment and decrement of pseudo-object references.
8749 if (pty->getKind() == BuiltinType::PseudoObject &&
8750 UnaryOperator::isIncrementDecrementOp(Opc))
8751 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8752
8753 // extension is always a builtin operator.
8754 if (Opc == UO_Extension)
8755 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8756
8757 // & gets special logic for several kinds of placeholder.
8758 // The builtin code knows what to do.
8759 if (Opc == UO_AddrOf &&
8760 (pty->getKind() == BuiltinType::Overload ||
8761 pty->getKind() == BuiltinType::UnknownAny ||
8762 pty->getKind() == BuiltinType::BoundMember))
8763 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8764
8765 // Anything else needs to be handled now.
8766 ExprResult Result = CheckPlaceholderExpr(Input);
8767 if (Result.isInvalid()) return ExprError();
8768 Input = Result.take();
8769 }
8770
David Blaikie4e4d0842012-03-11 07:00:24 +00008771 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008772 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8773 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008774 // Find all of the overloaded operators visible from this
8775 // point. We perform both an operator-name lookup from the local
8776 // scope and an argument-dependent lookup based on the types of
8777 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008778 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008779 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008780 if (S && OverOp != OO_None)
8781 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8782 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008783
John McCall9ae2f072010-08-23 23:25:46 +00008784 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008785 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008786
John McCall9ae2f072010-08-23 23:25:46 +00008787 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008788}
8789
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008790// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008791ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008792 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008793 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008794}
8795
Steve Naroff1b273c42007-09-16 14:56:35 +00008796/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008797ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008798 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008799 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008800 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008801 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008802 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008803}
8804
John McCallf85e1932011-06-15 23:02:42 +00008805/// Given the last statement in a statement-expression, check whether
8806/// the result is a producing expression (like a call to an
8807/// ns_returns_retained function) and, if so, rebuild it to hoist the
8808/// release out of the full-expression. Otherwise, return null.
8809/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008810static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008811 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008812 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008813 if (!cleanups) return 0;
8814
8815 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008816 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008817 return 0;
8818
8819 // Splice out the cast. This shouldn't modify any interesting
8820 // features of the statement.
8821 Expr *producer = cast->getSubExpr();
8822 assert(producer->getType() == cast->getType());
8823 assert(producer->getValueKind() == cast->getValueKind());
8824 cleanups->setSubExpr(producer);
8825 return cleanups;
8826}
8827
John McCall73f428c2012-04-04 01:27:53 +00008828void Sema::ActOnStartStmtExpr() {
8829 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8830}
8831
8832void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008833 // Note that function is also called by TreeTransform when leaving a
8834 // StmtExpr scope without rebuilding anything.
8835
John McCall73f428c2012-04-04 01:27:53 +00008836 DiscardCleanupsInEvaluationContext();
8837 PopExpressionEvaluationContext();
8838}
8839
John McCall60d7b3a2010-08-24 06:29:42 +00008840ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008841Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008842 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008843 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8844 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8845
John McCall73f428c2012-04-04 01:27:53 +00008846 if (hasAnyUnrecoverableErrorsInThisFunction())
8847 DiscardCleanupsInEvaluationContext();
8848 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8849 PopExpressionEvaluationContext();
8850
Douglas Gregordd8f5692010-03-10 04:54:39 +00008851 bool isFileScope
8852 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008853 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008854 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008855
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008856 // FIXME: there are a variety of strange constraints to enforce here, for
8857 // example, it is not possible to goto into a stmt expression apparently.
8858 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008859
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008860 // If there are sub stmts in the compound stmt, take the type of the last one
8861 // as the type of the stmtexpr.
8862 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008863 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008864 if (!Compound->body_empty()) {
8865 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008866 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008867 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008868 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8869 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008870 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008871 }
John McCallf85e1932011-06-15 23:02:42 +00008872
John Wiegley429bb272011-04-08 18:41:53 +00008873 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008874 // Do function/array conversion on the last expression, but not
8875 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008876 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8877 if (LastExpr.isInvalid())
8878 return ExprError();
8879 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008880
John Wiegley429bb272011-04-08 18:41:53 +00008881 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008882 // In ARC, if the final expression ends in a consume, splice
8883 // the consume out and bind it later. In the alternate case
8884 // (when dealing with a retainable type), the result
8885 // initialization will create a produce. In both cases the
8886 // result will be +1, and we'll need to balance that out with
8887 // a bind.
8888 if (Expr *rebuiltLastStmt
8889 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8890 LastExpr = rebuiltLastStmt;
8891 } else {
8892 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008893 InitializedEntity::InitializeResult(LPLoc,
8894 Ty,
8895 false),
8896 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008897 LastExpr);
8898 }
8899
John Wiegley429bb272011-04-08 18:41:53 +00008900 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008901 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008902 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008903 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008904 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008905 else
John Wiegley429bb272011-04-08 18:41:53 +00008906 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008907 StmtExprMayBindToTemp = true;
8908 }
8909 }
8910 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008911 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008912
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008913 // FIXME: Check that expression type is complete/non-abstract; statement
8914 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008915 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8916 if (StmtExprMayBindToTemp)
8917 return MaybeBindToTemporary(ResStmtExpr);
8918 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008919}
Steve Naroffd34e9152007-08-01 22:05:33 +00008920
John McCall60d7b3a2010-08-24 06:29:42 +00008921ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008922 TypeSourceInfo *TInfo,
8923 OffsetOfComponent *CompPtr,
8924 unsigned NumComponents,
8925 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008926 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008927 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008928 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008929
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008930 // We must have at least one component that refers to the type, and the first
8931 // one is known to be a field designator. Verify that the ArgTy represents
8932 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008933 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008934 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8935 << ArgTy << TypeRange);
8936
8937 // Type must be complete per C99 7.17p3 because a declaring a variable
8938 // with an incomplete type would be ill-formed.
8939 if (!Dependent
8940 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00008941 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008942 return ExprError();
8943
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008944 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8945 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008946 // FIXME: This diagnostic isn't actually visible because the location is in
8947 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008948 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008949 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8950 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008951
8952 bool DidWarnAboutNonPOD = false;
8953 QualType CurrentType = ArgTy;
8954 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008955 SmallVector<OffsetOfNode, 4> Comps;
8956 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008957 for (unsigned i = 0; i != NumComponents; ++i) {
8958 const OffsetOfComponent &OC = CompPtr[i];
8959 if (OC.isBrackets) {
8960 // Offset of an array sub-field. TODO: Should we allow vector elements?
8961 if (!CurrentType->isDependentType()) {
8962 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8963 if(!AT)
8964 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8965 << CurrentType);
8966 CurrentType = AT->getElementType();
8967 } else
8968 CurrentType = Context.DependentTy;
8969
Richard Smithea011432011-10-17 23:29:39 +00008970 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8971 if (IdxRval.isInvalid())
8972 return ExprError();
8973 Expr *Idx = IdxRval.take();
8974
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008975 // The expression must be an integral expression.
8976 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008977 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8978 !Idx->getType()->isIntegerType())
8979 return ExprError(Diag(Idx->getLocStart(),
8980 diag::err_typecheck_subscript_not_integer)
8981 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00008982
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008983 // Record this array index.
8984 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00008985 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008986 continue;
8987 }
8988
8989 // Offset of a field.
8990 if (CurrentType->isDependentType()) {
8991 // We have the offset of a field, but we can't look into the dependent
8992 // type. Just record the identifier of the field.
8993 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8994 CurrentType = Context.DependentTy;
8995 continue;
8996 }
8997
8998 // We need to have a complete type to look into.
8999 if (RequireCompleteType(OC.LocStart, CurrentType,
9000 diag::err_offsetof_incomplete_type))
9001 return ExprError();
9002
9003 // Look for the designated field.
9004 const RecordType *RC = CurrentType->getAs<RecordType>();
9005 if (!RC)
9006 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9007 << CurrentType);
9008 RecordDecl *RD = RC->getDecl();
9009
9010 // C++ [lib.support.types]p5:
9011 // The macro offsetof accepts a restricted set of type arguments in this
9012 // International Standard. type shall be a POD structure or a POD union
9013 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009014 // C++11 [support.types]p4:
9015 // If type is not a standard-layout class (Clause 9), the results are
9016 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009017 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009018 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9019 unsigned DiagID =
9020 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9021 : diag::warn_offsetof_non_pod_type;
9022
9023 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009024 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009025 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009026 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9027 << CurrentType))
9028 DidWarnAboutNonPOD = true;
9029 }
9030
9031 // Look for the field.
9032 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9033 LookupQualifiedName(R, RD);
9034 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009035 IndirectFieldDecl *IndirectMemberDecl = 0;
9036 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009037 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009038 MemberDecl = IndirectMemberDecl->getAnonField();
9039 }
9040
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009041 if (!MemberDecl)
9042 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9043 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9044 OC.LocEnd));
9045
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009046 // C99 7.17p3:
9047 // (If the specified member is a bit-field, the behavior is undefined.)
9048 //
9049 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009050 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009051 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9052 << MemberDecl->getDeclName()
9053 << SourceRange(BuiltinLoc, RParenLoc);
9054 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9055 return ExprError();
9056 }
Eli Friedman19410a72010-08-05 10:11:36 +00009057
9058 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009059 if (IndirectMemberDecl)
9060 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009061
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009062 // If the member was found in a base class, introduce OffsetOfNodes for
9063 // the base class indirections.
9064 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9065 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009066 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009067 CXXBasePath &Path = Paths.front();
9068 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9069 B != BEnd; ++B)
9070 Comps.push_back(OffsetOfNode(B->Base));
9071 }
Eli Friedman19410a72010-08-05 10:11:36 +00009072
Francois Pichet87c2e122010-11-21 06:08:52 +00009073 if (IndirectMemberDecl) {
9074 for (IndirectFieldDecl::chain_iterator FI =
9075 IndirectMemberDecl->chain_begin(),
9076 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9077 assert(isa<FieldDecl>(*FI));
9078 Comps.push_back(OffsetOfNode(OC.LocStart,
9079 cast<FieldDecl>(*FI), OC.LocEnd));
9080 }
9081 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009082 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009083
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009084 CurrentType = MemberDecl->getType().getNonReferenceType();
9085 }
9086
9087 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9088 TInfo, Comps.data(), Comps.size(),
9089 Exprs.data(), Exprs.size(), RParenLoc));
9090}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009091
John McCall60d7b3a2010-08-24 06:29:42 +00009092ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009093 SourceLocation BuiltinLoc,
9094 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009095 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009096 OffsetOfComponent *CompPtr,
9097 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009098 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009099
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009100 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009101 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009102 if (ArgTy.isNull())
9103 return ExprError();
9104
Eli Friedman5a15dc12010-08-05 10:15:45 +00009105 if (!ArgTInfo)
9106 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9107
9108 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009109 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009110}
9111
9112
John McCall60d7b3a2010-08-24 06:29:42 +00009113ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009114 Expr *CondExpr,
9115 Expr *LHSExpr, Expr *RHSExpr,
9116 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009117 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9118
John McCallf89e55a2010-11-18 06:31:45 +00009119 ExprValueKind VK = VK_RValue;
9120 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009121 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009122 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009123 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009124 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009125 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009126 } else {
9127 // The conditional expression is required to be a constant expression.
9128 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009129 ExprResult CondICE
9130 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9131 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009132 if (CondICE.isInvalid())
9133 return ExprError();
9134 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009135
Sebastian Redl28507842009-02-26 14:39:58 +00009136 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009137 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9138
9139 resType = ActiveExpr->getType();
9140 ValueDependent = ActiveExpr->isValueDependent();
9141 VK = ActiveExpr->getValueKind();
9142 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009143 }
9144
Sebastian Redlf53597f2009-03-15 17:47:39 +00009145 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009146 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009147 resType->isDependentType(),
9148 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009149}
9150
Steve Naroff4eb206b2008-09-03 18:15:37 +00009151//===----------------------------------------------------------------------===//
9152// Clang Extensions.
9153//===----------------------------------------------------------------------===//
9154
9155/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009156void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009157 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009158 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009159 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009160 if (CurScope)
9161 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009162 else
9163 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009164
Eli Friedman84b007f2012-01-26 03:00:14 +00009165 getCurBlock()->HasImplicitReturnType = true;
9166
John McCall538773c2011-11-11 03:19:12 +00009167 // Enter a new evaluation context to insulate the block from any
9168 // cleanups from the enclosing full-expression.
9169 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009170}
9171
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009172void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9173 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009174 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009175 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009176 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009177
John McCallbf1a0282010-06-04 23:28:52 +00009178 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009179 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009180
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009181 // FIXME: We should allow unexpanded parameter packs here, but that would,
9182 // in turn, make the block expression contain unexpanded parameter packs.
9183 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9184 // Drop the parameters.
9185 FunctionProtoType::ExtProtoInfo EPI;
9186 EPI.HasTrailingReturn = false;
9187 EPI.TypeQuals |= DeclSpec::TQ_const;
9188 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9189 EPI);
9190 Sig = Context.getTrivialTypeSourceInfo(T);
9191 }
9192
John McCall711c52b2011-01-05 12:14:39 +00009193 // GetTypeForDeclarator always produces a function type for a block
9194 // literal signature. Furthermore, it is always a FunctionProtoType
9195 // unless the function was written with a typedef.
9196 assert(T->isFunctionType() &&
9197 "GetTypeForDeclarator made a non-function block signature");
9198
9199 // Look for an explicit signature in that function type.
9200 FunctionProtoTypeLoc ExplicitSignature;
9201
9202 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9203 if (isa<FunctionProtoTypeLoc>(tmp)) {
9204 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9205
9206 // Check whether that explicit signature was synthesized by
9207 // GetTypeForDeclarator. If so, don't save that as part of the
9208 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009209 if (ExplicitSignature.getLocalRangeBegin() ==
9210 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009211 // This would be much cheaper if we stored TypeLocs instead of
9212 // TypeSourceInfos.
9213 TypeLoc Result = ExplicitSignature.getResultLoc();
9214 unsigned Size = Result.getFullDataSize();
9215 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9216 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9217
9218 ExplicitSignature = FunctionProtoTypeLoc();
9219 }
John McCall82dc0092010-06-04 11:21:44 +00009220 }
Mike Stump1eb44332009-09-09 15:08:12 +00009221
John McCall711c52b2011-01-05 12:14:39 +00009222 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9223 CurBlock->FunctionType = T;
9224
9225 const FunctionType *Fn = T->getAs<FunctionType>();
9226 QualType RetTy = Fn->getResultType();
9227 bool isVariadic =
9228 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9229
John McCallc71a4912010-06-04 19:02:56 +00009230 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009231
John McCall82dc0092010-06-04 11:21:44 +00009232 // Don't allow returning a objc interface by value.
9233 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009234 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009235 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9236 return;
9237 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009238
John McCall82dc0092010-06-04 11:21:44 +00009239 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009240 // return type. TODO: what should we do with declarators like:
9241 // ^ * { ... }
9242 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009243 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009244 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009245 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009246 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009247 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009248
John McCall82dc0092010-06-04 11:21:44 +00009249 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009250 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009251 if (ExplicitSignature) {
9252 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9253 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009254 if (Param->getIdentifier() == 0 &&
9255 !Param->isImplicit() &&
9256 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009257 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009258 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009259 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009260 }
John McCall82dc0092010-06-04 11:21:44 +00009261
9262 // Fake up parameter variables if we have a typedef, like
9263 // ^ fntype { ... }
9264 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9265 for (FunctionProtoType::arg_type_iterator
9266 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9267 ParmVarDecl *Param =
9268 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009269 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009270 *I);
John McCallc71a4912010-06-04 19:02:56 +00009271 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009272 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009273 }
John McCall82dc0092010-06-04 11:21:44 +00009274
John McCallc71a4912010-06-04 19:02:56 +00009275 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009276 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009277 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009278 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9279 CurBlock->TheDecl->param_end(),
9280 /*CheckParameterNames=*/false);
9281 }
9282
John McCall82dc0092010-06-04 11:21:44 +00009283 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009284 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009285
John McCall82dc0092010-06-04 11:21:44 +00009286 // Put the parameter variables in scope. We can bail out immediately
9287 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009288 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009289 return;
9290
Steve Naroff090276f2008-10-10 01:28:17 +00009291 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009292 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9293 (*AI)->setOwningFunction(CurBlock->TheDecl);
9294
Steve Naroff090276f2008-10-10 01:28:17 +00009295 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009296 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009297 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009298
Steve Naroff090276f2008-10-10 01:28:17 +00009299 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009300 }
John McCall7a9813c2010-01-22 00:28:27 +00009301 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009302}
9303
9304/// ActOnBlockError - If there is an error parsing a block, this callback
9305/// is invoked to pop the information about the block from the action impl.
9306void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009307 // Leave the expression-evaluation context.
9308 DiscardCleanupsInEvaluationContext();
9309 PopExpressionEvaluationContext();
9310
Steve Naroff4eb206b2008-09-03 18:15:37 +00009311 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009312 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009313 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009314}
9315
9316/// ActOnBlockStmtExpr - This is called when the body of a block statement
9317/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009318ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009319 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009320 // If blocks are disabled, emit an error.
9321 if (!LangOpts.Blocks)
9322 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009323
John McCall538773c2011-11-11 03:19:12 +00009324 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009325 if (hasAnyUnrecoverableErrorsInThisFunction())
9326 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009327 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9328 PopExpressionEvaluationContext();
9329
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009330 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009331
Steve Naroff090276f2008-10-10 01:28:17 +00009332 PopDeclContext();
9333
Steve Naroff4eb206b2008-09-03 18:15:37 +00009334 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009335 if (!BSI->ReturnType.isNull())
9336 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009337
Mike Stump56925862009-07-28 22:04:01 +00009338 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009339 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009340
John McCall469a1eb2011-02-02 13:00:07 +00009341 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009342 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9343 SmallVector<BlockDecl::Capture, 4> Captures;
9344 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9345 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9346 if (Cap.isThisCapture())
9347 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009348 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009349 Cap.isNested(), Cap.getCopyExpr());
9350 Captures.push_back(NewCap);
9351 }
9352 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9353 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009354
John McCallc71a4912010-06-04 19:02:56 +00009355 // If the user wrote a function type in some form, try to use that.
9356 if (!BSI->FunctionType.isNull()) {
9357 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9358
9359 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9360 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9361
9362 // Turn protoless block types into nullary block types.
9363 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009364 FunctionProtoType::ExtProtoInfo EPI;
9365 EPI.ExtInfo = Ext;
9366 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009367
9368 // Otherwise, if we don't need to change anything about the function type,
9369 // preserve its sugar structure.
9370 } else if (FTy->getResultType() == RetTy &&
9371 (!NoReturn || FTy->getNoReturnAttr())) {
9372 BlockTy = BSI->FunctionType;
9373
9374 // Otherwise, make the minimal modifications to the function type.
9375 } else {
9376 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009377 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9378 EPI.TypeQuals = 0; // FIXME: silently?
9379 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009380 BlockTy = Context.getFunctionType(RetTy,
9381 FPT->arg_type_begin(),
9382 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009383 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009384 }
9385
9386 // If we don't have a function type, just build one from nothing.
9387 } else {
John McCalle23cf432010-12-14 08:05:40 +00009388 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009389 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009390 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009391 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009392
John McCallc71a4912010-06-04 19:02:56 +00009393 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9394 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009395 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009396
Chris Lattner17a78302009-04-19 05:28:12 +00009397 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009398 if (getCurFunction()->NeedsScopeChecking() &&
9399 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009400 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009401
Chris Lattnere476bdc2011-02-17 23:58:47 +00009402 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009403
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009404 computeNRVO(Body, getCurBlock());
9405
Benjamin Kramerd2486192011-07-12 14:11:05 +00009406 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9407 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009408 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009409
John McCall80ee6e82011-11-10 05:35:25 +00009410 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009411 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009412 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009413 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009414 ExprCleanupObjects.push_back(Result->getBlockDecl());
9415 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009416
9417 // It also gets a branch-protected scope if any of the captured
9418 // variables needs destruction.
9419 for (BlockDecl::capture_const_iterator
9420 ci = Result->getBlockDecl()->capture_begin(),
9421 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9422 const VarDecl *var = ci->getVariable();
9423 if (var->getType().isDestructedType() != QualType::DK_none) {
9424 getCurFunction()->setHasBranchProtectedScope();
9425 break;
9426 }
9427 }
John McCall80ee6e82011-11-10 05:35:25 +00009428 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009429
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009430 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009431}
9432
John McCall60d7b3a2010-08-24 06:29:42 +00009433ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009434 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009435 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009436 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009437 GetTypeFromParser(Ty, &TInfo);
9438 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009439}
9440
John McCall60d7b3a2010-08-24 06:29:42 +00009441ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009442 Expr *E, TypeSourceInfo *TInfo,
9443 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009444 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009445
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009446 // Get the va_list type
9447 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009448 if (VaListType->isArrayType()) {
9449 // Deal with implicit array decay; for example, on x86-64,
9450 // va_list is an array, but it's supposed to decay to
9451 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009452 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009453 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009454 ExprResult Result = UsualUnaryConversions(E);
9455 if (Result.isInvalid())
9456 return ExprError();
9457 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009458 } else {
9459 // Otherwise, the va_list argument must be an l-value because
9460 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009461 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009462 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009463 return ExprError();
9464 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009465
Douglas Gregordd027302009-05-19 23:10:31 +00009466 if (!E->isTypeDependent() &&
9467 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009468 return ExprError(Diag(E->getLocStart(),
9469 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009470 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009471 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009472
David Majnemer0adde122011-06-14 05:17:32 +00009473 if (!TInfo->getType()->isDependentType()) {
9474 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009475 diag::err_second_parameter_to_va_arg_incomplete,
9476 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009477 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009478
David Majnemer0adde122011-06-14 05:17:32 +00009479 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009480 TInfo->getType(),
9481 diag::err_second_parameter_to_va_arg_abstract,
9482 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009483 return ExprError();
9484
Douglas Gregor4eb75222011-07-30 06:45:27 +00009485 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009486 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009487 TInfo->getType()->isObjCLifetimeType()
9488 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9489 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009490 << TInfo->getType()
9491 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009492 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009493
9494 // Check for va_arg where arguments of the given type will be promoted
9495 // (i.e. this va_arg is guaranteed to have undefined behavior).
9496 QualType PromoteType;
9497 if (TInfo->getType()->isPromotableIntegerType()) {
9498 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9499 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9500 PromoteType = QualType();
9501 }
9502 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9503 PromoteType = Context.DoubleTy;
9504 if (!PromoteType.isNull())
9505 Diag(TInfo->getTypeLoc().getBeginLoc(),
9506 diag::warn_second_parameter_to_va_arg_never_compatible)
9507 << TInfo->getType()
9508 << PromoteType
9509 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009510 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009511
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009512 QualType T = TInfo->getType().getNonLValueExprType(Context);
9513 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009514}
9515
John McCall60d7b3a2010-08-24 06:29:42 +00009516ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009517 // The type of __null will be int or long, depending on the size of
9518 // pointers on the target.
9519 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009520 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9521 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009522 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009523 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009524 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009525 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009526 Ty = Context.LongLongTy;
9527 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009528 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009529 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009530
Sebastian Redlf53597f2009-03-15 17:47:39 +00009531 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009532}
9533
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009534static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009535 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009536 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009537 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009538
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009539 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9540 if (!PT)
9541 return;
9542
9543 // Check if the destination is of type 'id'.
9544 if (!PT->isObjCIdType()) {
9545 // Check if the destination is the 'NSString' interface.
9546 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9547 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9548 return;
9549 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009550
John McCall4b9c2d22011-11-06 09:01:30 +00009551 // Ignore any parens, implicit casts (should only be
9552 // array-to-pointer decays), and not-so-opaque values. The last is
9553 // important for making this trigger for property assignments.
9554 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9555 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9556 if (OV->getSourceExpr())
9557 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9558
9559 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009560 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009561 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009562
Douglas Gregor849b2432010-03-31 17:46:05 +00009563 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009564}
9565
Chris Lattner5cf216b2008-01-04 18:04:52 +00009566bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9567 SourceLocation Loc,
9568 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009569 Expr *SrcExpr, AssignmentAction Action,
9570 bool *Complained) {
9571 if (Complained)
9572 *Complained = false;
9573
Chris Lattner5cf216b2008-01-04 18:04:52 +00009574 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009575 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009576 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009577 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009578 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009579 ConversionFixItGenerator ConvHints;
9580 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009581 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009582
Chris Lattner5cf216b2008-01-04 18:04:52 +00009583 switch (ConvTy) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00009584 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009585 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009586 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009587 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9588 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009589 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009590 case IntToPointer:
9591 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009592 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9593 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009594 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009595 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009596 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009597 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009598 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9599 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009600 if (Hint.isNull() && !CheckInferredResultType) {
9601 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9602 }
9603 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009604 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009605 case IncompatiblePointerSign:
9606 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9607 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009608 case FunctionVoidPointer:
9609 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9610 break;
John McCall86c05f32011-02-01 00:10:29 +00009611 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009612 // Perform array-to-pointer decay if necessary.
9613 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9614
John McCall86c05f32011-02-01 00:10:29 +00009615 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9616 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9617 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9618 DiagKind = diag::err_typecheck_incompatible_address_space;
9619 break;
John McCallf85e1932011-06-15 23:02:42 +00009620
9621
9622 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009623 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009624 break;
John McCall86c05f32011-02-01 00:10:29 +00009625 }
9626
9627 llvm_unreachable("unknown error case for discarding qualifiers!");
9628 // fallthrough
9629 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009630 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009631 // If the qualifiers lost were because we were applying the
9632 // (deprecated) C++ conversion from a string literal to a char*
9633 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9634 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009635 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009636 // bit of refactoring (so that the second argument is an
9637 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009638 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009639 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009640 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009641 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9642 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009643 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9644 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009645 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009646 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009647 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009648 case IntToBlockPointer:
9649 DiagKind = diag::err_int_to_block_pointer;
9650 break;
9651 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009652 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009653 break;
Steve Naroff39579072008-10-14 22:18:38 +00009654 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009655 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009656 // it can give a more specific diagnostic.
9657 DiagKind = diag::warn_incompatible_qualified_id;
9658 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009659 case IncompatibleVectors:
9660 DiagKind = diag::warn_incompatible_vectors;
9661 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009662 case IncompatibleObjCWeakRef:
9663 DiagKind = diag::err_arc_weak_unavailable_assign;
9664 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009665 case Incompatible:
9666 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009667 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9668 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009669 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009670 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009671 break;
9672 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009673
Douglas Gregord4eea832010-04-09 00:35:39 +00009674 QualType FirstType, SecondType;
9675 switch (Action) {
9676 case AA_Assigning:
9677 case AA_Initializing:
9678 // The destination type comes first.
9679 FirstType = DstType;
9680 SecondType = SrcType;
9681 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009682
Douglas Gregord4eea832010-04-09 00:35:39 +00009683 case AA_Returning:
9684 case AA_Passing:
9685 case AA_Converting:
9686 case AA_Sending:
9687 case AA_Casting:
9688 // The source type comes first.
9689 FirstType = SrcType;
9690 SecondType = DstType;
9691 break;
9692 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009693
Anna Zaks67221552011-07-28 19:51:27 +00009694 PartialDiagnostic FDiag = PDiag(DiagKind);
9695 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9696
9697 // If we can fix the conversion, suggest the FixIts.
9698 assert(ConvHints.isNull() || Hint.isNull());
9699 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009700 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9701 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009702 FDiag << *HI;
9703 } else {
9704 FDiag << Hint;
9705 }
9706 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9707
Richard Trieu6efd4c52011-11-23 22:32:32 +00009708 if (MayHaveFunctionDiff)
9709 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9710
Anna Zaks67221552011-07-28 19:51:27 +00009711 Diag(Loc, FDiag);
9712
Richard Trieu6efd4c52011-11-23 22:32:32 +00009713 if (SecondType == Context.OverloadTy)
9714 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9715 FirstType);
9716
Douglas Gregor926df6c2011-06-11 01:09:30 +00009717 if (CheckInferredResultType)
9718 EmitRelatedResultTypeNote(SrcExpr);
9719
Douglas Gregora41a8c52010-04-22 00:20:18 +00009720 if (Complained)
9721 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009722 return isInvalid;
9723}
Anders Carlssone21555e2008-11-30 19:50:32 +00009724
Richard Smith282e7e62012-02-04 09:53:13 +00009725ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9726 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009727 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9728 public:
9729 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9730 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9731 }
9732 } Diagnoser;
9733
9734 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9735}
9736
9737ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9738 llvm::APSInt *Result,
9739 unsigned DiagID,
9740 bool AllowFold) {
9741 class IDDiagnoser : public VerifyICEDiagnoser {
9742 unsigned DiagID;
9743
9744 public:
9745 IDDiagnoser(unsigned DiagID)
9746 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9747
9748 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9749 S.Diag(Loc, DiagID) << SR;
9750 }
9751 } Diagnoser(DiagID);
9752
9753 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9754}
9755
9756void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9757 SourceRange SR) {
9758 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009759}
9760
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009761ExprResult
9762Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009763 VerifyICEDiagnoser &Diagnoser,
9764 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009765 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009766
David Blaikie4e4d0842012-03-11 07:00:24 +00009767 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009768 // C++11 [expr.const]p5:
9769 // If an expression of literal class type is used in a context where an
9770 // integral constant expression is required, then that class type shall
9771 // have a single non-explicit conversion function to an integral or
9772 // unscoped enumeration type
9773 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009774 if (!Diagnoser.Suppress) {
9775 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9776 public:
9777 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9778
9779 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9780 QualType T) {
9781 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9782 }
9783
9784 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9785 SourceLocation Loc,
9786 QualType T) {
9787 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9788 }
9789
9790 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9791 SourceLocation Loc,
9792 QualType T,
9793 QualType ConvTy) {
9794 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9795 }
9796
9797 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9798 CXXConversionDecl *Conv,
9799 QualType ConvTy) {
9800 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9801 << ConvTy->isEnumeralType() << ConvTy;
9802 }
9803
9804 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9805 QualType T) {
9806 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9807 }
9808
9809 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9810 CXXConversionDecl *Conv,
9811 QualType ConvTy) {
9812 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9813 << ConvTy->isEnumeralType() << ConvTy;
9814 }
9815
9816 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9817 SourceLocation Loc,
9818 QualType T,
9819 QualType ConvTy) {
9820 return DiagnosticBuilder::getEmpty();
9821 }
9822 } ConvertDiagnoser;
9823
9824 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9825 ConvertDiagnoser,
9826 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +00009827 } else {
9828 // The caller wants to silently enquire whether this is an ICE. Don't
9829 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009830 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9831 public:
9832 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9833
9834 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9835 QualType T) {
9836 return DiagnosticBuilder::getEmpty();
9837 }
9838
9839 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9840 SourceLocation Loc,
9841 QualType T) {
9842 return DiagnosticBuilder::getEmpty();
9843 }
9844
9845 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9846 SourceLocation Loc,
9847 QualType T,
9848 QualType ConvTy) {
9849 return DiagnosticBuilder::getEmpty();
9850 }
9851
9852 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9853 CXXConversionDecl *Conv,
9854 QualType ConvTy) {
9855 return DiagnosticBuilder::getEmpty();
9856 }
9857
9858 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9859 QualType T) {
9860 return DiagnosticBuilder::getEmpty();
9861 }
9862
9863 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9864 CXXConversionDecl *Conv,
9865 QualType ConvTy) {
9866 return DiagnosticBuilder::getEmpty();
9867 }
9868
9869 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9870 SourceLocation Loc,
9871 QualType T,
9872 QualType ConvTy) {
9873 return DiagnosticBuilder::getEmpty();
9874 }
9875 } ConvertDiagnoser;
9876
9877 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9878 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009879 }
9880 if (Converted.isInvalid())
9881 return Converted;
9882 E = Converted.take();
9883 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9884 return ExprError();
9885 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9886 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009887 if (!Diagnoser.Suppress)
9888 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +00009889 return ExprError();
9890 }
9891
Richard Smithdaaefc52011-12-14 23:32:26 +00009892 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9893 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +00009894 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +00009895 if (Result)
9896 *Result = E->EvaluateKnownConstInt(Context);
9897 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009898 }
9899
Anders Carlssone21555e2008-11-30 19:50:32 +00009900 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +00009901 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9902 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +00009903
Richard Smithdaaefc52011-12-14 23:32:26 +00009904 // Try to evaluate the expression, and produce diagnostics explaining why it's
9905 // not a constant expression as a side-effect.
9906 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9907 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9908
9909 // In C++11, we can rely on diagnostics being produced for any expression
9910 // which is not a constant expression. If no diagnostics were produced, then
9911 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00009912 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009913 if (Result)
9914 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +00009915 return Owned(E);
9916 }
9917
9918 // If our only note is the usual "invalid subexpression" note, just point
9919 // the caret at its location rather than producing an essentially
9920 // redundant note.
9921 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9922 diag::note_invalid_subexpr_in_const_expr) {
9923 DiagLoc = Notes[0].first;
9924 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +00009925 }
9926
9927 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009928 if (!Diagnoser.Suppress) {
9929 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +00009930 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9931 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +00009932 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009933
Richard Smith282e7e62012-02-04 09:53:13 +00009934 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +00009935 }
9936
Douglas Gregorab41fe92012-05-04 22:38:52 +00009937 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +00009938 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9939 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009940
Anders Carlssone21555e2008-11-30 19:50:32 +00009941 if (Result)
9942 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +00009943 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +00009944}
Douglas Gregore0762c92009-06-19 23:52:42 +00009945
Eli Friedmanef331b72012-01-20 01:26:23 +00009946namespace {
9947 // Handle the case where we conclude a expression which we speculatively
9948 // considered to be unevaluated is actually evaluated.
9949 class TransformToPE : public TreeTransform<TransformToPE> {
9950 typedef TreeTransform<TransformToPE> BaseTransform;
9951
9952 public:
9953 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9954
9955 // Make sure we redo semantic analysis
9956 bool AlwaysRebuild() { return true; }
9957
Eli Friedman56ff2832012-02-06 23:29:57 +00009958 // Make sure we handle LabelStmts correctly.
9959 // FIXME: This does the right thing, but maybe we need a more general
9960 // fix to TreeTransform?
9961 StmtResult TransformLabelStmt(LabelStmt *S) {
9962 S->getDecl()->setStmt(0);
9963 return BaseTransform::TransformLabelStmt(S);
9964 }
9965
Eli Friedmanef331b72012-01-20 01:26:23 +00009966 // We need to special-case DeclRefExprs referring to FieldDecls which
9967 // are not part of a member pointer formation; normal TreeTransforming
9968 // doesn't catch this case because of the way we represent them in the AST.
9969 // FIXME: This is a bit ugly; is it really the best way to handle this
9970 // case?
9971 //
9972 // Error on DeclRefExprs referring to FieldDecls.
9973 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9974 if (isa<FieldDecl>(E->getDecl()) &&
9975 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9976 return SemaRef.Diag(E->getLocation(),
9977 diag::err_invalid_non_static_member_use)
9978 << E->getDecl() << E->getSourceRange();
9979
9980 return BaseTransform::TransformDeclRefExpr(E);
9981 }
9982
9983 // Exception: filter out member pointer formation
9984 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9985 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9986 return E;
9987
9988 return BaseTransform::TransformUnaryOperator(E);
9989 }
9990
Douglas Gregore2c59132012-02-09 08:14:43 +00009991 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9992 // Lambdas never need to be transformed.
9993 return E;
9994 }
Eli Friedmanef331b72012-01-20 01:26:23 +00009995 };
Eli Friedman93c878e2012-01-18 01:05:54 +00009996}
9997
Eli Friedmanef331b72012-01-20 01:26:23 +00009998ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +00009999 assert(ExprEvalContexts.back().Context == Unevaluated &&
10000 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010001 ExprEvalContexts.back().Context =
10002 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10003 if (ExprEvalContexts.back().Context == Unevaluated)
10004 return E;
10005 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010006}
10007
Douglas Gregor2afce722009-11-26 00:44:06 +000010008void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010009Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010010 Decl *LambdaContextDecl,
10011 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010012 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010013 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010014 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010015 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010016 LambdaContextDecl,
10017 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010018 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010019 if (!MaybeODRUseExprs.empty())
10020 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010021}
10022
Richard Trieu67e29332011-08-02 04:35:43 +000010023void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010024 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010025
Douglas Gregore2c59132012-02-09 08:14:43 +000010026 if (!Rec.Lambdas.empty()) {
10027 if (Rec.Context == Unevaluated) {
10028 // C++11 [expr.prim.lambda]p2:
10029 // A lambda-expression shall not appear in an unevaluated operand
10030 // (Clause 5).
10031 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10032 Diag(Rec.Lambdas[I]->getLocStart(),
10033 diag::err_lambda_unevaluated_operand);
10034 } else {
10035 // Mark the capture expressions odr-used. This was deferred
10036 // during lambda expression creation.
10037 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10038 LambdaExpr *Lambda = Rec.Lambdas[I];
10039 for (LambdaExpr::capture_init_iterator
10040 C = Lambda->capture_init_begin(),
10041 CEnd = Lambda->capture_init_end();
10042 C != CEnd; ++C) {
10043 MarkDeclarationsReferencedInExpr(*C);
10044 }
10045 }
10046 }
10047 }
10048
Douglas Gregor2afce722009-11-26 00:44:06 +000010049 // When are coming out of an unevaluated context, clear out any
10050 // temporaries that we may have created as part of the evaluation of
10051 // the expression in that context: they aren't relevant because they
10052 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010053 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010054 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10055 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010056 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010057 CleanupVarDeclMarking();
10058 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010059 // Otherwise, merge the contexts together.
10060 } else {
10061 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010062 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10063 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010064 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010065
10066 // Pop the current expression evaluation context off the stack.
10067 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010068}
Douglas Gregore0762c92009-06-19 23:52:42 +000010069
John McCallf85e1932011-06-15 23:02:42 +000010070void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010071 ExprCleanupObjects.erase(
10072 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10073 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010074 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010075 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010076}
10077
Eli Friedman71b8fb52012-01-21 01:01:51 +000010078ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10079 if (!E->getType()->isVariablyModifiedType())
10080 return E;
10081 return TranformToPotentiallyEvaluated(E);
10082}
10083
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010084static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010085 // Do not mark anything as "used" within a dependent context; wait for
10086 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010087 if (SemaRef.CurContext->isDependentContext())
10088 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010089
Eli Friedman5f2987c2012-02-02 03:46:19 +000010090 switch (SemaRef.ExprEvalContexts.back().Context) {
10091 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010092 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010093 // (Depending on how you read the standard, we actually do need to do
10094 // something here for null pointer constants, but the standard's
10095 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010096 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010097
Eli Friedman5f2987c2012-02-02 03:46:19 +000010098 case Sema::ConstantEvaluated:
10099 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010100 // We are in a potentially evaluated expression (or a constant-expression
10101 // in C++03); we need to do implicit template instantiation, implicitly
10102 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010103 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010104
Eli Friedman5f2987c2012-02-02 03:46:19 +000010105 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010106 // Referenced declarations will only be used if the construct in the
10107 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010108 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010109 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010110 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010111}
10112
10113/// \brief Mark a function referenced, and check whether it is odr-used
10114/// (C++ [basic.def.odr]p2, C99 6.9p3)
10115void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10116 assert(Func && "No function?");
10117
10118 Func->setReferenced();
10119
Richard Smith57b9c4e2012-02-14 22:25:15 +000010120 // Don't mark this function as used multiple times, unless it's a constexpr
10121 // function which we need to instantiate.
10122 if (Func->isUsed(false) &&
10123 !(Func->isConstexpr() && !Func->getBody() &&
10124 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010125 return;
10126
10127 if (!IsPotentiallyEvaluatedContext(*this))
10128 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010129
Douglas Gregore0762c92009-06-19 23:52:42 +000010130 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010131 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010132 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010133 if (Constructor->isDefaultConstructor()) {
10134 if (Constructor->isTrivial())
10135 return;
10136 if (!Constructor->isUsed(false))
10137 DefineImplicitDefaultConstructor(Loc, Constructor);
10138 } else if (Constructor->isCopyConstructor()) {
10139 if (!Constructor->isUsed(false))
10140 DefineImplicitCopyConstructor(Loc, Constructor);
10141 } else if (Constructor->isMoveConstructor()) {
10142 if (!Constructor->isUsed(false))
10143 DefineImplicitMoveConstructor(Loc, Constructor);
10144 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010145 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010146
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010147 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010148 } else if (CXXDestructorDecl *Destructor =
10149 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010150 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10151 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010152 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010153 if (Destructor->isVirtual())
10154 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010155 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010156 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10157 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010158 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010159 if (!MethodDecl->isUsed(false)) {
10160 if (MethodDecl->isCopyAssignmentOperator())
10161 DefineImplicitCopyAssignment(Loc, MethodDecl);
10162 else
10163 DefineImplicitMoveAssignment(Loc, MethodDecl);
10164 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010165 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10166 MethodDecl->getParent()->isLambda()) {
10167 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10168 if (Conversion->isLambdaToBlockPointerConversion())
10169 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10170 else
10171 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010172 } else if (MethodDecl->isVirtual())
10173 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010174 }
John McCall15e310a2011-02-19 02:53:41 +000010175
Eli Friedman5f2987c2012-02-02 03:46:19 +000010176 // Recursive functions should be marked when used from another function.
10177 // FIXME: Is this really right?
10178 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010179
Richard Smithe6975e92012-04-17 00:58:00 +000010180 // Instantiate the exception specification for any function which is
10181 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010182 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10183 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +000010184 InstantiateExceptionSpec(Loc, Func);
10185
Eli Friedman5f2987c2012-02-02 03:46:19 +000010186 // Implicit instantiation of function templates and member functions of
10187 // class templates.
10188 if (Func->isImplicitlyInstantiable()) {
10189 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010190 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010191 if (FunctionTemplateSpecializationInfo *SpecInfo
10192 = Func->getTemplateSpecializationInfo()) {
10193 if (SpecInfo->getPointOfInstantiation().isInvalid())
10194 SpecInfo->setPointOfInstantiation(Loc);
10195 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010196 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010197 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010198 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10199 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010200 } else if (MemberSpecializationInfo *MSInfo
10201 = Func->getMemberSpecializationInfo()) {
10202 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010203 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010204 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010205 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010206 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010207 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10208 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010209 }
Mike Stump1eb44332009-09-09 15:08:12 +000010210
Richard Smith57b9c4e2012-02-14 22:25:15 +000010211 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010212 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10213 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010214 PendingLocalImplicitInstantiations.push_back(
10215 std::make_pair(Func, PointOfInstantiation));
10216 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010217 // Do not defer instantiations of constexpr functions, to avoid the
10218 // expression evaluator needing to call back into Sema if it sees a
10219 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010220 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010221 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010222 PendingInstantiations.push_back(std::make_pair(Func,
10223 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010224 // Notify the consumer that a function was implicitly instantiated.
10225 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10226 }
John McCall15e310a2011-02-19 02:53:41 +000010227 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010228 } else {
10229 // Walk redefinitions, as some of them may be instantiable.
10230 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10231 e(Func->redecls_end()); i != e; ++i) {
10232 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10233 MarkFunctionReferenced(Loc, *i);
10234 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010235 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010236
10237 // Keep track of used but undefined functions.
10238 if (!Func->isPure() && !Func->hasBody() &&
10239 Func->getLinkage() != ExternalLinkage) {
10240 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10241 if (old.isInvalid()) old = Loc;
10242 }
10243
10244 Func->setUsed(true);
10245}
10246
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010247static void
10248diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10249 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010250 DeclContext *VarDC = var->getDeclContext();
10251
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010252 // If the parameter still belongs to the translation unit, then
10253 // we're actually just using one parameter in the declaration of
10254 // the next.
10255 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010256 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010257 return;
10258
Eli Friedman0a294222012-02-07 00:15:00 +000010259 // For C code, don't diagnose about capture if we're not actually in code
10260 // right now; it's impossible to write a non-constant expression outside of
10261 // function context, so we'll get other (more useful) diagnostics later.
10262 //
10263 // For C++, things get a bit more nasty... it would be nice to suppress this
10264 // diagnostic for certain cases like using a local variable in an array bound
10265 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010266 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010267 return;
10268
Eli Friedman0a294222012-02-07 00:15:00 +000010269 if (isa<CXXMethodDecl>(VarDC) &&
10270 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10271 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10272 << var->getIdentifier();
10273 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10274 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10275 << var->getIdentifier() << fn->getDeclName();
10276 } else if (isa<BlockDecl>(VarDC)) {
10277 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10278 << var->getIdentifier();
10279 } else {
10280 // FIXME: Is there any other context where a local variable can be
10281 // declared?
10282 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10283 << var->getIdentifier();
10284 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010285
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010286 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10287 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010288
10289 // FIXME: Add additional diagnostic info about class etc. which prevents
10290 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010291}
10292
Douglas Gregorf8af9822012-02-12 18:42:33 +000010293/// \brief Capture the given variable in the given lambda expression.
10294static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010295 VarDecl *Var, QualType FieldType,
10296 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010297 SourceLocation Loc,
10298 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010299 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010300
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010301 // Build the non-static data member.
10302 FieldDecl *Field
10303 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10304 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010305 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010306 Field->setImplicit(true);
10307 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010308 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010309
10310 // C++11 [expr.prim.lambda]p21:
10311 // When the lambda-expression is evaluated, the entities that
10312 // are captured by copy are used to direct-initialize each
10313 // corresponding non-static data member of the resulting closure
10314 // object. (For array members, the array elements are
10315 // direct-initialized in increasing subscript order.) These
10316 // initializations are performed in the (unspecified) order in
10317 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010318
Douglas Gregore2c59132012-02-09 08:14:43 +000010319 // Introduce a new evaluation context for the initialization, so
10320 // that temporaries introduced as part of the capture are retained
10321 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010322 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10323
Douglas Gregor73d90922012-02-10 09:26:04 +000010324 // C++ [expr.prim.labda]p12:
10325 // An entity captured by a lambda-expression is odr-used (3.2) in
10326 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010327 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10328 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010329 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010330 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010331
10332 // When the field has array type, create index variables for each
10333 // dimension of the array. We use these index variables to subscript
10334 // the source array, and other clients (e.g., CodeGen) will perform
10335 // the necessary iteration with these index variables.
10336 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010337 QualType BaseType = FieldType;
10338 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010339 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010340 while (const ConstantArrayType *Array
10341 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010342 // Create the iteration variable for this array index.
10343 IdentifierInfo *IterationVarName = 0;
10344 {
10345 SmallString<8> Str;
10346 llvm::raw_svector_ostream OS(Str);
10347 OS << "__i" << IndexVariables.size();
10348 IterationVarName = &S.Context.Idents.get(OS.str());
10349 }
10350 VarDecl *IterationVar
10351 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10352 IterationVarName, SizeType,
10353 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10354 SC_None, SC_None);
10355 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010356 LSI->ArrayIndexVars.push_back(IterationVar);
10357
Douglas Gregor18fe0842012-02-09 02:45:47 +000010358 // Create a reference to the iteration variable.
10359 ExprResult IterationVarRef
10360 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10361 assert(!IterationVarRef.isInvalid() &&
10362 "Reference to invented variable cannot fail!");
10363 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10364 assert(!IterationVarRef.isInvalid() &&
10365 "Conversion of invented variable cannot fail!");
10366
10367 // Subscript the array with this iteration variable.
10368 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10369 Ref, Loc, IterationVarRef.take(), Loc);
10370 if (Subscript.isInvalid()) {
10371 S.CleanupVarDeclMarking();
10372 S.DiscardCleanupsInEvaluationContext();
10373 S.PopExpressionEvaluationContext();
10374 return ExprError();
10375 }
10376
10377 Ref = Subscript.take();
10378 BaseType = Array->getElementType();
10379 }
10380
10381 // Construct the entity that we will be initializing. For an array, this
10382 // will be first element in the array, which may require several levels
10383 // of array-subscript entities.
10384 SmallVector<InitializedEntity, 4> Entities;
10385 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010386 Entities.push_back(
10387 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010388 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10389 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10390 0,
10391 Entities.back()));
10392
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010393 InitializationKind InitKind
10394 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010395 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010396 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010397 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10398 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010399 MultiExprArg(S, &Ref, 1));
10400
10401 // If this initialization requires any cleanups (e.g., due to a
10402 // default argument to a copy constructor), note that for the
10403 // lambda.
10404 if (S.ExprNeedsCleanups)
10405 LSI->ExprNeedsCleanups = true;
10406
10407 // Exit the expression evaluation context used for the capture.
10408 S.CleanupVarDeclMarking();
10409 S.DiscardCleanupsInEvaluationContext();
10410 S.PopExpressionEvaluationContext();
10411 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010412}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010413
Douglas Gregor999713e2012-02-18 09:37:24 +000010414bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10415 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10416 bool BuildAndDiagnose,
10417 QualType &CaptureType,
10418 QualType &DeclRefType) {
10419 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010420
Eli Friedmanb942cb22012-02-03 22:47:37 +000010421 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010422 if (Var->getDeclContext() == DC) return true;
10423 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010424
Douglas Gregorf8af9822012-02-12 18:42:33 +000010425 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010426
Douglas Gregor999713e2012-02-18 09:37:24 +000010427 // Walk up the stack to determine whether we can capture the variable,
10428 // performing the "simple" checks that don't depend on type. We stop when
10429 // we've either hit the declared scope of the variable or find an existing
10430 // capture of that variable.
10431 CaptureType = Var->getType();
10432 DeclRefType = CaptureType.getNonReferenceType();
10433 bool Explicit = (Kind != TryCapture_Implicit);
10434 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010435 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010436 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010437 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010438 DeclContext *ParentDC;
10439 if (isa<BlockDecl>(DC))
10440 ParentDC = DC->getParent();
10441 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010442 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010443 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10444 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010445 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010446 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010447 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010448 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010449 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010450
Eli Friedmanb942cb22012-02-03 22:47:37 +000010451 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010452 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010453
Eli Friedmanb942cb22012-02-03 22:47:37 +000010454 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010455 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010456 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010457 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010458
10459 // Retrieve the capture type for this variable.
10460 CaptureType = CSI->getCapture(Var).getCaptureType();
10461
10462 // Compute the type of an expression that refers to this variable.
10463 DeclRefType = CaptureType.getNonReferenceType();
10464
10465 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10466 if (Cap.isCopyCapture() &&
10467 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10468 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010469 break;
10470 }
10471
Douglas Gregorf8af9822012-02-12 18:42:33 +000010472 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010473 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010474
10475 // Lambdas are not allowed to capture unnamed variables
10476 // (e.g. anonymous unions).
10477 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10478 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010479 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010480 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010481 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10482 Diag(Var->getLocation(), diag::note_declared_at);
10483 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010484 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010485 }
10486
10487 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010488 if (Var->getType()->isVariablyModifiedType()) {
10489 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010490 if (IsBlock)
10491 Diag(Loc, diag::err_ref_vm_type);
10492 else
10493 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10494 Diag(Var->getLocation(), diag::note_previous_decl)
10495 << Var->getDeclName();
10496 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010497 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010498 }
10499
Eli Friedmanb942cb22012-02-03 22:47:37 +000010500 // Lambdas are not allowed to capture __block variables; they don't
10501 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010502 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010503 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010504 Diag(Loc, diag::err_lambda_capture_block)
10505 << Var->getDeclName();
10506 Diag(Var->getLocation(), diag::note_previous_decl)
10507 << Var->getDeclName();
10508 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010509 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010510 }
10511
Douglas Gregorf8af9822012-02-12 18:42:33 +000010512 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10513 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010514 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010515 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10516 Diag(Var->getLocation(), diag::note_previous_decl)
10517 << Var->getDeclName();
10518 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10519 diag::note_lambda_decl);
10520 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010521 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010522 }
10523
10524 FunctionScopesIndex--;
10525 DC = ParentDC;
10526 Explicit = false;
10527 } while (!Var->getDeclContext()->Equals(DC));
10528
Douglas Gregor999713e2012-02-18 09:37:24 +000010529 // Walk back down the scope stack, computing the type of the capture at
10530 // each step, checking type-specific requirements, and adding captures if
10531 // requested.
10532 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10533 ++I) {
10534 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010535
Douglas Gregor999713e2012-02-18 09:37:24 +000010536 // Compute the type of the capture and of a reference to the capture within
10537 // this scope.
10538 if (isa<BlockScopeInfo>(CSI)) {
10539 Expr *CopyExpr = 0;
10540 bool ByRef = false;
10541
10542 // Blocks are not allowed to capture arrays.
10543 if (CaptureType->isArrayType()) {
10544 if (BuildAndDiagnose) {
10545 Diag(Loc, diag::err_ref_array_type);
10546 Diag(Var->getLocation(), diag::note_previous_decl)
10547 << Var->getDeclName();
10548 }
10549 return true;
10550 }
10551
John McCall100c6492012-03-30 05:23:48 +000010552 // Forbid the block-capture of autoreleasing variables.
10553 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10554 if (BuildAndDiagnose) {
10555 Diag(Loc, diag::err_arc_autoreleasing_capture)
10556 << /*block*/ 0;
10557 Diag(Var->getLocation(), diag::note_previous_decl)
10558 << Var->getDeclName();
10559 }
10560 return true;
10561 }
10562
Douglas Gregor999713e2012-02-18 09:37:24 +000010563 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10564 // Block capture by reference does not change the capture or
10565 // declaration reference types.
10566 ByRef = true;
10567 } else {
10568 // Block capture by copy introduces 'const'.
10569 CaptureType = CaptureType.getNonReferenceType().withConst();
10570 DeclRefType = CaptureType;
10571
David Blaikie4e4d0842012-03-11 07:00:24 +000010572 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010573 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10574 // The capture logic needs the destructor, so make sure we mark it.
10575 // Usually this is unnecessary because most local variables have
10576 // their destructors marked at declaration time, but parameters are
10577 // an exception because it's technically only the call site that
10578 // actually requires the destructor.
10579 if (isa<ParmVarDecl>(Var))
10580 FinalizeVarWithDestructor(Var, Record);
10581
10582 // According to the blocks spec, the capture of a variable from
10583 // the stack requires a const copy constructor. This is not true
10584 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010585 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010586 DeclRefType.withConst(),
10587 VK_LValue, Loc);
10588 ExprResult Result
10589 = PerformCopyInitialization(
10590 InitializedEntity::InitializeBlock(Var->getLocation(),
10591 CaptureType, false),
10592 Loc, Owned(DeclRef));
10593
10594 // Build a full-expression copy expression if initialization
10595 // succeeded and used a non-trivial constructor. Recover from
10596 // errors by pretending that the copy isn't necessary.
10597 if (!Result.isInvalid() &&
10598 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10599 ->isTrivial()) {
10600 Result = MaybeCreateExprWithCleanups(Result);
10601 CopyExpr = Result.take();
10602 }
10603 }
10604 }
10605 }
10606
10607 // Actually capture the variable.
10608 if (BuildAndDiagnose)
10609 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10610 SourceLocation(), CaptureType, CopyExpr);
10611 Nested = true;
10612 continue;
10613 }
Douglas Gregor68932842012-02-18 05:51:20 +000010614
Douglas Gregor999713e2012-02-18 09:37:24 +000010615 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10616
10617 // Determine whether we are capturing by reference or by value.
10618 bool ByRef = false;
10619 if (I == N - 1 && Kind != TryCapture_Implicit) {
10620 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010621 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010622 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010623 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010624
10625 // Compute the type of the field that will capture this variable.
10626 if (ByRef) {
10627 // C++11 [expr.prim.lambda]p15:
10628 // An entity is captured by reference if it is implicitly or
10629 // explicitly captured but not captured by copy. It is
10630 // unspecified whether additional unnamed non-static data
10631 // members are declared in the closure type for entities
10632 // captured by reference.
10633 //
10634 // FIXME: It is not clear whether we want to build an lvalue reference
10635 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10636 // to do the former, while EDG does the latter. Core issue 1249 will
10637 // clarify, but for now we follow GCC because it's a more permissive and
10638 // easily defensible position.
10639 CaptureType = Context.getLValueReferenceType(DeclRefType);
10640 } else {
10641 // C++11 [expr.prim.lambda]p14:
10642 // For each entity captured by copy, an unnamed non-static
10643 // data member is declared in the closure type. The
10644 // declaration order of these members is unspecified. The type
10645 // of such a data member is the type of the corresponding
10646 // captured entity if the entity is not a reference to an
10647 // object, or the referenced type otherwise. [Note: If the
10648 // captured entity is a reference to a function, the
10649 // corresponding data member is also a reference to a
10650 // function. - end note ]
10651 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10652 if (!RefType->getPointeeType()->isFunctionType())
10653 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010654 }
John McCall100c6492012-03-30 05:23:48 +000010655
10656 // Forbid the lambda copy-capture of autoreleasing variables.
10657 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10658 if (BuildAndDiagnose) {
10659 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10660 Diag(Var->getLocation(), diag::note_previous_decl)
10661 << Var->getDeclName();
10662 }
10663 return true;
10664 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010665 }
10666
Douglas Gregor999713e2012-02-18 09:37:24 +000010667 // Capture this variable in the lambda.
10668 Expr *CopyExpr = 0;
10669 if (BuildAndDiagnose) {
10670 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010671 DeclRefType, Loc,
10672 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010673 if (!Result.isInvalid())
10674 CopyExpr = Result.take();
10675 }
10676
10677 // Compute the type of a reference to this captured variable.
10678 if (ByRef)
10679 DeclRefType = CaptureType.getNonReferenceType();
10680 else {
10681 // C++ [expr.prim.lambda]p5:
10682 // The closure type for a lambda-expression has a public inline
10683 // function call operator [...]. This function call operator is
10684 // declared const (9.3.1) if and only if the lambda-expression’s
10685 // parameter-declaration-clause is not followed by mutable.
10686 DeclRefType = CaptureType.getNonReferenceType();
10687 if (!LSI->Mutable && !CaptureType->isReferenceType())
10688 DeclRefType.addConst();
10689 }
10690
10691 // Add the capture.
10692 if (BuildAndDiagnose)
10693 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10694 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010695 Nested = true;
10696 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010697
10698 return false;
10699}
10700
10701bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10702 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10703 QualType CaptureType;
10704 QualType DeclRefType;
10705 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10706 /*BuildAndDiagnose=*/true, CaptureType,
10707 DeclRefType);
10708}
10709
10710QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10711 QualType CaptureType;
10712 QualType DeclRefType;
10713
10714 // Determine whether we can capture this variable.
10715 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10716 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10717 return QualType();
10718
10719 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010720}
10721
Eli Friedmand2cce132012-02-02 23:15:15 +000010722static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10723 SourceLocation Loc) {
10724 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010725 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010726 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010727 Var->getLinkage() != ExternalLinkage &&
10728 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010729 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10730 if (old.isInvalid()) old = Loc;
10731 }
10732
Douglas Gregor999713e2012-02-18 09:37:24 +000010733 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010734
Eli Friedmand2cce132012-02-02 23:15:15 +000010735 Var->setUsed(true);
10736}
10737
10738void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10739 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10740 // an object that satisfies the requirements for appearing in a
10741 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10742 // is immediately applied." This function handles the lvalue-to-rvalue
10743 // conversion part.
10744 MaybeODRUseExprs.erase(E->IgnoreParens());
10745}
10746
Eli Friedmanac626012012-02-29 03:16:56 +000010747ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10748 if (!Res.isUsable())
10749 return Res;
10750
10751 // If a constant-expression is a reference to a variable where we delay
10752 // deciding whether it is an odr-use, just assume we will apply the
10753 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10754 // (a non-type template argument), we have special handling anyway.
10755 UpdateMarkingForLValueToRValue(Res.get());
10756 return Res;
10757}
10758
Eli Friedmand2cce132012-02-02 23:15:15 +000010759void Sema::CleanupVarDeclMarking() {
10760 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10761 e = MaybeODRUseExprs.end();
10762 i != e; ++i) {
10763 VarDecl *Var;
10764 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010765 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010766 Var = cast<VarDecl>(DRE->getDecl());
10767 Loc = DRE->getLocation();
10768 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10769 Var = cast<VarDecl>(ME->getMemberDecl());
10770 Loc = ME->getMemberLoc();
10771 } else {
10772 llvm_unreachable("Unexpcted expression");
10773 }
10774
10775 MarkVarDeclODRUsed(*this, Var, Loc);
10776 }
10777
10778 MaybeODRUseExprs.clear();
10779}
10780
10781// Mark a VarDecl referenced, and perform the necessary handling to compute
10782// odr-uses.
10783static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10784 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010785 Var->setReferenced();
10786
Eli Friedmand2cce132012-02-02 23:15:15 +000010787 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010788 return;
10789
10790 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010791 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010792 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10793 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010794 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10795 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010796 (!AlreadyInstantiated ||
10797 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010798 if (!AlreadyInstantiated) {
10799 // This is a modification of an existing AST node. Notify listeners.
10800 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10801 L->StaticDataMemberInstantiated(Var);
10802 MSInfo->setPointOfInstantiation(Loc);
10803 }
10804 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010805 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010806 // Do not defer instantiations of variables which could be used in a
10807 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000010808 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010809 else
Richard Smith37ce0102012-02-15 02:42:50 +000010810 SemaRef.PendingInstantiations.push_back(
10811 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010812 }
10813 }
10814
Eli Friedmand2cce132012-02-02 23:15:15 +000010815 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10816 // an object that satisfies the requirements for appearing in a
10817 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10818 // is immediately applied." We check the first part here, and
10819 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10820 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000010821 // C++03 depends on whether we get the C++03 version correct. This does not
10822 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000010823 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000010824 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010825 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000010826 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10827 SemaRef.MaybeODRUseExprs.insert(E);
10828 else
10829 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10830}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010831
Eli Friedmand2cce132012-02-02 23:15:15 +000010832/// \brief Mark a variable referenced, and check whether it is odr-used
10833/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10834/// used directly for normal expressions referring to VarDecl.
10835void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10836 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010837}
10838
10839static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10840 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010841 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10842 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10843 return;
10844 }
10845
Eli Friedman5f2987c2012-02-02 03:46:19 +000010846 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010847}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010848
Eli Friedman5f2987c2012-02-02 03:46:19 +000010849/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10850void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10851 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10852}
10853
10854/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10855void Sema::MarkMemberReferenced(MemberExpr *E) {
10856 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10857}
10858
Douglas Gregor73d90922012-02-10 09:26:04 +000010859/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000010860/// marks the declaration referenced, and performs odr-use checking for functions
10861/// and variables. This method should not be used when building an normal
10862/// expression which refers to a variable.
10863void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10864 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10865 MarkVariableReferenced(Loc, VD);
10866 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10867 MarkFunctionReferenced(Loc, FD);
10868 else
10869 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000010870}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010871
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010872namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010873 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010874 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010875 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010876 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10877 Sema &S;
10878 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010879
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010880 public:
10881 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010882
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010883 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010884
10885 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10886 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010887 };
10888}
10889
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010890bool MarkReferencedDecls::TraverseTemplateArgument(
10891 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010892 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000010893 if (Decl *D = Arg.getAsDecl())
10894 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010895 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010896
10897 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010898}
10899
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010900bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010901 if (ClassTemplateSpecializationDecl *Spec
10902 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10903 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010904 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010905 }
10906
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010907 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010908}
10909
10910void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10911 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010912 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010913}
10914
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010915namespace {
10916 /// \brief Helper class that marks all of the declarations referenced by
10917 /// potentially-evaluated subexpressions as "referenced".
10918 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10919 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000010920 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010921
10922 public:
10923 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10924
Douglas Gregorf4b7de12012-02-21 19:11:17 +000010925 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10926 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010927
10928 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000010929 // If we were asked not to visit local variables, don't.
10930 if (SkipLocalVariables) {
10931 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10932 if (VD->hasLocalStorage())
10933 return;
10934 }
10935
Eli Friedman5f2987c2012-02-02 03:46:19 +000010936 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010937 }
10938
10939 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010940 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010941 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010942 }
10943
John McCall80ee6e82011-11-10 05:35:25 +000010944 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010945 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000010946 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10947 Visit(E->getSubExpr());
10948 }
10949
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010950 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010951 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010952 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010953 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010954 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010955 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010956 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000010957
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010958 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10959 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010960 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010961 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10962 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10963 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010964 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010965 S.LookupDestructor(Record));
10966 }
10967
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010968 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010969 }
10970
10971 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010972 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010973 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010974 }
10975
Douglas Gregor102ff972010-10-19 17:17:35 +000010976 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10977 Visit(E->getExpr());
10978 }
Eli Friedmand2cce132012-02-02 23:15:15 +000010979
10980 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10981 Inherited::VisitImplicitCastExpr(E);
10982
10983 if (E->getCastKind() == CK_LValueToRValue)
10984 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10985 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010986 };
10987}
10988
10989/// \brief Mark any declarations that appear within this expression or any
10990/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000010991///
10992/// \param SkipLocalVariables If true, don't mark local variables as
10993/// 'referenced'.
10994void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10995 bool SkipLocalVariables) {
10996 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010997}
10998
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010999/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11000/// of the program being compiled.
11001///
11002/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011003/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011004/// possibility that the code will actually be executable. Code in sizeof()
11005/// expressions, code used only during overload resolution, etc., are not
11006/// potentially evaluated. This routine will suppress such diagnostics or,
11007/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011008/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011009/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011010///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011011/// This routine should be used for all diagnostics that describe the run-time
11012/// behavior of a program, such as passing a non-POD value through an ellipsis.
11013/// Failure to do so will likely result in spurious diagnostics or failures
11014/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011015bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011016 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011017 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011018 case Unevaluated:
11019 // The argument will never be evaluated, so don't complain.
11020 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011021
Richard Smithf6702a32011-12-20 02:08:33 +000011022 case ConstantEvaluated:
11023 // Relevant diagnostics should be produced by constant evaluation.
11024 break;
11025
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011026 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011027 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011028 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011029 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011030 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011031 }
11032 else
11033 Diag(Loc, PD);
11034
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011035 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011036 }
11037
11038 return false;
11039}
11040
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011041bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11042 CallExpr *CE, FunctionDecl *FD) {
11043 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11044 return false;
11045
Richard Smith76f3f692012-02-22 02:04:18 +000011046 // If we're inside a decltype's expression, don't check for a valid return
11047 // type or construct temporaries until we know whether this is the last call.
11048 if (ExprEvalContexts.back().IsDecltype) {
11049 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11050 return false;
11051 }
11052
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011053 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011054 FunctionDecl *FD;
11055 CallExpr *CE;
11056
11057 public:
11058 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11059 : FD(FD), CE(CE) { }
11060
11061 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11062 if (!FD) {
11063 S.Diag(Loc, diag::err_call_incomplete_return)
11064 << T << CE->getSourceRange();
11065 return;
11066 }
11067
11068 S.Diag(Loc, diag::err_call_function_incomplete_return)
11069 << CE->getSourceRange() << FD->getDeclName() << T;
11070 S.Diag(FD->getLocation(),
11071 diag::note_function_with_incomplete_return_type_declared_here)
11072 << FD->getDeclName();
11073 }
11074 } Diagnoser(FD, CE);
11075
11076 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011077 return true;
11078
11079 return false;
11080}
11081
Douglas Gregor92c3a042011-01-19 16:50:08 +000011082// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011083// will prevent this condition from triggering, which is what we want.
11084void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11085 SourceLocation Loc;
11086
John McCalla52ef082009-11-11 02:41:58 +000011087 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011088 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011089
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011090 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011091 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011092 return;
11093
Douglas Gregor92c3a042011-01-19 16:50:08 +000011094 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11095
John McCallc8d8ac52009-11-12 00:06:05 +000011096 // Greylist some idioms by putting them into a warning subcategory.
11097 if (ObjCMessageExpr *ME
11098 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11099 Selector Sel = ME->getSelector();
11100
John McCallc8d8ac52009-11-12 00:06:05 +000011101 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011102 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011103 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11104
11105 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011106 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011107 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11108 }
John McCalla52ef082009-11-11 02:41:58 +000011109
John McCall5a881bb2009-10-12 21:59:07 +000011110 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011111 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011112 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011113 return;
11114
Douglas Gregor92c3a042011-01-19 16:50:08 +000011115 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011116 Loc = Op->getOperatorLoc();
11117 } else {
11118 // Not an assignment.
11119 return;
11120 }
11121
Douglas Gregor55b38842010-04-14 16:09:52 +000011122 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011123
Daniel Dunbar96a00142012-03-09 18:35:03 +000011124 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011125 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11126 Diag(Loc, diag::note_condition_assign_silence)
11127 << FixItHint::CreateInsertion(Open, "(")
11128 << FixItHint::CreateInsertion(Close, ")");
11129
Douglas Gregor92c3a042011-01-19 16:50:08 +000011130 if (IsOrAssign)
11131 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11132 << FixItHint::CreateReplacement(Loc, "!=");
11133 else
11134 Diag(Loc, diag::note_condition_assign_to_comparison)
11135 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011136}
11137
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011138/// \brief Redundant parentheses over an equality comparison can indicate
11139/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011140void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011141 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011142 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011143 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11144 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011145 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011146 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011147 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011148
Richard Trieuccd891a2011-09-09 01:45:06 +000011149 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011150
11151 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011152 if (opE->getOpcode() == BO_EQ &&
11153 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11154 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011155 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011156
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011157 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011158 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011159 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011160 << FixItHint::CreateRemoval(ParenERange.getBegin())
11161 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011162 Diag(Loc, diag::note_equality_comparison_to_assign)
11163 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011164 }
11165}
11166
John Wiegley429bb272011-04-08 18:41:53 +000011167ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011168 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011169 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11170 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011171
John McCall864c0412011-04-26 20:42:42 +000011172 ExprResult result = CheckPlaceholderExpr(E);
11173 if (result.isInvalid()) return ExprError();
11174 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011175
John McCall864c0412011-04-26 20:42:42 +000011176 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011177 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011178 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11179
John Wiegley429bb272011-04-08 18:41:53 +000011180 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11181 if (ERes.isInvalid())
11182 return ExprError();
11183 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011184
11185 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011186 if (!T->isScalarType()) { // C99 6.8.4.1p1
11187 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11188 << T << E->getSourceRange();
11189 return ExprError();
11190 }
John McCall5a881bb2009-10-12 21:59:07 +000011191 }
11192
John Wiegley429bb272011-04-08 18:41:53 +000011193 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011194}
Douglas Gregor586596f2010-05-06 17:25:47 +000011195
John McCall60d7b3a2010-08-24 06:29:42 +000011196ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011197 Expr *SubExpr) {
11198 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011199 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011200
Richard Trieuccd891a2011-09-09 01:45:06 +000011201 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011202}
John McCall2a984ca2010-10-12 00:20:44 +000011203
John McCall1de4d4e2011-04-07 08:22:57 +000011204namespace {
John McCall755d8492011-04-12 00:42:48 +000011205 /// A visitor for rebuilding a call to an __unknown_any expression
11206 /// to have an appropriate type.
11207 struct RebuildUnknownAnyFunction
11208 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11209
11210 Sema &S;
11211
11212 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11213
11214 ExprResult VisitStmt(Stmt *S) {
11215 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011216 }
11217
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011218 ExprResult VisitExpr(Expr *E) {
11219 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11220 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011221 return ExprError();
11222 }
11223
11224 /// Rebuild an expression which simply semantically wraps another
11225 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011226 template <class T> ExprResult rebuildSugarExpr(T *E) {
11227 ExprResult SubResult = Visit(E->getSubExpr());
11228 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011229
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011230 Expr *SubExpr = SubResult.take();
11231 E->setSubExpr(SubExpr);
11232 E->setType(SubExpr->getType());
11233 E->setValueKind(SubExpr->getValueKind());
11234 assert(E->getObjectKind() == OK_Ordinary);
11235 return E;
John McCall755d8492011-04-12 00:42:48 +000011236 }
11237
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011238 ExprResult VisitParenExpr(ParenExpr *E) {
11239 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011240 }
11241
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011242 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11243 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011244 }
11245
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011246 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11247 ExprResult SubResult = Visit(E->getSubExpr());
11248 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011249
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011250 Expr *SubExpr = SubResult.take();
11251 E->setSubExpr(SubExpr);
11252 E->setType(S.Context.getPointerType(SubExpr->getType()));
11253 assert(E->getValueKind() == VK_RValue);
11254 assert(E->getObjectKind() == OK_Ordinary);
11255 return E;
John McCall755d8492011-04-12 00:42:48 +000011256 }
11257
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011258 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11259 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011260
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011261 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011262
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011263 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011264 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011265 !(isa<CXXMethodDecl>(VD) &&
11266 cast<CXXMethodDecl>(VD)->isInstance()))
11267 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011268
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011269 return E;
John McCall755d8492011-04-12 00:42:48 +000011270 }
11271
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011272 ExprResult VisitMemberExpr(MemberExpr *E) {
11273 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011274 }
11275
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011276 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11277 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011278 }
11279 };
11280}
11281
11282/// Given a function expression of unknown-any type, try to rebuild it
11283/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011284static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11285 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11286 if (Result.isInvalid()) return ExprError();
11287 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011288}
11289
11290namespace {
John McCall379b5152011-04-11 07:02:50 +000011291 /// A visitor for rebuilding an expression of type __unknown_anytype
11292 /// into one which resolves the type directly on the referring
11293 /// expression. Strict preservation of the original source
11294 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011295 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011296 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011297
11298 Sema &S;
11299
11300 /// The current destination type.
11301 QualType DestType;
11302
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011303 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11304 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011305
John McCalla5fc4722011-04-09 22:50:59 +000011306 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011307 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011308 }
11309
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011310 ExprResult VisitExpr(Expr *E) {
11311 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11312 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011313 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011314 }
11315
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011316 ExprResult VisitCallExpr(CallExpr *E);
11317 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011318
John McCalla5fc4722011-04-09 22:50:59 +000011319 /// Rebuild an expression which simply semantically wraps another
11320 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011321 template <class T> ExprResult rebuildSugarExpr(T *E) {
11322 ExprResult SubResult = Visit(E->getSubExpr());
11323 if (SubResult.isInvalid()) return ExprError();
11324 Expr *SubExpr = SubResult.take();
11325 E->setSubExpr(SubExpr);
11326 E->setType(SubExpr->getType());
11327 E->setValueKind(SubExpr->getValueKind());
11328 assert(E->getObjectKind() == OK_Ordinary);
11329 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011330 }
John McCall1de4d4e2011-04-07 08:22:57 +000011331
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011332 ExprResult VisitParenExpr(ParenExpr *E) {
11333 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011334 }
11335
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011336 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11337 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011338 }
11339
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011340 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11341 const PointerType *Ptr = DestType->getAs<PointerType>();
11342 if (!Ptr) {
11343 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11344 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011345 return ExprError();
11346 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011347 assert(E->getValueKind() == VK_RValue);
11348 assert(E->getObjectKind() == OK_Ordinary);
11349 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011350
11351 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011352 DestType = Ptr->getPointeeType();
11353 ExprResult SubResult = Visit(E->getSubExpr());
11354 if (SubResult.isInvalid()) return ExprError();
11355 E->setSubExpr(SubResult.take());
11356 return E;
John McCall755d8492011-04-12 00:42:48 +000011357 }
11358
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011359 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011360
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011361 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011362
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011363 ExprResult VisitMemberExpr(MemberExpr *E) {
11364 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011365 }
John McCalla5fc4722011-04-09 22:50:59 +000011366
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011367 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11368 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011369 }
11370 };
11371}
11372
John McCall379b5152011-04-11 07:02:50 +000011373/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011374ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11375 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011376
11377 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011378 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011379 FK_FunctionPointer,
11380 FK_BlockPointer
11381 };
11382
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011383 FnKind Kind;
11384 QualType CalleeType = CalleeExpr->getType();
11385 if (CalleeType == S.Context.BoundMemberTy) {
11386 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11387 Kind = FK_MemberFunction;
11388 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11389 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11390 CalleeType = Ptr->getPointeeType();
11391 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011392 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011393 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11394 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011395 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011396 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011397
11398 // Verify that this is a legal result type of a function.
11399 if (DestType->isArrayType() || DestType->isFunctionType()) {
11400 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011401 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011402 diagID = diag::err_block_returning_array_function;
11403
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011404 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011405 << DestType->isFunctionType() << DestType;
11406 return ExprError();
11407 }
11408
11409 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011410 E->setType(DestType.getNonLValueExprType(S.Context));
11411 E->setValueKind(Expr::getValueKindForType(DestType));
11412 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011413
11414 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011415 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011416 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011417 Proto->arg_type_begin(),
11418 Proto->getNumArgs(),
11419 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011420 else
11421 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011422 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011423
11424 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011425 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011426 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011427 // Nothing to do.
11428 break;
11429
11430 case FK_FunctionPointer:
11431 DestType = S.Context.getPointerType(DestType);
11432 break;
11433
11434 case FK_BlockPointer:
11435 DestType = S.Context.getBlockPointerType(DestType);
11436 break;
11437 }
11438
11439 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011440 ExprResult CalleeResult = Visit(CalleeExpr);
11441 if (!CalleeResult.isUsable()) return ExprError();
11442 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011443
11444 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011445 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011446}
11447
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011448ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011449 // Verify that this is a legal result type of a call.
11450 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011451 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011452 << DestType->isFunctionType() << DestType;
11453 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011454 }
11455
John McCall48218c62011-07-13 17:56:40 +000011456 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011457 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11458 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11459 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011460 }
John McCall755d8492011-04-12 00:42:48 +000011461
John McCall379b5152011-04-11 07:02:50 +000011462 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011463 E->setType(DestType.getNonReferenceType());
11464 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011465
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011466 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011467}
11468
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011469ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011470 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011471 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011472 assert(E->getValueKind() == VK_RValue);
11473 assert(E->getObjectKind() == OK_Ordinary);
11474
11475 E->setType(DestType);
11476
11477 // Rebuild the sub-expression as the pointee (function) type.
11478 DestType = DestType->castAs<PointerType>()->getPointeeType();
11479
11480 ExprResult Result = Visit(E->getSubExpr());
11481 if (!Result.isUsable()) return ExprError();
11482
11483 E->setSubExpr(Result.take());
11484 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011485 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011486 assert(E->getValueKind() == VK_RValue);
11487 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011488
Sean Callanance9c8312012-03-06 21:34:12 +000011489 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011490
Sean Callanance9c8312012-03-06 21:34:12 +000011491 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011492
Sean Callanance9c8312012-03-06 21:34:12 +000011493 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11494 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011495
Sean Callanance9c8312012-03-06 21:34:12 +000011496 ExprResult Result = Visit(E->getSubExpr());
11497 if (!Result.isUsable()) return ExprError();
11498
11499 E->setSubExpr(Result.take());
11500 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011501 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011502 llvm_unreachable("Unhandled cast type!");
11503 }
John McCall379b5152011-04-11 07:02:50 +000011504}
11505
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011506ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11507 ExprValueKind ValueKind = VK_LValue;
11508 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011509
11510 // We know how to make this work for certain kinds of decls:
11511
11512 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011513 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11514 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11515 DestType = Ptr->getPointeeType();
11516 ExprResult Result = resolveDecl(E, VD);
11517 if (Result.isInvalid()) return ExprError();
11518 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011519 CK_FunctionToPointerDecay, VK_RValue);
11520 }
11521
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011522 if (!Type->isFunctionType()) {
11523 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11524 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011525 return ExprError();
11526 }
John McCall379b5152011-04-11 07:02:50 +000011527
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011528 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11529 if (MD->isInstance()) {
11530 ValueKind = VK_RValue;
11531 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011532 }
11533
John McCall379b5152011-04-11 07:02:50 +000011534 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011535 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011536 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011537
11538 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011539 } else if (isa<VarDecl>(VD)) {
11540 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11541 Type = RefTy->getPointeeType();
11542 } else if (Type->isFunctionType()) {
11543 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11544 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011545 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011546 }
11547
11548 // - nothing else
11549 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011550 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11551 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011552 return ExprError();
11553 }
11554
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011555 VD->setType(DestType);
11556 E->setType(Type);
11557 E->setValueKind(ValueKind);
11558 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011559}
11560
John McCall1de4d4e2011-04-07 08:22:57 +000011561/// Check a cast of an unknown-any type. We intentionally only
11562/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011563ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11564 Expr *CastExpr, CastKind &CastKind,
11565 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011566 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011567 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011568 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011569
Richard Trieuccd891a2011-09-09 01:45:06 +000011570 CastExpr = result.take();
11571 VK = CastExpr->getValueKind();
11572 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011573
Richard Trieuccd891a2011-09-09 01:45:06 +000011574 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011575}
11576
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011577ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11578 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11579}
11580
Richard Trieuccd891a2011-09-09 01:45:06 +000011581static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11582 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011583 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011584 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011585 E = E->IgnoreParenImpCasts();
11586 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11587 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011588 diagID = diag::err_uncasted_call_of_unknown_any;
11589 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011590 break;
John McCall379b5152011-04-11 07:02:50 +000011591 }
John McCall1de4d4e2011-04-07 08:22:57 +000011592 }
11593
John McCall379b5152011-04-11 07:02:50 +000011594 SourceLocation loc;
11595 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011596 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011597 loc = ref->getLocation();
11598 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011599 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011600 loc = mem->getMemberLoc();
11601 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011602 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011603 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011604 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011605 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011606 if (!d) {
11607 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11608 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11609 << orig->getSourceRange();
11610 return ExprError();
11611 }
John McCall379b5152011-04-11 07:02:50 +000011612 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011613 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11614 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011615 return ExprError();
11616 }
11617
11618 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011619
11620 // Never recoverable.
11621 return ExprError();
11622}
11623
John McCall2a984ca2010-10-12 00:20:44 +000011624/// Check for operands with placeholder types and complain if found.
11625/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011626ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011627 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11628 if (!placeholderType) return Owned(E);
11629
11630 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011631
John McCall1de4d4e2011-04-07 08:22:57 +000011632 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011633 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011634 // Try to resolve a single function template specialization.
11635 // This is obligatory.
11636 ExprResult result = Owned(E);
11637 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11638 return result;
11639
11640 // If that failed, try to recover with a call.
11641 } else {
11642 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11643 /*complain*/ true);
11644 return result;
11645 }
11646 }
John McCall1de4d4e2011-04-07 08:22:57 +000011647
John McCall864c0412011-04-26 20:42:42 +000011648 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011649 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011650 ExprResult result = Owned(E);
11651 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11652 /*complain*/ true);
11653 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011654 }
11655
11656 // ARC unbridged casts.
11657 case BuiltinType::ARCUnbridgedCast: {
11658 Expr *realCast = stripARCUnbridgedCast(E);
11659 diagnoseARCUnbridgedCast(realCast);
11660 return Owned(realCast);
11661 }
John McCall864c0412011-04-26 20:42:42 +000011662
John McCall1de4d4e2011-04-07 08:22:57 +000011663 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011664 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011665 return diagnoseUnknownAnyExpr(*this, E);
11666
John McCall3c3b7f92011-10-25 17:37:35 +000011667 // Pseudo-objects.
11668 case BuiltinType::PseudoObject:
11669 return checkPseudoObjectRValue(E);
11670
John McCalle0a22d02011-10-18 21:02:43 +000011671 // Everything else should be impossible.
11672#define BUILTIN_TYPE(Id, SingletonId) \
11673 case BuiltinType::Id:
11674#define PLACEHOLDER_TYPE(Id, SingletonId)
11675#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011676 break;
11677 }
11678
11679 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011680}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011681
Richard Trieuccd891a2011-09-09 01:45:06 +000011682bool Sema::CheckCaseExpression(Expr *E) {
11683 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011684 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011685 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11686 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011687 return false;
11688}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011689
11690/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11691ExprResult
11692Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11693 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11694 "Unknown Objective-C Boolean value!");
11695 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian93a49942012-04-16 21:03:30 +000011696 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011697}