blob: 158e02a450e4e9d447658176374c022251df8f44 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.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 C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
Richard Smith7a614d82011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Nick Lewyckyfca84b22012-01-24 21:15:41 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000025#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000027#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/Preprocessor.h"
David Blaikie91ec7892011-12-16 16:03:09 +000032#include "TypeLocBuilder.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000034#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
John McCallb3d87482010-08-24 05:47:05 +000038ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000039 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000040 SourceLocation NameLoc,
41 Scope *S, CXXScopeSpec &SS,
42 ParsedType ObjectTypePtr,
43 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000044 // Determine where to perform name lookup.
45
46 // FIXME: This area of the standard is very messy, and the current
47 // wording is rather unclear about which scopes we search for the
48 // destructor name; see core issues 399 and 555. Issue 399 in
49 // particular shows where the current description of destructor name
50 // lookup is completely out of line with existing practice, e.g.,
51 // this appears to be ill-formed:
52 //
53 // namespace N {
54 // template <typename T> struct S {
55 // ~S();
56 // };
57 // }
58 //
59 // void f(N::S<int>* s) {
60 // s->N::S<int>::~S();
61 // }
62 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000063 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000064 // For this reason, we're currently only doing the C++03 version of this
65 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000066 QualType SearchType;
67 DeclContext *LookupCtx = 0;
68 bool isDependent = false;
69 bool LookInScope = false;
70
71 // If we have an object type, it's because we are in a
72 // pseudo-destructor-expression or a member access expression, and
73 // we know what type we're looking for.
74 if (ObjectTypePtr)
75 SearchType = GetTypeFromParser(ObjectTypePtr);
76
77 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000078 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079
Douglas Gregor93649fd2010-02-23 00:15:22 +000080 bool AlreadySearched = false;
81 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000082 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000083 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 // the type-names are looked up as types in the scope designated by the
85 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000086 //
87 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000088 //
89 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000090 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000092 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000093 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000096 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000097 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000098 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000099 // nested-name-specifier.
100 DeclContext *DC = computeDeclContext(SS, EnteringContext);
101 if (DC && DC->isFileContext()) {
102 AlreadySearched = true;
103 LookupCtx = DC;
104 isDependent = false;
105 } else if (DC && isa<CXXRecordDecl>(DC))
106 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000107
Sebastian Redlc0fee502010-07-07 23:17:38 +0000108 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 NestedNameSpecifier *Prefix = 0;
110 if (AlreadySearched) {
111 // Nothing left to do.
112 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
113 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000114 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000115 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
116 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000117 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 LookupCtx = computeDeclContext(SearchType);
119 isDependent = SearchType->isDependentType();
120 } else {
121 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000122 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000124
Douglas Gregoredc90502010-02-25 04:46:04 +0000125 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000126 } else if (ObjectTypePtr) {
127 // C++ [basic.lookup.classref]p3:
128 // If the unqualified-id is ~type-name, the type-name is looked up
129 // in the context of the entire postfix-expression. If the type T
130 // of the object expression is of a class type C, the type-name is
131 // also looked up in the scope of class C. At least one of the
132 // lookups shall find a name that refers to (possibly
133 // cv-qualified) T.
134 LookupCtx = computeDeclContext(SearchType);
135 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000136 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 "Caller should have completed object type");
138
139 LookInScope = true;
140 } else {
141 // Perform lookup into the current scope (only).
142 LookInScope = true;
143 }
144
Douglas Gregor7ec18732011-03-04 22:32:08 +0000145 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000146 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
147 for (unsigned Step = 0; Step != 2; ++Step) {
148 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000149 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000150 // we're allowed to look there).
151 Found.clear();
152 if (Step == 0 && LookupCtx)
153 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000154 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000155 LookupName(Found, S);
156 else
157 continue;
158
159 // FIXME: Should we be suppressing ambiguities here?
160 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000161 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000162
163 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
164 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000165
166 if (SearchType.isNull() || SearchType->isDependentType() ||
167 Context.hasSameUnqualifiedType(T, SearchType)) {
168 // We found our type!
169
John McCallb3d87482010-08-24 05:47:05 +0000170 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000171 }
John Wiegley36784e72011-03-08 08:13:22 +0000172
Douglas Gregor7ec18732011-03-04 22:32:08 +0000173 if (!SearchType.isNull())
174 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000175 }
176
177 // If the name that we found is a class template name, and it is
178 // the same name as the template name in the last part of the
179 // nested-name-specifier (if present) or the object type, then
180 // this is the destructor for that class.
181 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000182 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000183 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
184 QualType MemberOfType;
185 if (SS.isSet()) {
186 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
187 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000188 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
189 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000190 }
191 }
192 if (MemberOfType.isNull())
193 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000194
Douglas Gregor124b8782010-02-16 19:09:40 +0000195 if (MemberOfType.isNull())
196 continue;
197
198 // We're referring into a class template specialization. If the
199 // class template we found is the same as the template being
200 // specialized, we found what we are looking for.
201 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
202 if (ClassTemplateSpecializationDecl *Spec
203 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
204 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
205 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000206 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000207 }
208
209 continue;
210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000211
Douglas Gregor124b8782010-02-16 19:09:40 +0000212 // We're referring to an unresolved class template
213 // specialization. Determine whether we class template we found
214 // is the same as the template being specialized or, if we don't
215 // know which template is being specialized, that it at least
216 // has the same name.
217 if (const TemplateSpecializationType *SpecType
218 = MemberOfType->getAs<TemplateSpecializationType>()) {
219 TemplateName SpecName = SpecType->getTemplateName();
220
221 // The class template we found is the same template being
222 // specialized.
223 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
224 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000225 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000226
227 continue;
228 }
229
230 // The class template we found has the same name as the
231 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000232 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000233 = SpecName.getAsDependentTemplateName()) {
234 if (DepTemplate->isIdentifier() &&
235 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000236 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000237
238 continue;
239 }
240 }
241 }
242 }
243
244 if (isDependent) {
245 // We didn't find our type, but that's okay: it's dependent
246 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000247
248 // FIXME: What if we have no nested-name-specifier?
249 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
250 SS.getWithLocInContext(Context),
251 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000252 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000253 }
254
Douglas Gregor7ec18732011-03-04 22:32:08 +0000255 if (NonMatchingTypeDecl) {
256 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
257 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
258 << T << SearchType;
259 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
260 << T;
261 } else if (ObjectTypePtr)
262 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000263 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000264 else
265 Diag(NameLoc, diag::err_destructor_class_name);
266
John McCallb3d87482010-08-24 05:47:05 +0000267 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000268}
269
David Blaikie53a75c02011-12-08 16:13:53 +0000270ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000271 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000272 return ParsedType();
273 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
274 && "only get destructor types from declspecs");
275 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
276 QualType SearchType = GetTypeFromParser(ObjectType);
277 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
278 return ParsedType::make(T);
279 }
280
281 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
282 << T << SearchType;
283 return ParsedType();
284}
285
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000286/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 TypeSourceInfo *Operand,
290 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000293 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000295 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000296 Qualifiers Quals;
297 QualType T
298 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
299 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000300 if (T->getAs<RecordType>() &&
301 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
302 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000303
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
305 Operand,
306 SourceRange(TypeidLoc, RParenLoc)));
307}
308
309/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000310ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000311 SourceLocation TypeidLoc,
312 Expr *E,
313 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000314 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000315 if (E->getType()->isPlaceholderType()) {
316 ExprResult result = CheckPlaceholderExpr(E);
317 if (result.isInvalid()) return ExprError();
318 E = result.take();
319 }
320
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000321 QualType T = E->getType();
322 if (const RecordType *RecordT = T->getAs<RecordType>()) {
323 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
324 // C++ [expr.typeid]p3:
325 // [...] If the type of the expression is a class type, the class
326 // shall be completely-defined.
327 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
328 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000330 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000331 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 // polymorphic class type [...] [the] expression is an unevaluated
333 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000334 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedmanef331b72012-01-20 01:26:23 +0000335 // The subexpression is potentially evaluated; switch the context
336 // and recheck the subexpression.
337 ExprResult Result = TranformToPotentiallyEvaluated(E);
338 if (Result.isInvalid()) return ExprError();
339 E = Result.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000340
341 // We require a vtable to query the type at run time.
342 MarkVTableUsed(TypeidLoc, RecordD);
343 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000345
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000346 // C++ [expr.typeid]p4:
347 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000348 // cv-qualified type, the result of the typeid expression refers to a
349 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000350 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000351 Qualifiers Quals;
352 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
353 if (!Context.hasSameType(T, UnqualT)) {
354 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000355 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000356 }
357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000359 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000360 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000361 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362}
363
364/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000365ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000366Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
367 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000369 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000370 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000371
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000372 if (!CXXTypeInfoDecl) {
373 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
374 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
375 LookupQualifiedName(R, getStdNamespace());
376 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
377 if (!CXXTypeInfoDecl)
378 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000380
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000381 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000382
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000383 if (isType) {
384 // The operand is a type; handle it as such.
385 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000386 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
387 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000388 if (T.isNull())
389 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000391 if (!TInfo)
392 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000393
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000394 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000397 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000398 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000399}
400
Francois Pichet6915c522010-12-27 01:32:00 +0000401/// Retrieve the UuidAttr associated with QT.
402static UuidAttr *GetUuidAttrOfType(QualType QT) {
403 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000404 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000405 if (QT->isPointerType() || QT->isReferenceType())
406 Ty = QT->getPointeeType().getTypePtr();
407 else if (QT->isArrayType())
408 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
409
Francois Pichet8db75a22011-05-08 10:02:20 +0000410 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000411 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000412 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
413 E = RD->redecls_end(); I != E; ++I) {
414 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000415 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000416 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000417
Francois Pichet6915c522010-12-27 01:32:00 +0000418 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000419}
420
Francois Pichet01b7c302010-09-08 12:20:18 +0000421/// \brief Build a Microsoft __uuidof expression with a type operand.
422ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
423 SourceLocation TypeidLoc,
424 TypeSourceInfo *Operand,
425 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000426 if (!Operand->getType()->isDependentType()) {
427 if (!GetUuidAttrOfType(Operand->getType()))
428 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
429 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000430
Francois Pichet01b7c302010-09-08 12:20:18 +0000431 // FIXME: add __uuidof semantic analysis for type operand.
432 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
433 Operand,
434 SourceRange(TypeidLoc, RParenLoc)));
435}
436
437/// \brief Build a Microsoft __uuidof expression with an expression operand.
438ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
439 SourceLocation TypeidLoc,
440 Expr *E,
441 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000442 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000443 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000444 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
445 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
446 }
447 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000448 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
449 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000450 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000451}
452
453/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
454ExprResult
455Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
456 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000457 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000458 if (!MSVCGuidDecl) {
459 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
460 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
461 LookupQualifiedName(R, Context.getTranslationUnitDecl());
462 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
463 if (!MSVCGuidDecl)
464 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000465 }
466
Francois Pichet01b7c302010-09-08 12:20:18 +0000467 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468
Francois Pichet01b7c302010-09-08 12:20:18 +0000469 if (isType) {
470 // The operand is a type; handle it as such.
471 TypeSourceInfo *TInfo = 0;
472 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
473 &TInfo);
474 if (T.isNull())
475 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000476
Francois Pichet01b7c302010-09-08 12:20:18 +0000477 if (!TInfo)
478 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
479
480 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
481 }
482
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000483 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000484 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
485}
486
Steve Naroff1b273c42007-09-16 14:56:35 +0000487/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000488ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000489Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000490 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000492 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
493 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000494}
Chris Lattner50dd2892008-02-26 00:51:44 +0000495
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000496/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000497ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000498Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
499 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
500}
501
Chris Lattner50dd2892008-02-26 00:51:44 +0000502/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000503ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000504Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
505 bool IsThrownVarInScope = false;
506 if (Ex) {
507 // C++0x [class.copymove]p31:
508 // When certain criteria are met, an implementation is allowed to omit the
509 // copy/move construction of a class object [...]
510 //
511 // - in a throw-expression, when the operand is the name of a
512 // non-volatile automatic object (other than a function or catch-
513 // clause parameter) whose scope does not extend beyond the end of the
514 // innermost enclosing try-block (if there is one), the copy/move
515 // operation from the operand to the exception object (15.1) can be
516 // omitted by constructing the automatic object directly into the
517 // exception object
518 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
519 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
520 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
521 for( ; S; S = S->getParent()) {
522 if (S->isDeclScope(Var)) {
523 IsThrownVarInScope = true;
524 break;
525 }
526
527 if (S->getFlags() &
528 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
529 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
530 Scope::TryScope))
531 break;
532 }
533 }
534 }
535 }
536
537 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
538}
539
540ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
541 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000542 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000543 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000544 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000545 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000546
John Wiegley429bb272011-04-08 18:41:53 +0000547 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000548 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000549 if (ExRes.isInvalid())
550 return ExprError();
551 Ex = ExRes.take();
552 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000553
554 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
555 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000556}
557
558/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000559ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
560 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000561 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000562 // A throw-expression initializes a temporary object, called the exception
563 // object, the type of which is determined by removing any top-level
564 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000565 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000566 // or "pointer to function returning T", [...]
567 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000568 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000569 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570
John Wiegley429bb272011-04-08 18:41:53 +0000571 ExprResult Res = DefaultFunctionArrayConversion(E);
572 if (Res.isInvalid())
573 return ExprError();
574 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000575
576 // If the type of the exception would be an incomplete type or a pointer
577 // to an incomplete type other than (cv) void the program is ill-formed.
578 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000579 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000580 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000581 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000582 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000583 }
584 if (!isPointer || !Ty->isVoidType()) {
585 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000586 PDiag(isPointer ? diag::err_throw_incomplete_ptr
587 : diag::err_throw_incomplete)
588 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000589 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000590
Douglas Gregorbf422f92010-04-15 18:05:39 +0000591 if (RequireNonAbstractType(ThrowLoc, E->getType(),
592 PDiag(diag::err_throw_abstract_type)
593 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000594 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000595 }
596
John McCallac418162010-04-22 01:10:34 +0000597 // Initialize the exception result. This implicitly weeds out
598 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000599
600 // C++0x [class.copymove]p31:
601 // When certain criteria are met, an implementation is allowed to omit the
602 // copy/move construction of a class object [...]
603 //
604 // - in a throw-expression, when the operand is the name of a
605 // non-volatile automatic object (other than a function or catch-clause
606 // parameter) whose scope does not extend beyond the end of the
607 // innermost enclosing try-block (if there is one), the copy/move
608 // operation from the operand to the exception object (15.1) can be
609 // omitted by constructing the automatic object directly into the
610 // exception object
611 const VarDecl *NRVOVariable = 0;
612 if (IsThrownVarInScope)
613 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
614
John McCallac418162010-04-22 01:10:34 +0000615 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000616 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000617 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000618 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000619 QualType(), E,
620 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000621 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000622 return ExprError();
623 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000624
Eli Friedman5ed9b932010-06-03 20:39:03 +0000625 // If the exception has class type, we need additional handling.
626 const RecordType *RecordTy = Ty->getAs<RecordType>();
627 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000628 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000629 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
630
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000631 // If we are throwing a polymorphic class type or pointer thereof,
632 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000633 MarkVTableUsed(ThrowLoc, RD);
634
Eli Friedman98efb9f2010-10-12 20:32:36 +0000635 // If a pointer is thrown, the referenced object will not be destroyed.
636 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000637 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000638
Eli Friedman5ed9b932010-06-03 20:39:03 +0000639 // If the class has a non-trivial destructor, we must be able to call it.
640 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000641 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000642
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000643 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000644 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000645 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000646 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000647
Eli Friedman5f2987c2012-02-02 03:46:19 +0000648 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000649 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000650 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000651 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000652}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000653
Eli Friedman72899c32012-01-07 04:59:52 +0000654QualType Sema::getCurrentThisType() {
655 DeclContext *DC = getFunctionLevelDeclContext();
Richard Smith7a614d82011-06-11 17:19:42 +0000656 QualType ThisTy;
657 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
658 if (method && method->isInstance())
659 ThisTy = method->getThisType(Context);
660 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
661 // C++0x [expr.prim]p4:
662 // Otherwise, if a member-declarator declares a non-static data member
663 // of a class X, the expression this is a prvalue of type "pointer to X"
664 // within the optional brace-or-equal-initializer.
665 Scope *S = getScopeForContext(DC);
666 if (!S || S->getFlags() & Scope::ThisScope)
667 ThisTy = Context.getPointerType(Context.getRecordType(RD));
668 }
John McCall469a1eb2011-02-02 13:00:07 +0000669
Richard Smith7a614d82011-06-11 17:19:42 +0000670 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000671}
672
Douglas Gregora1f21142012-02-01 17:04:21 +0000673void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Eli Friedman72899c32012-01-07 04:59:52 +0000674 // We don't need to capture this in an unevaluated context.
Douglas Gregora1f21142012-02-01 17:04:21 +0000675 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
Eli Friedman72899c32012-01-07 04:59:52 +0000676 return;
677
678 // Otherwise, check that we can capture 'this'.
679 unsigned NumClosures = 0;
680 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000681 if (CapturingScopeInfo *CSI =
682 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
683 if (CSI->CXXThisCaptureIndex != 0) {
684 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000685 break;
686 }
Douglas Gregora1f21142012-02-01 17:04:21 +0000687
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000688 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1f21142012-02-01 17:04:21 +0000689 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
690 Explicit) {
691 // This closure can capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000692 // FIXME: Is this check correct? The rules in the standard are a bit
693 // unclear.
694 NumClosures++;
Douglas Gregora1f21142012-02-01 17:04:21 +0000695 Explicit = false;
Eli Friedman72899c32012-01-07 04:59:52 +0000696 continue;
697 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000698 // This context can't implicitly capture 'this'; fail out.
Douglas Gregora1f21142012-02-01 17:04:21 +0000699 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman72899c32012-01-07 04:59:52 +0000700 return;
701 }
Eli Friedman72899c32012-01-07 04:59:52 +0000702 break;
703 }
704
705 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
706 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
707 // contexts.
708 for (unsigned idx = FunctionScopes.size() - 1;
709 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000710 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
711 bool isNested = NumClosures > 1;
Douglas Gregor93962e52012-02-01 01:18:43 +0000712 CSI->AddThisCapture(isNested, Loc);
Eli Friedman72899c32012-01-07 04:59:52 +0000713 }
714}
715
Richard Smith7a614d82011-06-11 17:19:42 +0000716ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000717 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
718 /// is a non-lvalue expression whose value is the address of the object for
719 /// which the function is called.
720
Douglas Gregor341350e2011-10-18 16:47:30 +0000721 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000722 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000723
Eli Friedman72899c32012-01-07 04:59:52 +0000724 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000725 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000726}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000727
John McCall60d7b3a2010-08-24 06:29:42 +0000728ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000729Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000730 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000731 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000732 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000733 if (!TypeRep)
734 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000735
John McCall9d125032010-01-15 18:39:57 +0000736 TypeSourceInfo *TInfo;
737 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
738 if (!TInfo)
739 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000740
741 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
742}
743
744/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
745/// Can be interpreted either as function-style casting ("int(x)")
746/// or class type construction ("ClassType(x,y,z)")
747/// or creation of a value-initialized type ("int()").
748ExprResult
749Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
750 SourceLocation LParenLoc,
751 MultiExprArg exprs,
752 SourceLocation RParenLoc) {
753 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000754 unsigned NumExprs = exprs.size();
755 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000756 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000757 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
758
Sebastian Redlf53597f2009-03-15 17:47:39 +0000759 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000760 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000761 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Douglas Gregorab6677e2010-09-08 00:15:04 +0000763 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000764 LParenLoc,
765 Exprs, NumExprs,
766 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000767 }
768
Anders Carlssonbb60a502009-08-27 03:53:50 +0000769 if (Ty->isArrayType())
770 return ExprError(Diag(TyBeginLoc,
771 diag::err_value_init_for_array_type) << FullRange);
772 if (!Ty->isVoidType() &&
773 RequireCompleteType(TyBeginLoc, Ty,
774 PDiag(diag::err_invalid_incomplete_type_use)
775 << FullRange))
776 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000777
Anders Carlssonbb60a502009-08-27 03:53:50 +0000778 if (RequireNonAbstractType(TyBeginLoc, Ty,
779 diag::err_allocation_of_abstract_type))
780 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000781
782
Douglas Gregor506ae412009-01-16 18:33:17 +0000783 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000784 // If the expression list is a single expression, the type conversion
785 // expression is equivalent (in definedness, and if defined in meaning) to the
786 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000787 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000788 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000789 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000790 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000791 }
792
Douglas Gregor19311e72010-09-08 21:40:08 +0000793 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
794 InitializationKind Kind
795 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
796 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000797 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000798 LParenLoc, RParenLoc);
799 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
800 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000801
Douglas Gregor19311e72010-09-08 21:40:08 +0000802 // FIXME: Improve AST representation?
803 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000804}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000805
John McCall6ec278d2011-01-27 09:37:56 +0000806/// doesUsualArrayDeleteWantSize - Answers whether the usual
807/// operator delete[] for the given type has a size_t parameter.
808static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
809 QualType allocType) {
810 const RecordType *record =
811 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
812 if (!record) return false;
813
814 // Try to find an operator delete[] in class scope.
815
816 DeclarationName deleteName =
817 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
818 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
819 S.LookupQualifiedName(ops, record->getDecl());
820
821 // We're just doing this for information.
822 ops.suppressDiagnostics();
823
824 // Very likely: there's no operator delete[].
825 if (ops.empty()) return false;
826
827 // If it's ambiguous, it should be illegal to call operator delete[]
828 // on this thing, so it doesn't matter if we allocate extra space or not.
829 if (ops.isAmbiguous()) return false;
830
831 LookupResult::Filter filter = ops.makeFilter();
832 while (filter.hasNext()) {
833 NamedDecl *del = filter.next()->getUnderlyingDecl();
834
835 // C++0x [basic.stc.dynamic.deallocation]p2:
836 // A template instance is never a usual deallocation function,
837 // regardless of its signature.
838 if (isa<FunctionTemplateDecl>(del)) {
839 filter.erase();
840 continue;
841 }
842
843 // C++0x [basic.stc.dynamic.deallocation]p2:
844 // If class T does not declare [an operator delete[] with one
845 // parameter] but does declare a member deallocation function
846 // named operator delete[] with exactly two parameters, the
847 // second of which has type std::size_t, then this function
848 // is a usual deallocation function.
849 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
850 filter.erase();
851 continue;
852 }
853 }
854 filter.done();
855
856 if (!ops.isSingleResult()) return false;
857
858 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
859 return (del->getNumParams() == 2);
860}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000861
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000862/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
863/// @code new (memory) int[size][4] @endcode
864/// or
865/// @code ::new Foo(23, "hello") @endcode
866/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000867ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000868Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000869 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000870 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000871 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000872 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000873 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000874 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
875
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000876 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000877 // If the specified type is an array, unwrap it and save the expression.
878 if (D.getNumTypeObjects() > 0 &&
879 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
880 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000881 if (TypeContainsAuto)
882 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
883 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000884 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000885 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
886 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000887 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000888 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
889 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000890
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000891 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000892 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000893 }
894
Douglas Gregor043cad22009-09-11 00:18:58 +0000895 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000896 if (ArraySize) {
897 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000898 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
899 break;
900
901 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
902 if (Expr *NumElts = (Expr *)Array.NumElts) {
903 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
904 !NumElts->isIntegerConstantExpr(Context)) {
905 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
906 << NumElts->getSourceRange();
907 return ExprError();
908 }
909 }
910 }
911 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000912
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000913 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000914 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000915 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000916 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000917
Mike Stump1eb44332009-09-09 15:08:12 +0000918 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000919 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000920 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000921 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000922 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000923 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000924 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000925 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000926 ConstructorLParen,
927 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000928 ConstructorRParen,
929 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000930}
931
John McCall60d7b3a2010-08-24 06:29:42 +0000932ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000933Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
934 SourceLocation PlacementLParen,
935 MultiExprArg PlacementArgs,
936 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000937 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000938 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000939 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000940 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000941 SourceLocation ConstructorLParen,
942 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000943 SourceLocation ConstructorRParen,
944 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000945 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000946
Richard Smith34b41d92011-02-20 03:19:35 +0000947 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
948 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
949 if (ConstructorArgs.size() == 0)
950 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
951 << AllocType << TypeRange);
952 if (ConstructorArgs.size() != 1) {
953 Expr *FirstBad = ConstructorArgs.get()[1];
954 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
955 diag::err_auto_new_ctor_multiple_expressions)
956 << AllocType << TypeRange);
957 }
Richard Smitha085da82011-03-17 16:11:59 +0000958 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +0000959 if (DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType) ==
960 DAR_Failed)
Richard Smith34b41d92011-02-20 03:19:35 +0000961 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
962 << AllocType
963 << ConstructorArgs.get()[0]->getType()
964 << TypeRange
965 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000966 if (!DeducedType)
967 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000968
Richard Smitha085da82011-03-17 16:11:59 +0000969 AllocTypeInfo = DeducedType;
970 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000971 }
972
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000973 // Per C++0x [expr.new]p5, the type being constructed may be a
974 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000975 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000976 if (const ConstantArrayType *Array
977 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000978 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
979 Context.getSizeType(),
980 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000981 AllocType = Array->getElementType();
982 }
983 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000984
Douglas Gregora0750762010-10-06 16:00:31 +0000985 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
986 return ExprError();
987
John McCallf85e1932011-06-15 23:02:42 +0000988 // In ARC, infer 'retaining' for the allocated
989 if (getLangOptions().ObjCAutoRefCount &&
990 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
991 AllocType->isObjCLifetimeType()) {
992 AllocType = Context.getLifetimeQualifiedType(AllocType,
993 AllocType->getObjCARCImplicitLifetime());
994 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000995
John McCallf85e1932011-06-15 23:02:42 +0000996 QualType ResultType = Context.getPointerType(AllocType);
997
Richard Smithf39aec12012-02-04 07:07:42 +0000998 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
999 // integral or enumeration type with a non-negative value."
1000 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1001 // enumeration type, or a class type for which a single non-explicit
1002 // conversion function to integral or unscoped enumeration type exists.
Sebastian Redl28507842009-02-26 14:39:58 +00001003 if (ArraySize && !ArraySize->isTypeDependent()) {
Eli Friedmanceccab92012-01-26 00:26:18 +00001004 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smithebaf0e62011-10-18 20:49:44 +00001005 StartLoc, ArraySize,
Richard Smithf39aec12012-02-04 07:07:42 +00001006 PDiag(diag::err_array_size_not_integral) << getLangOptions().CPlusPlus0x,
Richard Smithebaf0e62011-10-18 20:49:44 +00001007 PDiag(diag::err_array_size_incomplete_type)
1008 << ArraySize->getSourceRange(),
1009 PDiag(diag::err_array_size_explicit_conversion),
1010 PDiag(diag::note_array_size_conversion),
1011 PDiag(diag::err_array_size_ambiguous_conversion),
1012 PDiag(diag::note_array_size_conversion),
1013 PDiag(getLangOptions().CPlusPlus0x ?
1014 diag::warn_cxx98_compat_array_size_conversion :
Richard Smithf39aec12012-02-04 07:07:42 +00001015 diag::ext_array_size_conversion),
1016 /*AllowScopedEnumerations*/ false);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001017 if (ConvertedSize.isInvalid())
1018 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001019
John McCall9ae2f072010-08-23 23:25:46 +00001020 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001021 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001022 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001023 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001024
Richard Smith0b458fd2012-02-04 05:35:53 +00001025 // C++98 [expr.new]p7:
1026 // The expression in a direct-new-declarator shall have integral type
1027 // with a non-negative value.
1028 //
1029 // Let's see if this is a constant < 0. If so, we reject it out of
1030 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1031 // array type.
1032 //
1033 // Note: such a construct has well-defined semantics in C++11: it throws
1034 // std::bad_array_new_length.
Sebastian Redl28507842009-02-26 14:39:58 +00001035 if (!ArraySize->isValueDependent()) {
1036 llvm::APSInt Value;
Richard Smith0b458fd2012-02-04 05:35:53 +00001037 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl28507842009-02-26 14:39:58 +00001038 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001039 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smith0b458fd2012-02-04 05:35:53 +00001040 Value.isUnsigned())) {
1041 if (getLangOptions().CPlusPlus0x)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001042 Diag(ArraySize->getSourceRange().getBegin(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001043 diag::warn_typecheck_negative_array_new_size)
Douglas Gregor2767ce22010-08-18 00:39:00 +00001044 << ArraySize->getSourceRange();
Richard Smith0b458fd2012-02-04 05:35:53 +00001045 else
1046 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1047 diag::err_typecheck_negative_array_size)
1048 << ArraySize->getSourceRange());
1049 } else if (!AllocType->isDependentType()) {
1050 unsigned ActiveSizeBits =
1051 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1052 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1053 if (getLangOptions().CPlusPlus0x)
1054 Diag(ArraySize->getSourceRange().getBegin(),
1055 diag::warn_array_new_too_large)
1056 << Value.toString(10)
1057 << ArraySize->getSourceRange();
1058 else
1059 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1060 diag::err_array_too_large)
1061 << Value.toString(10)
1062 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +00001063 }
1064 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001065 } else if (TypeIdParens.isValid()) {
1066 // Can't have dynamic array size when the type-id is in parentheses.
1067 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1068 << ArraySize->getSourceRange()
1069 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1070 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001071
Douglas Gregor4bd40312010-07-13 15:54:32 +00001072 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001073 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001074 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001075
John McCallf85e1932011-06-15 23:02:42 +00001076 // ARC: warn about ABI issues.
1077 if (getLangOptions().ObjCAutoRefCount) {
1078 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1079 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1080 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1081 << 0 << BaseAllocType;
1082 }
1083
John McCall7d166272011-05-15 07:14:44 +00001084 // Note that we do *not* convert the argument in any way. It can
1085 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001086 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001087
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001088 FunctionDecl *OperatorNew = 0;
1089 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001090 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1091 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001092
Sebastian Redl28507842009-02-26 14:39:58 +00001093 if (!AllocType->isDependentType() &&
1094 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1095 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001096 SourceRange(PlacementLParen, PlacementRParen),
1097 UseGlobal, AllocType, ArraySize, PlaceArgs,
1098 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001099 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001100
1101 // If this is an array allocation, compute whether the usual array
1102 // deallocation function for the type has a size_t parameter.
1103 bool UsualArrayDeleteWantsSize = false;
1104 if (ArraySize && !AllocType->isDependentType())
1105 UsualArrayDeleteWantsSize
1106 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1107
Chris Lattner5f9e2722011-07-23 10:55:15 +00001108 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001109 if (OperatorNew) {
1110 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001111 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001112 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001113 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001114 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001115
Anders Carlsson28e94832010-05-03 02:07:56 +00001116 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001117 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001118 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001119 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001120
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001121 NumPlaceArgs = AllPlaceArgs.size();
1122 if (NumPlaceArgs > 0)
1123 PlaceArgs = &AllPlaceArgs[0];
1124 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001125
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001126 // Warn if the type is over-aligned and is being allocated by global operator
1127 // new.
Nick Lewycky507a8a32012-02-04 03:30:14 +00001128 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001129 (OperatorNew->isImplicit() ||
1130 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1131 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1132 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1133 if (Align > SuitableAlign)
1134 Diag(StartLoc, diag::warn_overaligned_type)
1135 << AllocType
1136 << unsigned(Align / Context.getCharWidth())
1137 << unsigned(SuitableAlign / Context.getCharWidth());
1138 }
1139 }
1140
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001141 bool Init = ConstructorLParen.isValid();
1142 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001143 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001144 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001145 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1146 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001147 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001148
Anders Carlsson48c95012010-05-03 15:45:23 +00001149 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001150 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001151 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1152 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001153
Anders Carlsson48c95012010-05-03 15:45:23 +00001154 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1155 return ExprError();
1156 }
1157
Douglas Gregor99a2e602009-12-16 01:38:02 +00001158 if (!AllocType->isDependentType() &&
1159 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1160 // C++0x [expr.new]p15:
1161 // A new-expression that creates an object of type T initializes that
1162 // object as follows:
1163 InitializationKind Kind
1164 // - If the new-initializer is omitted, the object is default-
1165 // initialized (8.5); if no initialization is performed,
1166 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001167 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001168 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001169 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001170 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001171 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001172 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001173
Douglas Gregor99a2e602009-12-16 01:38:02 +00001174 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001175 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001176 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001177 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001178 move(ConstructorArgs));
1179 if (FullInit.isInvalid())
1180 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001181
1182 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001183 // constructor call, which CXXNewExpr handles directly.
1184 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1185 if (CXXBindTemporaryExpr *Binder
1186 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1187 FullInitExpr = Binder->getSubExpr();
1188 if (CXXConstructExpr *Construct
1189 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1190 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001191 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001192 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1193 AEnd = Construct->arg_end();
1194 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001195 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001196 } else {
1197 // Take the converted initializer.
1198 ConvertedConstructorArgs.push_back(FullInit.release());
1199 }
1200 } else {
1201 // No initialization required.
1202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001203
Douglas Gregor99a2e602009-12-16 01:38:02 +00001204 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001205 NumConsArgs = ConvertedConstructorArgs.size();
1206 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001207 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001208
Douglas Gregor6d908702010-02-26 05:06:18 +00001209 // Mark the new and delete operators as referenced.
1210 if (OperatorNew)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001211 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6d908702010-02-26 05:06:18 +00001212 if (OperatorDelete)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001213 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6d908702010-02-26 05:06:18 +00001214
John McCall84ff0fc2011-07-13 20:12:57 +00001215 // C++0x [expr.new]p17:
1216 // If the new expression creates an array of objects of class type,
1217 // access and ambiguity control are done for the destructor.
1218 if (ArraySize && Constructor) {
1219 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00001220 MarkFunctionReferenced(StartLoc, dtor);
John McCall84ff0fc2011-07-13 20:12:57 +00001221 CheckDestructorAccess(StartLoc, dtor,
1222 PDiag(diag::err_access_dtor)
1223 << Context.getBaseElementType(AllocType));
1224 }
1225 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001226
Sebastian Redlf53597f2009-03-15 17:47:39 +00001227 PlacementArgs.release();
1228 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001229
Ted Kremenekad7fe862010-02-11 22:51:03 +00001230 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001231 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001232 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001233 ConsArgs, NumConsArgs,
1234 HadMultipleCandidates,
1235 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001236 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001237 ResultType, AllocTypeInfo,
1238 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001239 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001240 TypeRange.getEnd(),
1241 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001242}
1243
1244/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1245/// in a new-expression.
1246/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001247bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001248 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001249 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1250 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001251 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001252 return Diag(Loc, diag::err_bad_new_type)
1253 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001254 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001255 return Diag(Loc, diag::err_bad_new_type)
1256 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001257 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001258 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001259 PDiag(diag::err_new_incomplete_type)
1260 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001261 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001262 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001263 diag::err_allocation_of_abstract_type))
1264 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001265 else if (AllocType->isVariablyModifiedType())
1266 return Diag(Loc, diag::err_variably_modified_new_type)
1267 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001268 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1269 return Diag(Loc, diag::err_address_space_qualified_new)
1270 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001271 else if (getLangOptions().ObjCAutoRefCount) {
1272 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1273 QualType BaseAllocType = Context.getBaseElementType(AT);
1274 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1275 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001276 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001277 << BaseAllocType;
1278 }
1279 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001280
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001281 return false;
1282}
1283
Douglas Gregor6d908702010-02-26 05:06:18 +00001284/// \brief Determine whether the given function is a non-placement
1285/// deallocation function.
1286static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1287 if (FD->isInvalidDecl())
1288 return false;
1289
1290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1291 return Method->isUsualDeallocationFunction();
1292
1293 return ((FD->getOverloadedOperator() == OO_Delete ||
1294 FD->getOverloadedOperator() == OO_Array_Delete) &&
1295 FD->getNumParams() == 1);
1296}
1297
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001298/// FindAllocationFunctions - Finds the overloads of operator new and delete
1299/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001300bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1301 bool UseGlobal, QualType AllocType,
1302 bool IsArray, Expr **PlaceArgs,
1303 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001304 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001305 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001306 // --- Choosing an allocation function ---
1307 // C++ 5.3.4p8 - 14 & 18
1308 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1309 // in the scope of the allocated class.
1310 // 2) If an array size is given, look for operator new[], else look for
1311 // operator new.
1312 // 3) The first argument is always size_t. Append the arguments from the
1313 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001314
Chris Lattner5f9e2722011-07-23 10:55:15 +00001315 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001316 // We don't care about the actual value of this argument.
1317 // FIXME: Should the Sema create the expression and embed it in the syntax
1318 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001319 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001320 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001321 Context.getSizeType(),
1322 SourceLocation());
1323 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001324 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1325
Douglas Gregor6d908702010-02-26 05:06:18 +00001326 // C++ [expr.new]p8:
1327 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001328 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001329 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001330 // type, the allocation function's name is operator new[] and the
1331 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001332 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1333 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001334 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1335 IsArray ? OO_Array_Delete : OO_Delete);
1336
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001337 QualType AllocElemType = Context.getBaseElementType(AllocType);
1338
1339 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001340 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001341 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001342 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001343 AllocArgs.size(), Record, /*AllowMissing=*/true,
1344 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001345 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001346 }
1347 if (!OperatorNew) {
1348 // Didn't find a member overload. Look for a global one.
1349 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001350 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001351 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001352 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1353 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001354 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001355 }
1356
John McCall9c82afc2010-04-20 02:18:25 +00001357 // We don't need an operator delete if we're running under
1358 // -fno-exceptions.
1359 if (!getLangOptions().Exceptions) {
1360 OperatorDelete = 0;
1361 return false;
1362 }
1363
Anders Carlssond9583892009-05-31 20:26:12 +00001364 // FindAllocationOverload can change the passed in arguments, so we need to
1365 // copy them back.
1366 if (NumPlaceArgs > 0)
1367 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Douglas Gregor6d908702010-02-26 05:06:18 +00001369 // C++ [expr.new]p19:
1370 //
1371 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001372 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001373 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001374 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001375 // the scope of T. If this lookup fails to find the name, or if
1376 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001377 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001378 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001379 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001380 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001381 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001382 LookupQualifiedName(FoundDelete, RD);
1383 }
John McCall90c8c572010-03-18 08:19:33 +00001384 if (FoundDelete.isAmbiguous())
1385 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001386
1387 if (FoundDelete.empty()) {
1388 DeclareGlobalNewDelete();
1389 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1390 }
1391
1392 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001393
Chris Lattner5f9e2722011-07-23 10:55:15 +00001394 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001395
John McCalledeb6c92010-09-14 21:34:24 +00001396 // Whether we're looking for a placement operator delete is dictated
1397 // by whether we selected a placement operator new, not by whether
1398 // we had explicit placement arguments. This matters for things like
1399 // struct A { void *operator new(size_t, int = 0); ... };
1400 // A *a = new A()
1401 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1402
1403 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001404 // C++ [expr.new]p20:
1405 // A declaration of a placement deallocation function matches the
1406 // declaration of a placement allocation function if it has the
1407 // same number of parameters and, after parameter transformations
1408 // (8.3.5), all parameter types except the first are
1409 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001410 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001411 // To perform this comparison, we compute the function type that
1412 // the deallocation function should have, and use that type both
1413 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001414 //
1415 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001416 QualType ExpectedFunctionType;
1417 {
1418 const FunctionProtoType *Proto
1419 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001420
Chris Lattner5f9e2722011-07-23 10:55:15 +00001421 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001422 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001423 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1424 ArgTypes.push_back(Proto->getArgType(I));
1425
John McCalle23cf432010-12-14 08:05:40 +00001426 FunctionProtoType::ExtProtoInfo EPI;
1427 EPI.Variadic = Proto->isVariadic();
1428
Douglas Gregor6d908702010-02-26 05:06:18 +00001429 ExpectedFunctionType
1430 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001431 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001432 }
1433
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001434 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001435 DEnd = FoundDelete.end();
1436 D != DEnd; ++D) {
1437 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001438 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001439 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1440 // Perform template argument deduction to try to match the
1441 // expected function type.
1442 TemplateDeductionInfo Info(Context, StartLoc);
1443 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1444 continue;
1445 } else
1446 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1447
1448 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001449 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001450 }
1451 } else {
1452 // C++ [expr.new]p20:
1453 // [...] Any non-placement deallocation function matches a
1454 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001455 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001456 DEnd = FoundDelete.end();
1457 D != DEnd; ++D) {
1458 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1459 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001460 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001461 }
1462 }
1463
1464 // C++ [expr.new]p20:
1465 // [...] If the lookup finds a single matching deallocation
1466 // function, that function will be called; otherwise, no
1467 // deallocation function will be called.
1468 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001469 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001470
1471 // C++0x [expr.new]p20:
1472 // If the lookup finds the two-parameter form of a usual
1473 // deallocation function (3.7.4.2) and that function, considered
1474 // as a placement deallocation function, would have been
1475 // selected as a match for the allocation function, the program
1476 // is ill-formed.
1477 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1478 isNonPlacementDeallocationFunction(OperatorDelete)) {
1479 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001480 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001481 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1482 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1483 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001484 } else {
1485 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001486 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001487 }
1488 }
1489
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001490 return false;
1491}
1492
Sebastian Redl7f662392008-12-04 22:20:51 +00001493/// FindAllocationOverload - Find an fitting overload for the allocation
1494/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001495bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1496 DeclarationName Name, Expr** Args,
1497 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001498 bool AllowMissing, FunctionDecl *&Operator,
1499 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001500 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1501 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001502 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001503 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001504 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001505 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001506 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001507 }
1508
John McCall90c8c572010-03-18 08:19:33 +00001509 if (R.isAmbiguous())
1510 return true;
1511
1512 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001513
John McCall5769d612010-02-08 23:07:23 +00001514 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001515 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001516 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001517 // Even member operator new/delete are implicitly treated as
1518 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001519 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001520
John McCall9aa472c2010-03-19 07:35:19 +00001521 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1522 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001523 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1524 Candidates,
1525 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001526 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001527 }
1528
John McCall9aa472c2010-03-19 07:35:19 +00001529 FunctionDecl *Fn = cast<FunctionDecl>(D);
1530 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001531 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001532 }
1533
1534 // Do the resolution.
1535 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001536 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001537 case OR_Success: {
1538 // Got one!
1539 FunctionDecl *FnDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00001540 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001541 // The first argument is size_t, and the first parameter must be size_t,
1542 // too. This is checked on declaration and can be assumed. (It can't be
1543 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001544 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001545 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1546 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001547 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1548 FnDecl->getParamDecl(i));
1549
1550 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1551 return true;
1552
John McCall60d7b3a2010-08-24 06:29:42 +00001553 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001554 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001555 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001556 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001557
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001558 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001559 }
1560 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001561 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1562 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001563 return false;
1564 }
1565
1566 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001567 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001568 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1569 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001570 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1571 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001572 return true;
1573
1574 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001575 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001576 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1577 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001578 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1579 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001580 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001581
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001582 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001583 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001584 Diag(StartLoc, diag::err_ovl_deleted_call)
1585 << Best->Function->isDeleted()
1586 << Name
1587 << getDeletedOrUnavailableSuffix(Best->Function)
1588 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001589 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1590 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001591 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001592 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001593 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001594 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001595}
1596
1597
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001598/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1599/// delete. These are:
1600/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001601/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001602/// void* operator new(std::size_t) throw(std::bad_alloc);
1603/// void* operator new[](std::size_t) throw(std::bad_alloc);
1604/// void operator delete(void *) throw();
1605/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001606/// // C++0x:
1607/// void* operator new(std::size_t);
1608/// void* operator new[](std::size_t);
1609/// void operator delete(void *);
1610/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001611/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001612/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001613/// Note that the placement and nothrow forms of new are *not* implicitly
1614/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001615void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001616 if (GlobalNewDeleteDeclared)
1617 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001618
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001619 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001620 // [...] The following allocation and deallocation functions (18.4) are
1621 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001622 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001624 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001625 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001626 // void* operator new[](std::size_t) throw(std::bad_alloc);
1627 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001628 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001629 // C++0x:
1630 // void* operator new(std::size_t);
1631 // void* operator new[](std::size_t);
1632 // void operator delete(void*);
1633 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001634 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001635 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001636 // new, operator new[], operator delete, operator delete[].
1637 //
1638 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1639 // "std" or "bad_alloc" as necessary to form the exception specification.
1640 // However, we do not make these implicit declarations visible to name
1641 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001642 // Note that the C++0x versions of operator delete are deallocation functions,
1643 // and thus are implicitly noexcept.
1644 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001645 // The "std::bad_alloc" class has not yet been declared, so build it
1646 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001647 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1648 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001649 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001651 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001652 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001653 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001654
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001655 GlobalNewDeleteDeclared = true;
1656
1657 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1658 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001659 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001660
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001661 DeclareGlobalAllocationFunction(
1662 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001663 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001664 DeclareGlobalAllocationFunction(
1665 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001666 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001667 DeclareGlobalAllocationFunction(
1668 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1669 Context.VoidTy, VoidPtr);
1670 DeclareGlobalAllocationFunction(
1671 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1672 Context.VoidTy, VoidPtr);
1673}
1674
1675/// DeclareGlobalAllocationFunction - Declares a single implicit global
1676/// allocation function if it doesn't already exist.
1677void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001678 QualType Return, QualType Argument,
1679 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001680 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1681
1682 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001683 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001684 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001685 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001686 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001687 // Only look at non-template functions, as it is the predefined,
1688 // non-templated allocation function we are trying to declare here.
1689 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1690 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001691 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001692 Func->getParamDecl(0)->getType().getUnqualifiedType());
1693 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001694 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1695 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001696 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001697 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001698 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001699 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001700 }
1701 }
1702
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001703 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001705 = (Name.getCXXOverloadedOperator() == OO_New ||
1706 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001707 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001708 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001709 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001710 }
John McCalle23cf432010-12-14 08:05:40 +00001711
1712 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001713 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001714 if (!getLangOptions().CPlusPlus0x) {
1715 EPI.ExceptionSpecType = EST_Dynamic;
1716 EPI.NumExceptions = 1;
1717 EPI.Exceptions = &BadAllocType;
1718 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001719 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001720 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1721 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001722 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001723
John McCalle23cf432010-12-14 08:05:40 +00001724 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001725 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001726 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1727 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001728 FnType, /*TInfo=*/0, SC_None,
1729 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001730 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001731
Nuno Lopesfc284482009-12-16 16:59:22 +00001732 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001733 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001734
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001735 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001736 SourceLocation(), 0,
1737 Argument, /*TInfo=*/0,
1738 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001739 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001740
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001741 // FIXME: Also add this declaration to the IdentifierResolver, but
1742 // make sure it is at the end of the chain to coincide with the
1743 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001744 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001745}
1746
Anders Carlsson78f74552009-11-15 18:45:20 +00001747bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1748 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001749 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001750 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001751 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001752 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001753
John McCalla24dc2e2009-11-17 02:14:36 +00001754 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001755 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001756
Chandler Carruth23893242010-06-28 00:30:51 +00001757 Found.suppressDiagnostics();
1758
Chris Lattner5f9e2722011-07-23 10:55:15 +00001759 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001760 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1761 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001762 NamedDecl *ND = (*F)->getUnderlyingDecl();
1763
1764 // Ignore template operator delete members from the check for a usual
1765 // deallocation function.
1766 if (isa<FunctionTemplateDecl>(ND))
1767 continue;
1768
1769 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001770 Matches.push_back(F.getPair());
1771 }
1772
1773 // There's exactly one suitable operator; pick it.
1774 if (Matches.size() == 1) {
1775 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001776
1777 if (Operator->isDeleted()) {
1778 if (Diagnose) {
1779 Diag(StartLoc, diag::err_deleted_function_use);
1780 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1781 }
1782 return true;
1783 }
1784
John McCall046a7462010-08-04 00:31:26 +00001785 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001786 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001787 return false;
1788
1789 // We found multiple suitable operators; complain about the ambiguity.
1790 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001791 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001792 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1793 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001794
Chris Lattner5f9e2722011-07-23 10:55:15 +00001795 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001796 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1797 Diag((*F)->getUnderlyingDecl()->getLocation(),
1798 diag::note_member_declared_here) << Name;
1799 }
John McCall046a7462010-08-04 00:31:26 +00001800 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001801 }
1802
1803 // We did find operator delete/operator delete[] declarations, but
1804 // none of them were suitable.
1805 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001806 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001807 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1808 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001809
Sean Huntcb45a0f2011-05-12 22:46:25 +00001810 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1811 F != FEnd; ++F)
1812 Diag((*F)->getUnderlyingDecl()->getLocation(),
1813 diag::note_member_declared_here) << Name;
1814 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001815 return true;
1816 }
1817
1818 // Look for a global declaration.
1819 DeclareGlobalNewDelete();
1820 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001821
Anders Carlsson78f74552009-11-15 18:45:20 +00001822 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1823 Expr* DeallocArgs[1];
1824 DeallocArgs[0] = &Null;
1825 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001826 DeallocArgs, 1, TUDecl, !Diagnose,
1827 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001828 return true;
1829
1830 assert(Operator && "Did not find a deallocation function!");
1831 return false;
1832}
1833
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001834/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1835/// @code ::delete ptr; @endcode
1836/// or
1837/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001838ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001839Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001840 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001841 // C++ [expr.delete]p1:
1842 // The operand shall have a pointer type, or a class type having a single
1843 // conversion function to a pointer type. The result has type void.
1844 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001845 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1846
John Wiegley429bb272011-04-08 18:41:53 +00001847 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001848 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001849 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001850 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001851
John Wiegley429bb272011-04-08 18:41:53 +00001852 if (!Ex.get()->isTypeDependent()) {
1853 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001854
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001855 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001856 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001857 PDiag(diag::err_delete_incomplete_class_type)))
1858 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001859
Chris Lattner5f9e2722011-07-23 10:55:15 +00001860 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001861
Fariborz Jahanian53462782009-09-11 21:44:33 +00001862 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001864 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001865 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001866 NamedDecl *D = I.getDecl();
1867 if (isa<UsingShadowDecl>(D))
1868 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1869
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001870 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001871 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001872 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001873
John McCall32daa422010-03-31 01:36:47 +00001874 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001875
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001876 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1877 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001878 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001879 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001880 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001881 if (ObjectPtrConversions.size() == 1) {
1882 // We have a single conversion to a pointer-to-object type. Perform
1883 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001884 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001885 ExprResult Res =
1886 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001887 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001888 AA_Converting);
1889 if (Res.isUsable()) {
1890 Ex = move(Res);
1891 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001892 }
1893 }
1894 else if (ObjectPtrConversions.size() > 1) {
1895 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001896 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001897 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1898 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001899 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001900 }
Sebastian Redl28507842009-02-26 14:39:58 +00001901 }
1902
Sebastian Redlf53597f2009-03-15 17:47:39 +00001903 if (!Type->isPointerType())
1904 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001905 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001906
Ted Kremenek6217b802009-07-29 21:53:49 +00001907 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001908 QualType PointeeElem = Context.getBaseElementType(Pointee);
1909
1910 if (unsigned AddressSpace = Pointee.getAddressSpace())
1911 return Diag(Ex.get()->getLocStart(),
1912 diag::err_address_space_qualified_delete)
1913 << Pointee.getUnqualifiedType() << AddressSpace;
1914
1915 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001916 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001917 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001918 // effectively bans deletion of "void*". However, most compilers support
1919 // this, so we treat it as a warning unless we're in a SFINAE context.
1920 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001921 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001922 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001923 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001924 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001925 } else if (!Pointee->isDependentType()) {
1926 if (!RequireCompleteType(StartLoc, Pointee,
1927 PDiag(diag::warn_delete_incomplete)
1928 << Ex.get()->getSourceRange())) {
1929 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1930 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1931 }
1932 }
1933
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001934 // Perform lvalue-to-rvalue cast, if needed.
1935 Ex = DefaultLvalueConversion(Ex.take());
1936
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001937 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001938 // [Note: a pointer to a const type can be the operand of a
1939 // delete-expression; it is not necessary to cast away the constness
1940 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001941 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001942 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001943 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1944 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001945
1946 if (Pointee->isArrayType() && !ArrayForm) {
1947 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001948 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001949 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1950 ArrayForm = true;
1951 }
1952
Anders Carlssond67c4c32009-08-16 20:29:29 +00001953 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1954 ArrayForm ? OO_Array_Delete : OO_Delete);
1955
Eli Friedmane52c9142011-07-26 22:25:31 +00001956 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001957 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001958 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1959 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001960 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001961
John McCall6ec278d2011-01-27 09:37:56 +00001962 // If we're allocating an array of records, check whether the
1963 // usual operator delete[] has a size_t parameter.
1964 if (ArrayForm) {
1965 // If the user specifically asked to use the global allocator,
1966 // we'll need to do the lookup into the class.
1967 if (UseGlobal)
1968 UsualArrayDeleteWantsSize =
1969 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1970
1971 // Otherwise, the usual operator delete[] should be the
1972 // function we just found.
1973 else if (isa<CXXMethodDecl>(OperatorDelete))
1974 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1975 }
1976
Eli Friedmane52c9142011-07-26 22:25:31 +00001977 if (!PointeeRD->hasTrivialDestructor())
1978 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00001979 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001980 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001981 DiagnoseUseOfDecl(Dtor, StartLoc);
1982 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001983
1984 // C++ [expr.delete]p3:
1985 // In the first alternative (delete object), if the static type of the
1986 // object to be deleted is different from its dynamic type, the static
1987 // type shall be a base class of the dynamic type of the object to be
1988 // deleted and the static type shall have a virtual destructor or the
1989 // behavior is undefined.
1990 //
1991 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001992 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001993 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001994 if (dtor && !dtor->isVirtual()) {
1995 if (PointeeRD->isAbstract()) {
1996 // If the class is abstract, we warn by default, because we're
1997 // sure the code has undefined behavior.
1998 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1999 << PointeeElem;
2000 } else if (!ArrayForm) {
2001 // Otherwise, if this is not an array delete, it's a bit suspect,
2002 // but not necessarily wrong.
2003 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2004 }
2005 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002006 }
John McCallf85e1932011-06-15 23:02:42 +00002007
2008 } else if (getLangOptions().ObjCAutoRefCount &&
2009 PointeeElem->isObjCLifetimeType() &&
2010 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2011 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2012 ArrayForm) {
2013 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2014 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00002015 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002016
Anders Carlssond67c4c32009-08-16 20:29:29 +00002017 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002018 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002019 DeclareGlobalNewDelete();
2020 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002021 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002022 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002023 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002024 OperatorDelete))
2025 return ExprError();
2026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Eli Friedman5f2987c2012-02-02 03:46:19 +00002028 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002029
Douglas Gregord880f522011-02-01 15:50:11 +00002030 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002031 if (PointeeRD) {
2032 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002033 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002034 PDiag(diag::err_access_dtor) << PointeeElem);
2035 }
2036 }
2037
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002038 }
2039
Sebastian Redlf53597f2009-03-15 17:47:39 +00002040 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002041 ArrayFormAsWritten,
2042 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002043 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002044}
2045
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002046/// \brief Check the use of the given variable as a C++ condition in an if,
2047/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002048ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002049 SourceLocation StmtLoc,
2050 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002051 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002052
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002053 // C++ [stmt.select]p2:
2054 // The declarator shall not specify a function or an array.
2055 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002056 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002057 diag::err_invalid_use_of_function_type)
2058 << ConditionVar->getSourceRange());
2059 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002060 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002061 diag::err_invalid_use_of_array_type)
2062 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002063
John Wiegley429bb272011-04-08 18:41:53 +00002064 ExprResult Condition =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002065 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2066 SourceLocation(),
2067 ConditionVar,
2068 ConditionVar->getLocation(),
2069 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002070 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002071
Eli Friedman5f2987c2012-02-02 03:46:19 +00002072 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002073
John Wiegley429bb272011-04-08 18:41:53 +00002074 if (ConvertToBoolean) {
2075 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2076 if (Condition.isInvalid())
2077 return ExprError();
2078 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079
John Wiegley429bb272011-04-08 18:41:53 +00002080 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002081}
2082
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002083/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002084ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002085 // C++ 6.4p4:
2086 // The value of a condition that is an initialized declaration in a statement
2087 // other than a switch statement is the value of the declared variable
2088 // implicitly converted to type bool. If that conversion is ill-formed, the
2089 // program is ill-formed.
2090 // The value of a condition that is an expression is the value of the
2091 // expression, implicitly converted to bool.
2092 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002093 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002094}
Douglas Gregor77a52232008-09-12 00:47:35 +00002095
2096/// Helper function to determine whether this is the (deprecated) C++
2097/// conversion from a string literal to a pointer to non-const char or
2098/// non-const wchar_t (for narrow and wide string literals,
2099/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002100bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002101Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2102 // Look inside the implicit cast, if it exists.
2103 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2104 From = Cast->getSubExpr();
2105
2106 // A string literal (2.13.4) that is not a wide string literal can
2107 // be converted to an rvalue of type "pointer to char"; a wide
2108 // string literal can be converted to an rvalue of type "pointer
2109 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002110 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002111 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002112 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002113 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002114 // This conversion is considered only when there is an
2115 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002116 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2117 switch (StrLit->getKind()) {
2118 case StringLiteral::UTF8:
2119 case StringLiteral::UTF16:
2120 case StringLiteral::UTF32:
2121 // We don't allow UTF literals to be implicitly converted
2122 break;
2123 case StringLiteral::Ascii:
2124 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2125 ToPointeeType->getKind() == BuiltinType::Char_S);
2126 case StringLiteral::Wide:
2127 return ToPointeeType->isWideCharType();
2128 }
2129 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002130 }
2131
2132 return false;
2133}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002134
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002135static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002136 SourceLocation CastLoc,
2137 QualType Ty,
2138 CastKind Kind,
2139 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002140 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002141 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002142 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002143 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002144 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002145 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002146 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002147 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002148
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002149 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002150 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002151 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002152 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002153
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002154 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2155 S.PDiag(diag::err_access_ctor));
2156
2157 ExprResult Result
2158 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2159 move_arg(ConstructorArgs),
2160 HadMultipleCandidates, /*ZeroInit*/ false,
2161 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002162 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002163 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002164
Douglas Gregorba70ab62010-04-16 22:17:36 +00002165 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002167
John McCall2de56d12010-08-25 11:45:40 +00002168 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002169 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002170
Douglas Gregorba70ab62010-04-16 22:17:36 +00002171 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002172 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2173 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002174 if (Result.isInvalid())
2175 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002176 // Record usage of conversion in an implicit cast.
2177 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2178 Result.get()->getType(),
2179 CK_UserDefinedConversion,
2180 Result.get(), 0,
2181 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002182
John McCallca82a822011-09-21 08:36:56 +00002183 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2184
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002185 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002186 }
2187 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002188}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002189
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002190/// PerformImplicitConversion - Perform an implicit conversion of the
2191/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002192/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002193/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002194/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002195ExprResult
2196Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002197 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002198 AssignmentAction Action,
2199 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002200 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002201 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002202 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2203 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002204 if (Res.isInvalid())
2205 return ExprError();
2206 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002207 break;
John Wiegley429bb272011-04-08 18:41:53 +00002208 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002209
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002210 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002211
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002212 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002213 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002214 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002215 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002216 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002217 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002218
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002219 // If the user-defined conversion is specified by a conversion function,
2220 // the initial standard conversion sequence converts the source type to
2221 // the implicit object parameter of the conversion function.
2222 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002223 } else {
2224 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002225 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002226 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002227 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002228 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002229 // initial standard conversion sequence converts the source type to the
2230 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002231 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2232 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002233 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002234 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002235 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002236 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002237 PerformImplicitConversion(From, BeforeToType,
2238 ICS.UserDefined.Before, AA_Converting,
2239 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002240 if (Res.isInvalid())
2241 return ExprError();
2242 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
2245 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002246 = BuildCXXCastArgument(*this,
2247 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002248 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002249 CastKind, cast<CXXMethodDecl>(FD),
2250 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002251 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002252 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002253
2254 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002255 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002256
John Wiegley429bb272011-04-08 18:41:53 +00002257 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002258
Richard Smithc8d7f582011-11-29 22:48:16 +00002259 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2260 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002261 }
John McCall1d318332010-01-12 00:44:57 +00002262
2263 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002264 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002265 PDiag(diag::err_typecheck_ambiguous_condition)
2266 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002267 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002268
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002269 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002270 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002271
2272 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002273 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002274 }
2275
2276 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002277 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002278}
2279
Richard Smithc8d7f582011-11-29 22:48:16 +00002280/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002281/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002282/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002283/// expression. Flavor is the context in which we're performing this
2284/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002285ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002286Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002287 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002288 AssignmentAction Action,
2289 CheckedConversionKind CCK) {
2290 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2291
Mike Stump390b4cc2009-05-16 07:39:55 +00002292 // Overall FIXME: we are recomputing too many types here and doing far too
2293 // much extra work. What this means is that we need to keep track of more
2294 // information that is computed when we try the implicit conversion initially,
2295 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002296 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002297
Douglas Gregor225c41e2008-11-03 19:09:14 +00002298 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002299 // FIXME: When can ToType be a reference type?
2300 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002301 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002302 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002303 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002304 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002305 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002306 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002307 return ExprError();
2308 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2309 ToType, SCS.CopyConstructor,
2310 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002311 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002312 /*ZeroInit*/ false,
2313 CXXConstructExpr::CK_Complete,
2314 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002315 }
John Wiegley429bb272011-04-08 18:41:53 +00002316 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2317 ToType, SCS.CopyConstructor,
2318 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002319 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002320 /*ZeroInit*/ false,
2321 CXXConstructExpr::CK_Complete,
2322 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002323 }
2324
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002325 // Resolve overloaded function references.
2326 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2327 DeclAccessPair Found;
2328 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2329 true, Found);
2330 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002331 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002332
2333 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002334 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002335
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002336 From = FixOverloadedFunctionReference(From, Found, Fn);
2337 FromType = From->getType();
2338 }
2339
Richard Smithc8d7f582011-11-29 22:48:16 +00002340 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002341 switch (SCS.First) {
2342 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002343 // Nothing to do.
2344 break;
2345
Eli Friedmand814eaf2012-01-24 22:51:26 +00002346 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002347 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002348 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002349 ExprResult FromRes = DefaultLvalueConversion(From);
2350 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2351 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002352 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002353 }
John McCallf6a16482010-12-04 03:47:34 +00002354
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002355 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002356 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002357 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2358 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002359 break;
2360
2361 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002362 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002363 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2364 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002365 break;
2366
2367 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002368 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002369 }
2370
Richard Smithc8d7f582011-11-29 22:48:16 +00002371 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002372 switch (SCS.Second) {
2373 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002374 // If both sides are functions (or pointers/references to them), there could
2375 // be incompatible exception declarations.
2376 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002377 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002378 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002379 break;
2380
Douglas Gregor43c79c22009-12-09 00:47:37 +00002381 case ICK_NoReturn_Adjustment:
2382 // If both sides are functions (or pointers/references to them), there could
2383 // be incompatible exception declarations.
2384 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002385 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002386
Richard Smithc8d7f582011-11-29 22:48:16 +00002387 From = ImpCastExprToType(From, ToType, CK_NoOp,
2388 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002389 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002390
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002391 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002392 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002393 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2394 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002395 break;
2396
2397 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002398 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002399 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2400 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002401 break;
2402
2403 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002404 case ICK_Complex_Conversion: {
2405 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2406 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2407 CastKind CK;
2408 if (FromEl->isRealFloatingType()) {
2409 if (ToEl->isRealFloatingType())
2410 CK = CK_FloatingComplexCast;
2411 else
2412 CK = CK_FloatingComplexToIntegralComplex;
2413 } else if (ToEl->isRealFloatingType()) {
2414 CK = CK_IntegralComplexToFloatingComplex;
2415 } else {
2416 CK = CK_IntegralComplexCast;
2417 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002418 From = ImpCastExprToType(From, ToType, CK,
2419 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002420 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002421 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002422
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002423 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002424 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002425 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2426 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002427 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002428 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2429 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002430 break;
2431
Douglas Gregorf9201e02009-02-11 23:02:49 +00002432 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002433 From = ImpCastExprToType(From, ToType, CK_NoOp,
2434 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002435 break;
2436
John McCallf85e1932011-06-15 23:02:42 +00002437 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002438 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002439 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002440 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002441 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002442 Diag(From->getSourceRange().getBegin(),
2443 diag::ext_typecheck_convert_incompatible_pointer)
2444 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002445 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002446 else
2447 Diag(From->getSourceRange().getBegin(),
2448 diag::ext_typecheck_convert_incompatible_pointer)
2449 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002450 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002451
Douglas Gregor926df6c2011-06-11 01:09:30 +00002452 if (From->getType()->isObjCObjectPointerType() &&
2453 ToType->isObjCObjectPointerType())
2454 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002455 }
2456 else if (getLangOptions().ObjCAutoRefCount &&
2457 !CheckObjCARCUnavailableWeakConversion(ToType,
2458 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002459 if (Action == AA_Initializing)
2460 Diag(From->getSourceRange().getBegin(),
2461 diag::err_arc_weak_unavailable_assign);
2462 else
2463 Diag(From->getSourceRange().getBegin(),
2464 diag::err_arc_convesion_of_weak_unavailable)
2465 << (Action == AA_Casting) << From->getType() << ToType
2466 << From->getSourceRange();
2467 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002468
John McCalldaa8e4e2010-11-15 09:13:47 +00002469 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002470 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002471 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002472 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002473
2474 // Make sure we extend blocks if necessary.
2475 // FIXME: doing this here is really ugly.
2476 if (Kind == CK_BlockPointerToObjCPointerCast) {
2477 ExprResult E = From;
2478 (void) PrepareCastToObjCObjectPointer(E);
2479 From = E.take();
2480 }
2481
Richard Smithc8d7f582011-11-29 22:48:16 +00002482 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2483 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002484 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002485 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002486
Anders Carlsson61faec12009-09-12 04:46:44 +00002487 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002488 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002489 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002490 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002491 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002492 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002493 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002494 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2495 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002496 break;
2497 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002498
Abramo Bagnara737d5442011-04-07 09:26:19 +00002499 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002500 // Perform half-to-boolean conversion via float.
2501 if (From->getType()->isHalfType()) {
2502 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2503 FromType = Context.FloatTy;
2504 }
2505
Richard Smithc8d7f582011-11-29 22:48:16 +00002506 From = ImpCastExprToType(From, Context.BoolTy,
2507 ScalarTypeToBooleanCastKind(FromType),
2508 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002509 break;
2510
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002511 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002512 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002513 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002514 ToType.getNonReferenceType(),
2515 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002516 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002517 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002518 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002519 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002520
Richard Smithc8d7f582011-11-29 22:48:16 +00002521 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2522 CK_DerivedToBase, From->getValueKind(),
2523 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002524 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002525 }
2526
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002527 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002528 From = ImpCastExprToType(From, ToType, CK_BitCast,
2529 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002530 break;
2531
2532 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002533 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2534 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002535 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002536
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002537 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002538 // Case 1. x -> _Complex y
2539 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2540 QualType ElType = ToComplex->getElementType();
2541 bool isFloatingComplex = ElType->isRealFloatingType();
2542
2543 // x -> y
2544 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2545 // do nothing
2546 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002547 From = ImpCastExprToType(From, ElType,
2548 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002549 } else {
2550 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002551 From = ImpCastExprToType(From, ElType,
2552 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002553 }
2554 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002555 From = ImpCastExprToType(From, ToType,
2556 isFloatingComplex ? CK_FloatingRealToComplex
2557 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002558
2559 // Case 2. _Complex x -> y
2560 } else {
2561 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2562 assert(FromComplex);
2563
2564 QualType ElType = FromComplex->getElementType();
2565 bool isFloatingComplex = ElType->isRealFloatingType();
2566
2567 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002568 From = ImpCastExprToType(From, ElType,
2569 isFloatingComplex ? CK_FloatingComplexToReal
2570 : CK_IntegralComplexToReal,
2571 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002572
2573 // x -> y
2574 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2575 // do nothing
2576 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002577 From = ImpCastExprToType(From, ToType,
2578 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2579 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002580 } else {
2581 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002582 From = ImpCastExprToType(From, ToType,
2583 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2584 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002585 }
2586 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002587 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002588
2589 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002590 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2591 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002592 break;
2593 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002594
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002595 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002596 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002597 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002598 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2599 if (FromRes.isInvalid())
2600 return ExprError();
2601 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002602 assert ((ConvTy == Sema::Compatible) &&
2603 "Improper transparent union conversion");
2604 (void)ConvTy;
2605 break;
2606 }
2607
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002608 case ICK_Lvalue_To_Rvalue:
2609 case ICK_Array_To_Pointer:
2610 case ICK_Function_To_Pointer:
2611 case ICK_Qualification:
2612 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002613 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002614 }
2615
2616 switch (SCS.Third) {
2617 case ICK_Identity:
2618 // Nothing to do.
2619 break;
2620
Sebastian Redl906082e2010-07-20 04:20:21 +00002621 case ICK_Qualification: {
2622 // The qualification keeps the category of the inner expression, unless the
2623 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002624 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002625 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002626 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2627 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002628
Douglas Gregor069a6da2011-03-14 16:13:32 +00002629 if (SCS.DeprecatedStringLiteralToCharPtr &&
2630 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002631 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2632 << ToType.getNonReferenceType();
2633
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002634 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002635 }
2636
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002637 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002638 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002639 }
2640
John Wiegley429bb272011-04-08 18:41:53 +00002641 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002642}
2643
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002644ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002645 SourceLocation KWLoc,
2646 ParsedType Ty,
2647 SourceLocation RParen) {
2648 TypeSourceInfo *TSInfo;
2649 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002651 if (!TSInfo)
2652 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002653 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002654}
2655
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002656/// \brief Check the completeness of a type in a unary type trait.
2657///
2658/// If the particular type trait requires a complete type, tries to complete
2659/// it. If completing the type fails, a diagnostic is emitted and false
2660/// returned. If completing the type succeeds or no completion was required,
2661/// returns true.
2662static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2663 UnaryTypeTrait UTT,
2664 SourceLocation Loc,
2665 QualType ArgTy) {
2666 // C++0x [meta.unary.prop]p3:
2667 // For all of the class templates X declared in this Clause, instantiating
2668 // that template with a template argument that is a class template
2669 // specialization may result in the implicit instantiation of the template
2670 // argument if and only if the semantics of X require that the argument
2671 // must be a complete type.
2672 // We apply this rule to all the type trait expressions used to implement
2673 // these class templates. We also try to follow any GCC documented behavior
2674 // in these expressions to ensure portability of standard libraries.
2675 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002676 // is_complete_type somewhat obviously cannot require a complete type.
2677 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002678 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002679
2680 // These traits are modeled on the type predicates in C++0x
2681 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2682 // requiring a complete type, as whether or not they return true cannot be
2683 // impacted by the completeness of the type.
2684 case UTT_IsVoid:
2685 case UTT_IsIntegral:
2686 case UTT_IsFloatingPoint:
2687 case UTT_IsArray:
2688 case UTT_IsPointer:
2689 case UTT_IsLvalueReference:
2690 case UTT_IsRvalueReference:
2691 case UTT_IsMemberFunctionPointer:
2692 case UTT_IsMemberObjectPointer:
2693 case UTT_IsEnum:
2694 case UTT_IsUnion:
2695 case UTT_IsClass:
2696 case UTT_IsFunction:
2697 case UTT_IsReference:
2698 case UTT_IsArithmetic:
2699 case UTT_IsFundamental:
2700 case UTT_IsObject:
2701 case UTT_IsScalar:
2702 case UTT_IsCompound:
2703 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002704 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002705
2706 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2707 // which requires some of its traits to have the complete type. However,
2708 // the completeness of the type cannot impact these traits' semantics, and
2709 // so they don't require it. This matches the comments on these traits in
2710 // Table 49.
2711 case UTT_IsConst:
2712 case UTT_IsVolatile:
2713 case UTT_IsSigned:
2714 case UTT_IsUnsigned:
2715 return true;
2716
2717 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002718 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002719 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002720 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002721 case UTT_IsStandardLayout:
2722 case UTT_IsPOD:
2723 case UTT_IsLiteral:
2724 case UTT_IsEmpty:
2725 case UTT_IsPolymorphic:
2726 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002727 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002728
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002729 // These traits require a complete type.
2730 case UTT_IsFinal:
2731
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002732 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002733 // [meta.unary.prop] despite not being named the same. They are specified
2734 // by both GCC and the Embarcadero C++ compiler, and require the complete
2735 // type due to the overarching C++0x type predicates being implemented
2736 // requiring the complete type.
2737 case UTT_HasNothrowAssign:
2738 case UTT_HasNothrowConstructor:
2739 case UTT_HasNothrowCopy:
2740 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002741 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002742 case UTT_HasTrivialCopy:
2743 case UTT_HasTrivialDestructor:
2744 case UTT_HasVirtualDestructor:
2745 // Arrays of unknown bound are expressly allowed.
2746 QualType ElTy = ArgTy;
2747 if (ArgTy->isIncompleteArrayType())
2748 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2749
2750 // The void type is expressly allowed.
2751 if (ElTy->isVoidType())
2752 return true;
2753
2754 return !S.RequireCompleteType(
2755 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002756 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002757 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002758}
2759
2760static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2761 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002762 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002763
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002764 ASTContext &C = Self.Context;
2765 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002766 // Type trait expressions corresponding to the primary type category
2767 // predicates in C++0x [meta.unary.cat].
2768 case UTT_IsVoid:
2769 return T->isVoidType();
2770 case UTT_IsIntegral:
2771 return T->isIntegralType(C);
2772 case UTT_IsFloatingPoint:
2773 return T->isFloatingType();
2774 case UTT_IsArray:
2775 return T->isArrayType();
2776 case UTT_IsPointer:
2777 return T->isPointerType();
2778 case UTT_IsLvalueReference:
2779 return T->isLValueReferenceType();
2780 case UTT_IsRvalueReference:
2781 return T->isRValueReferenceType();
2782 case UTT_IsMemberFunctionPointer:
2783 return T->isMemberFunctionPointerType();
2784 case UTT_IsMemberObjectPointer:
2785 return T->isMemberDataPointerType();
2786 case UTT_IsEnum:
2787 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002788 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002789 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002790 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002791 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002792 case UTT_IsFunction:
2793 return T->isFunctionType();
2794
2795 // Type trait expressions which correspond to the convenient composition
2796 // predicates in C++0x [meta.unary.comp].
2797 case UTT_IsReference:
2798 return T->isReferenceType();
2799 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002800 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002801 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002802 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002803 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002804 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002805 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002806 // Note: semantic analysis depends on Objective-C lifetime types to be
2807 // considered scalar types. However, such types do not actually behave
2808 // like scalar types at run time (since they may require retain/release
2809 // operations), so we report them as non-scalar.
2810 if (T->isObjCLifetimeType()) {
2811 switch (T.getObjCLifetime()) {
2812 case Qualifiers::OCL_None:
2813 case Qualifiers::OCL_ExplicitNone:
2814 return true;
2815
2816 case Qualifiers::OCL_Strong:
2817 case Qualifiers::OCL_Weak:
2818 case Qualifiers::OCL_Autoreleasing:
2819 return false;
2820 }
2821 }
2822
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002823 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002824 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002825 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002826 case UTT_IsMemberPointer:
2827 return T->isMemberPointerType();
2828
2829 // Type trait expressions which correspond to the type property predicates
2830 // in C++0x [meta.unary.prop].
2831 case UTT_IsConst:
2832 return T.isConstQualified();
2833 case UTT_IsVolatile:
2834 return T.isVolatileQualified();
2835 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002836 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002837 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002838 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002839 case UTT_IsStandardLayout:
2840 return T->isStandardLayoutType();
2841 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002842 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002843 case UTT_IsLiteral:
2844 return T->isLiteralType();
2845 case UTT_IsEmpty:
2846 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2847 return !RD->isUnion() && RD->isEmpty();
2848 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002849 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002850 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2851 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002852 return false;
2853 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002854 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2855 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002856 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002857 case UTT_IsFinal:
2858 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2859 return RD->hasAttr<FinalAttr>();
2860 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002861 case UTT_IsSigned:
2862 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002863 case UTT_IsUnsigned:
2864 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002865
2866 // Type trait expressions which query classes regarding their construction,
2867 // destruction, and copying. Rather than being based directly on the
2868 // related type predicates in the standard, they are specified by both
2869 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2870 // specifications.
2871 //
2872 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2873 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002874 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002875 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2876 // If __is_pod (type) is true then the trait is true, else if type is
2877 // a cv class or union type (or array thereof) with a trivial default
2878 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002879 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002880 return true;
2881 if (const RecordType *RT =
2882 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002883 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002884 return false;
2885 case UTT_HasTrivialCopy:
2886 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2887 // If __is_pod (type) is true or type is a reference type then
2888 // the trait is true, else if type is a cv class or union type
2889 // with a trivial copy constructor ([class.copy]) then the trait
2890 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002891 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002892 return true;
2893 if (const RecordType *RT = T->getAs<RecordType>())
2894 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2895 return false;
2896 case UTT_HasTrivialAssign:
2897 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2898 // If type is const qualified or is a reference type then the
2899 // trait is false. Otherwise if __is_pod (type) is true then the
2900 // trait is true, else if type is a cv class or union type with
2901 // a trivial copy assignment ([class.copy]) then the trait is
2902 // true, else it is false.
2903 // Note: the const and reference restrictions are interesting,
2904 // given that const and reference members don't prevent a class
2905 // from having a trivial copy assignment operator (but do cause
2906 // errors if the copy assignment operator is actually used, q.v.
2907 // [class.copy]p12).
2908
2909 if (C.getBaseElementType(T).isConstQualified())
2910 return false;
John McCallf85e1932011-06-15 23:02:42 +00002911 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002912 return true;
2913 if (const RecordType *RT = T->getAs<RecordType>())
2914 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2915 return false;
2916 case UTT_HasTrivialDestructor:
2917 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2918 // If __is_pod (type) is true or type is a reference type
2919 // then the trait is true, else if type is a cv class or union
2920 // type (or array thereof) with a trivial destructor
2921 // ([class.dtor]) then the trait is true, else it is
2922 // false.
John McCallf85e1932011-06-15 23:02:42 +00002923 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002924 return true;
John McCallf85e1932011-06-15 23:02:42 +00002925
2926 // Objective-C++ ARC: autorelease types don't require destruction.
2927 if (T->isObjCLifetimeType() &&
2928 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2929 return true;
2930
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002931 if (const RecordType *RT =
2932 C.getBaseElementType(T)->getAs<RecordType>())
2933 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2934 return false;
2935 // TODO: Propagate nothrowness for implicitly declared special members.
2936 case UTT_HasNothrowAssign:
2937 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2938 // If type is const qualified or is a reference type then the
2939 // trait is false. Otherwise if __has_trivial_assign (type)
2940 // is true then the trait is true, else if type is a cv class
2941 // or union type with copy assignment operators that are known
2942 // not to throw an exception then the trait is true, else it is
2943 // false.
2944 if (C.getBaseElementType(T).isConstQualified())
2945 return false;
2946 if (T->isReferenceType())
2947 return false;
John McCallf85e1932011-06-15 23:02:42 +00002948 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2949 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002950 if (const RecordType *RT = T->getAs<RecordType>()) {
2951 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2952 if (RD->hasTrivialCopyAssignment())
2953 return true;
2954
2955 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002956 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002957 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2958 Sema::LookupOrdinaryName);
2959 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002960 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002961 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2962 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002963 if (isa<FunctionTemplateDecl>(*Op))
2964 continue;
2965
Sebastian Redlf8aca862010-09-14 23:40:14 +00002966 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2967 if (Operator->isCopyAssignmentOperator()) {
2968 FoundAssign = true;
2969 const FunctionProtoType *CPT
2970 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002971 if (CPT->getExceptionSpecType() == EST_Delayed)
2972 return false;
2973 if (!CPT->isNothrow(Self.Context))
2974 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002975 }
2976 }
2977 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002978
Richard Smith7a614d82011-06-11 17:19:42 +00002979 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002980 }
2981 return false;
2982 case UTT_HasNothrowCopy:
2983 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2984 // If __has_trivial_copy (type) is true then the trait is true, else
2985 // if type is a cv class or union type with copy constructors that are
2986 // known not to throw an exception then the trait is true, else it is
2987 // false.
John McCallf85e1932011-06-15 23:02:42 +00002988 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002989 return true;
2990 if (const RecordType *RT = T->getAs<RecordType>()) {
2991 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2992 if (RD->hasTrivialCopyConstructor())
2993 return true;
2994
2995 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002996 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002997 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002998 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002999 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003000 // A template constructor is never a copy constructor.
3001 // FIXME: However, it may actually be selected at the actual overload
3002 // resolution point.
3003 if (isa<FunctionTemplateDecl>(*Con))
3004 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003005 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3006 if (Constructor->isCopyConstructor(FoundTQs)) {
3007 FoundConstructor = true;
3008 const FunctionProtoType *CPT
3009 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003010 if (CPT->getExceptionSpecType() == EST_Delayed)
3011 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003012 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00003013 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00003014 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3015 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003016 }
3017 }
3018
Richard Smith7a614d82011-06-11 17:19:42 +00003019 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003020 }
3021 return false;
3022 case UTT_HasNothrowConstructor:
3023 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3024 // If __has_trivial_constructor (type) is true then the trait is
3025 // true, else if type is a cv class or union type (or array
3026 // thereof) with a default constructor that is known not to
3027 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003028 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003029 return true;
3030 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3031 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003032 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003033 return true;
3034
Sebastian Redl751025d2010-09-13 22:02:47 +00003035 DeclContext::lookup_const_iterator Con, ConEnd;
3036 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3037 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003038 // FIXME: In C++0x, a constructor template can be a default constructor.
3039 if (isa<FunctionTemplateDecl>(*Con))
3040 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003041 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3042 if (Constructor->isDefaultConstructor()) {
3043 const FunctionProtoType *CPT
3044 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003045 if (CPT->getExceptionSpecType() == EST_Delayed)
3046 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003047 // TODO: check whether evaluating default arguments can throw.
3048 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003049 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003050 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003051 }
3052 }
3053 return false;
3054 case UTT_HasVirtualDestructor:
3055 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3056 // If type is a class type with a virtual destructor ([class.dtor])
3057 // then the trait is true, else it is false.
3058 if (const RecordType *Record = T->getAs<RecordType>()) {
3059 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003060 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003061 return Destructor->isVirtual();
3062 }
3063 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003064
3065 // These type trait expressions are modeled on the specifications for the
3066 // Embarcadero C++0x type trait functions:
3067 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3068 case UTT_IsCompleteType:
3069 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3070 // Returns True if and only if T is a complete type at the point of the
3071 // function call.
3072 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003073 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003074 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003075}
3076
3077ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003078 SourceLocation KWLoc,
3079 TypeSourceInfo *TSInfo,
3080 SourceLocation RParen) {
3081 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003082 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3083 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003084
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003085 bool Value = false;
3086 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003087 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003088
3089 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003090 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003091}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003092
Francois Pichet6ad6f282010-12-07 00:08:36 +00003093ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3094 SourceLocation KWLoc,
3095 ParsedType LhsTy,
3096 ParsedType RhsTy,
3097 SourceLocation RParen) {
3098 TypeSourceInfo *LhsTSInfo;
3099 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3100 if (!LhsTSInfo)
3101 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3102
3103 TypeSourceInfo *RhsTSInfo;
3104 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3105 if (!RhsTSInfo)
3106 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3107
3108 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3109}
3110
3111static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3112 QualType LhsT, QualType RhsT,
3113 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003114 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3115 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003116
3117 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003118 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003119 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003120 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003121 // Base and Derived are not unions and name the same class type without
3122 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003123
John McCalld89d30f2011-01-28 22:02:36 +00003124 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3125 if (!lhsRecord) return false;
3126
3127 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3128 if (!rhsRecord) return false;
3129
3130 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3131 == (lhsRecord == rhsRecord));
3132
3133 if (lhsRecord == rhsRecord)
3134 return !lhsRecord->getDecl()->isUnion();
3135
3136 // C++0x [meta.rel]p2:
3137 // If Base and Derived are class types and are different types
3138 // (ignoring possible cv-qualifiers) then Derived shall be a
3139 // complete type.
3140 if (Self.RequireCompleteType(KeyLoc, RhsT,
3141 diag::err_incomplete_type_used_in_type_trait_expr))
3142 return false;
3143
3144 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3145 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3146 }
John Wiegley20c0da72011-04-27 23:09:49 +00003147 case BTT_IsSame:
3148 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003149 case BTT_TypeCompatible:
3150 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3151 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003152 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003153 case BTT_IsConvertibleTo: {
3154 // C++0x [meta.rel]p4:
3155 // Given the following function prototype:
3156 //
3157 // template <class T>
3158 // typename add_rvalue_reference<T>::type create();
3159 //
3160 // the predicate condition for a template specialization
3161 // is_convertible<From, To> shall be satisfied if and only if
3162 // the return expression in the following code would be
3163 // well-formed, including any implicit conversions to the return
3164 // type of the function:
3165 //
3166 // To test() {
3167 // return create<From>();
3168 // }
3169 //
3170 // Access checking is performed as if in a context unrelated to To and
3171 // From. Only the validity of the immediate context of the expression
3172 // of the return-statement (including conversions to the return type)
3173 // is considered.
3174 //
3175 // We model the initialization as a copy-initialization of a temporary
3176 // of the appropriate type, which for this expression is identical to the
3177 // return statement (since NRVO doesn't apply).
3178 if (LhsT->isObjectType() || LhsT->isFunctionType())
3179 LhsT = Self.Context.getRValueReferenceType(LhsT);
3180
3181 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003182 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003183 Expr::getValueKindForType(LhsT));
3184 Expr *FromPtr = &From;
3185 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3186 SourceLocation()));
3187
Eli Friedman3add9f02012-01-25 01:05:57 +00003188 // Perform the initialization in an unevaluated context within a SFINAE
3189 // trap at translation unit scope.
3190 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003191 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3192 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003193 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003194 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003195 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003196
Douglas Gregor9f361132011-01-27 20:28:01 +00003197 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3198 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3199 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003200 }
3201 llvm_unreachable("Unknown type trait or not implemented");
3202}
3203
3204ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3205 SourceLocation KWLoc,
3206 TypeSourceInfo *LhsTSInfo,
3207 TypeSourceInfo *RhsTSInfo,
3208 SourceLocation RParen) {
3209 QualType LhsT = LhsTSInfo->getType();
3210 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211
John McCalld89d30f2011-01-28 22:02:36 +00003212 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003213 if (getLangOptions().CPlusPlus) {
3214 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3215 << SourceRange(KWLoc, RParen);
3216 return ExprError();
3217 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003218 }
3219
3220 bool Value = false;
3221 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3222 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3223
Francois Pichetf1872372010-12-08 22:35:30 +00003224 // Select trait result type.
3225 QualType ResultType;
3226 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003227 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003228 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3229 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003230 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003231 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003232 }
3233
Francois Pichet6ad6f282010-12-07 00:08:36 +00003234 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3235 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003236 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003237}
3238
John Wiegley21ff2e52011-04-28 00:16:57 +00003239ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3240 SourceLocation KWLoc,
3241 ParsedType Ty,
3242 Expr* DimExpr,
3243 SourceLocation RParen) {
3244 TypeSourceInfo *TSInfo;
3245 QualType T = GetTypeFromParser(Ty, &TSInfo);
3246 if (!TSInfo)
3247 TSInfo = Context.getTrivialTypeSourceInfo(T);
3248
3249 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3250}
3251
3252static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3253 QualType T, Expr *DimExpr,
3254 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003255 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003256
3257 switch(ATT) {
3258 case ATT_ArrayRank:
3259 if (T->isArrayType()) {
3260 unsigned Dim = 0;
3261 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3262 ++Dim;
3263 T = AT->getElementType();
3264 }
3265 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003266 }
John Wiegleycf566412011-04-28 02:06:46 +00003267 return 0;
3268
John Wiegley21ff2e52011-04-28 00:16:57 +00003269 case ATT_ArrayExtent: {
3270 llvm::APSInt Value;
3271 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003272 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3273 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3274 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3275 DimExpr->getSourceRange();
3276 return false;
3277 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003278 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003279 } else {
3280 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3281 DimExpr->getSourceRange();
3282 return false;
3283 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003284
3285 if (T->isArrayType()) {
3286 unsigned D = 0;
3287 bool Matched = false;
3288 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3289 if (Dim == D) {
3290 Matched = true;
3291 break;
3292 }
3293 ++D;
3294 T = AT->getElementType();
3295 }
3296
John Wiegleycf566412011-04-28 02:06:46 +00003297 if (Matched && T->isArrayType()) {
3298 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3299 return CAT->getSize().getLimitedValue();
3300 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003301 }
John Wiegleycf566412011-04-28 02:06:46 +00003302 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003303 }
3304 }
3305 llvm_unreachable("Unknown type trait or not implemented");
3306}
3307
3308ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3309 SourceLocation KWLoc,
3310 TypeSourceInfo *TSInfo,
3311 Expr* DimExpr,
3312 SourceLocation RParen) {
3313 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003314
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003315 // FIXME: This should likely be tracked as an APInt to remove any host
3316 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003317 uint64_t Value = 0;
3318 if (!T->isDependentType())
3319 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3320
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003321 // While the specification for these traits from the Embarcadero C++
3322 // compiler's documentation says the return type is 'unsigned int', Clang
3323 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3324 // compiler, there is no difference. On several other platforms this is an
3325 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003326 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003327 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003328 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003329}
3330
John Wiegley55262202011-04-25 06:54:41 +00003331ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003332 SourceLocation KWLoc,
3333 Expr *Queried,
3334 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003335 // If error parsing the expression, ignore.
3336 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003337 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003338
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003339 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003340
3341 return move(Result);
3342}
3343
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003344static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3345 switch (ET) {
3346 case ET_IsLValueExpr: return E->isLValue();
3347 case ET_IsRValueExpr: return E->isRValue();
3348 }
3349 llvm_unreachable("Expression trait not covered by switch");
3350}
3351
John Wiegley55262202011-04-25 06:54:41 +00003352ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003353 SourceLocation KWLoc,
3354 Expr *Queried,
3355 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003356 if (Queried->isTypeDependent()) {
3357 // Delay type-checking for type-dependent expressions.
3358 } else if (Queried->getType()->isPlaceholderType()) {
3359 ExprResult PE = CheckPlaceholderExpr(Queried);
3360 if (PE.isInvalid()) return ExprError();
3361 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3362 }
3363
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003364 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003365
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003366 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3367 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003368}
3369
Richard Trieudd225092011-09-15 21:56:47 +00003370QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003371 ExprValueKind &VK,
3372 SourceLocation Loc,
3373 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003374 assert(!LHS.get()->getType()->isPlaceholderType() &&
3375 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003376 "placeholders should have been weeded out by now");
3377
3378 // The LHS undergoes lvalue conversions if this is ->*.
3379 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003380 LHS = DefaultLvalueConversion(LHS.take());
3381 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003382 }
3383
3384 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003385 RHS = DefaultLvalueConversion(RHS.take());
3386 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003387
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003388 const char *OpSpelling = isIndirect ? "->*" : ".*";
3389 // C++ 5.5p2
3390 // The binary operator .* [p3: ->*] binds its second operand, which shall
3391 // be of type "pointer to member of T" (where T is a completely-defined
3392 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003393 QualType RHSType = RHS.get()->getType();
3394 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003395 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003396 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003397 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003398 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003399 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003400
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003401 QualType Class(MemPtr->getClass(), 0);
3402
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003403 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3404 // member pointer points must be completely-defined. However, there is no
3405 // reason for this semantic distinction, and the rule is not enforced by
3406 // other compilers. Therefore, we do not check this property, as it is
3407 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003408
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003409 // C++ 5.5p2
3410 // [...] to its first operand, which shall be of class T or of a class of
3411 // which T is an unambiguous and accessible base class. [p3: a pointer to
3412 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003413 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003414 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003415 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3416 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003417 else {
3418 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003419 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003420 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003421 return QualType();
3422 }
3423 }
3424
Richard Trieudd225092011-09-15 21:56:47 +00003425 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003426 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003427 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003428 << OpSpelling << (int)isIndirect)) {
3429 return QualType();
3430 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003431 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003432 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003433 // FIXME: Would it be useful to print full ambiguity paths, or is that
3434 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003435 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003436 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3437 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003438 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003439 return QualType();
3440 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003441 // Cast LHS to type of use.
3442 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003443 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003444
John McCallf871d0c2010-08-07 06:22:56 +00003445 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003446 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003447 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3448 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003449 }
3450
Richard Trieudd225092011-09-15 21:56:47 +00003451 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003452 // Diagnose use of pointer-to-member type which when used as
3453 // the functional cast in a pointer-to-member expression.
3454 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3455 return QualType();
3456 }
John McCallf89e55a2010-11-18 06:31:45 +00003457
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003458 // C++ 5.5p2
3459 // The result is an object or a function of the type specified by the
3460 // second operand.
3461 // The cv qualifiers are the union of those in the pointer and the left side,
3462 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003463 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003464 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003465
Douglas Gregor6b4df912011-01-26 16:40:18 +00003466 // C++0x [expr.mptr.oper]p6:
3467 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003468 // ill-formed if the second operand is a pointer to member function with
3469 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3470 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003471 // is a pointer to member function with ref-qualifier &&.
3472 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3473 switch (Proto->getRefQualifier()) {
3474 case RQ_None:
3475 // Do nothing
3476 break;
3477
3478 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003479 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003480 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003481 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003482 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003483
Douglas Gregor6b4df912011-01-26 16:40:18 +00003484 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003485 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003486 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003487 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003488 break;
3489 }
3490 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003491
John McCallf89e55a2010-11-18 06:31:45 +00003492 // C++ [expr.mptr.oper]p6:
3493 // The result of a .* expression whose second operand is a pointer
3494 // to a data member is of the same value category as its
3495 // first operand. The result of a .* expression whose second
3496 // operand is a pointer to a member function is a prvalue. The
3497 // result of an ->* expression is an lvalue if its second operand
3498 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003499 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003500 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003501 return Context.BoundMemberTy;
3502 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003503 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003504 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003505 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003506 }
John McCallf89e55a2010-11-18 06:31:45 +00003507
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003508 return Result;
3509}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003510
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003511/// \brief Try to convert a type to another according to C++0x 5.16p3.
3512///
3513/// This is part of the parameter validation for the ? operator. If either
3514/// value operand is a class type, the two operands are attempted to be
3515/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003516/// It returns true if the program is ill-formed and has already been diagnosed
3517/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003518static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3519 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003520 bool &HaveConversion,
3521 QualType &ToType) {
3522 HaveConversion = false;
3523 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003524
3525 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003526 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003527 // C++0x 5.16p3
3528 // The process for determining whether an operand expression E1 of type T1
3529 // can be converted to match an operand expression E2 of type T2 is defined
3530 // as follows:
3531 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003532 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003533 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003534 // E1 can be converted to match E2 if E1 can be implicitly converted to
3535 // type "lvalue reference to T2", subject to the constraint that in the
3536 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003537 QualType T = Self.Context.getLValueReferenceType(ToType);
3538 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003539
Douglas Gregorb70cf442010-03-26 20:14:36 +00003540 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3541 if (InitSeq.isDirectReferenceBinding()) {
3542 ToType = T;
3543 HaveConversion = true;
3544 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003545 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003546
Douglas Gregorb70cf442010-03-26 20:14:36 +00003547 if (InitSeq.isAmbiguous())
3548 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003549 }
John McCallb1bdc622010-02-25 01:37:24 +00003550
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003551 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3552 // -- if E1 and E2 have class type, and the underlying class types are
3553 // the same or one is a base class of the other:
3554 QualType FTy = From->getType();
3555 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003556 const RecordType *FRec = FTy->getAs<RecordType>();
3557 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003558 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003559 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003560 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003561 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003562 // E1 can be converted to match E2 if the class of T2 is the
3563 // same type as, or a base class of, the class of T1, and
3564 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003565 if (FRec == TRec || FDerivedFromT) {
3566 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003567 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3568 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003569 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003570 HaveConversion = true;
3571 return false;
3572 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003573
Douglas Gregorb70cf442010-03-26 20:14:36 +00003574 if (InitSeq.isAmbiguous())
3575 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003576 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003577 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003578
Douglas Gregorb70cf442010-03-26 20:14:36 +00003579 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003580 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003581
Douglas Gregorb70cf442010-03-26 20:14:36 +00003582 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3583 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003584 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003585 // an rvalue).
3586 //
3587 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3588 // to the array-to-pointer or function-to-pointer conversions.
3589 if (!TTy->getAs<TagType>())
3590 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003591
Douglas Gregorb70cf442010-03-26 20:14:36 +00003592 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3593 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003594 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003595 ToType = TTy;
3596 if (InitSeq.isAmbiguous())
3597 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3598
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003599 return false;
3600}
3601
3602/// \brief Try to find a common type for two according to C++0x 5.16p5.
3603///
3604/// This is part of the parameter validation for the ? operator. If either
3605/// value operand is a class type, overload resolution is used to find a
3606/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003607static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003608 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003609 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003610 OverloadCandidateSet CandidateSet(QuestionLoc);
3611 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3612 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003613
3614 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003615 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003616 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003617 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003618 ExprResult LHSRes =
3619 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3620 Best->Conversions[0], Sema::AA_Converting);
3621 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003622 break;
John Wiegley429bb272011-04-08 18:41:53 +00003623 LHS = move(LHSRes);
3624
3625 ExprResult RHSRes =
3626 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3627 Best->Conversions[1], Sema::AA_Converting);
3628 if (RHSRes.isInvalid())
3629 break;
3630 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003631 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003632 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003633 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003634 }
3635
Douglas Gregor20093b42009-12-09 23:02:17 +00003636 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003637
3638 // Emit a better diagnostic if one of the expressions is a null pointer
3639 // constant and the other is a pointer type. In this case, the user most
3640 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003641 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003642 return true;
3643
3644 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003645 << LHS.get()->getType() << RHS.get()->getType()
3646 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003647 return true;
3648
Douglas Gregor20093b42009-12-09 23:02:17 +00003649 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003650 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003651 << LHS.get()->getType() << RHS.get()->getType()
3652 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003653 // FIXME: Print the possible common types by printing the return types of
3654 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003655 break;
3656
Douglas Gregor20093b42009-12-09 23:02:17 +00003657 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003658 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003659 }
3660 return true;
3661}
3662
Sebastian Redl76458502009-04-17 16:30:52 +00003663/// \brief Perform an "extended" implicit conversion as returned by
3664/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003665static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003666 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003667 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003668 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003669 Expr *Arg = E.take();
3670 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3671 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003672 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003673 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003674
John Wiegley429bb272011-04-08 18:41:53 +00003675 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003676 return false;
3677}
3678
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003679/// \brief Check the operands of ?: under C++ semantics.
3680///
3681/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3682/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003683QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003684 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003685 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003686 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3687 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003688
3689 // C++0x 5.16p1
3690 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003691 if (!Cond.get()->isTypeDependent()) {
3692 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3693 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003694 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003695 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003696 }
3697
John McCallf89e55a2010-11-18 06:31:45 +00003698 // Assume r-value.
3699 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003700 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003701
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003702 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003703 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003704 return Context.DependentTy;
3705
3706 // C++0x 5.16p2
3707 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003708 QualType LTy = LHS.get()->getType();
3709 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003710 bool LVoid = LTy->isVoidType();
3711 bool RVoid = RTy->isVoidType();
3712 if (LVoid || RVoid) {
3713 // ... then the [l2r] conversions are performed on the second and third
3714 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003715 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3716 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3717 if (LHS.isInvalid() || RHS.isInvalid())
3718 return QualType();
3719 LTy = LHS.get()->getType();
3720 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003721
3722 // ... and one of the following shall hold:
3723 // -- The second or the third operand (but not both) is a throw-
3724 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003725 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3726 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003727 if (LThrow && !RThrow)
3728 return RTy;
3729 if (RThrow && !LThrow)
3730 return LTy;
3731
3732 // -- Both the second and third operands have type void; the result is of
3733 // type void and is an rvalue.
3734 if (LVoid && RVoid)
3735 return Context.VoidTy;
3736
3737 // Neither holds, error.
3738 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3739 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003740 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003741 return QualType();
3742 }
3743
3744 // Neither is void.
3745
3746 // C++0x 5.16p3
3747 // Otherwise, if the second and third operand have different types, and
3748 // either has (cv) class type, and attempt is made to convert each of those
3749 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003750 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003751 (LTy->isRecordType() || RTy->isRecordType())) {
3752 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3753 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003754 QualType L2RType, R2LType;
3755 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003756 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003757 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003758 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003759 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003760
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003761 // If both can be converted, [...] the program is ill-formed.
3762 if (HaveL2R && HaveR2L) {
3763 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003764 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003765 return QualType();
3766 }
3767
3768 // If exactly one conversion is possible, that conversion is applied to
3769 // the chosen operand and the converted operands are used in place of the
3770 // original operands for the remainder of this section.
3771 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003772 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003773 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003774 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003775 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003776 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003777 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003778 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003779 }
3780 }
3781
3782 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003783 // If the second and third operands are glvalues of the same value
3784 // category and have the same type, the result is of that type and
3785 // value category and it is a bit-field if the second or the third
3786 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003787 // We only extend this to bitfields, not to the crazy other kinds of
3788 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003789 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003790 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003791 LHS.get()->isGLValue() &&
3792 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3793 LHS.get()->isOrdinaryOrBitFieldObject() &&
3794 RHS.get()->isOrdinaryOrBitFieldObject()) {
3795 VK = LHS.get()->getValueKind();
3796 if (LHS.get()->getObjectKind() == OK_BitField ||
3797 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003798 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003799 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003800 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003801
3802 // C++0x 5.16p5
3803 // Otherwise, the result is an rvalue. If the second and third operands
3804 // do not have the same type, and either has (cv) class type, ...
3805 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3806 // ... overload resolution is used to determine the conversions (if any)
3807 // to be applied to the operands. If the overload resolution fails, the
3808 // program is ill-formed.
3809 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3810 return QualType();
3811 }
3812
3813 // C++0x 5.16p6
3814 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3815 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003816 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3817 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3818 if (LHS.isInvalid() || RHS.isInvalid())
3819 return QualType();
3820 LTy = LHS.get()->getType();
3821 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003822
3823 // After those conversions, one of the following shall hold:
3824 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003825 // is of that type. If the operands have class type, the result
3826 // is a prvalue temporary of the result type, which is
3827 // copy-initialized from either the second operand or the third
3828 // operand depending on the value of the first operand.
3829 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3830 if (LTy->isRecordType()) {
3831 // The operands have class type. Make a temporary copy.
3832 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003833 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3834 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003835 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003836 if (LHSCopy.isInvalid())
3837 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003838
3839 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3840 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003841 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003842 if (RHSCopy.isInvalid())
3843 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844
John Wiegley429bb272011-04-08 18:41:53 +00003845 LHS = LHSCopy;
3846 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003847 }
3848
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003849 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003850 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003851
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003852 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003853 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003854 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003855
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003856 // -- The second and third operands have arithmetic or enumeration type;
3857 // the usual arithmetic conversions are performed to bring them to a
3858 // common type, and the result is of that type.
3859 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3860 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003861 if (LHS.isInvalid() || RHS.isInvalid())
3862 return QualType();
3863 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003864 }
3865
3866 // -- The second and third operands have pointer type, or one has pointer
3867 // type and the other is a null pointer constant; pointer conversions
3868 // and qualification conversions are performed to bring them to their
3869 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003870 // -- The second and third operands have pointer to member type, or one has
3871 // pointer to member type and the other is a null pointer constant;
3872 // pointer to member conversions and qualification conversions are
3873 // performed to bring them to a common type, whose cv-qualification
3874 // shall match the cv-qualification of either the second or the third
3875 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003876 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003877 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003878 isSFINAEContext()? 0 : &NonStandardCompositeType);
3879 if (!Composite.isNull()) {
3880 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003881 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003882 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3883 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003884 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003886 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003887 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003888
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003889 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003890 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3891 if (!Composite.isNull())
3892 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003893
Chandler Carruth7ef93242011-02-19 00:13:59 +00003894 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003895 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003896 return QualType();
3897
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003898 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003899 << LHS.get()->getType() << RHS.get()->getType()
3900 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003901 return QualType();
3902}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003903
3904/// \brief Find a merged pointer type and convert the two expressions to it.
3905///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003906/// This finds the composite pointer type (or member pointer type) for @p E1
3907/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3908/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003909/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003910///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003911/// \param Loc The location of the operator requiring these two expressions to
3912/// be converted to the composite pointer type.
3913///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003914/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3915/// a non-standard (but still sane) composite type to which both expressions
3916/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3917/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003918QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003919 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003920 bool *NonStandardCompositeType) {
3921 if (NonStandardCompositeType)
3922 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003923
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003924 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3925 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003927 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3928 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003929 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003930
3931 // C++0x 5.9p2
3932 // Pointer conversions and qualification conversions are performed on
3933 // pointer operands to bring them to their composite pointer type. If
3934 // one operand is a null pointer constant, the composite pointer type is
3935 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003936 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003937 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003938 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003939 else
John Wiegley429bb272011-04-08 18:41:53 +00003940 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003941 return T2;
3942 }
Douglas Gregorce940492009-09-25 04:25:58 +00003943 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003944 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003945 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003946 else
John Wiegley429bb272011-04-08 18:41:53 +00003947 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003948 return T1;
3949 }
Mike Stump1eb44332009-09-09 15:08:12 +00003950
Douglas Gregor20b3e992009-08-24 17:42:35 +00003951 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003952 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3953 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003954 return QualType();
3955
3956 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3957 // the other has type "pointer to cv2 T" and the composite pointer type is
3958 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3959 // Otherwise, the composite pointer type is a pointer type similar to the
3960 // type of one of the operands, with a cv-qualification signature that is
3961 // the union of the cv-qualification signatures of the operand types.
3962 // In practice, the first part here is redundant; it's subsumed by the second.
3963 // What we do here is, we build the two possible composite types, and try the
3964 // conversions in both directions. If only one works, or if the two composite
3965 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003966 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003967 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003968 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003969 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003970 ContainingClassVector;
3971 ContainingClassVector MemberOfClass;
3972 QualType Composite1 = Context.getCanonicalType(T1),
3973 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003974 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003975 do {
3976 const PointerType *Ptr1, *Ptr2;
3977 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3978 (Ptr2 = Composite2->getAs<PointerType>())) {
3979 Composite1 = Ptr1->getPointeeType();
3980 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003981
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003982 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003984 if (NonStandardCompositeType &&
3985 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3986 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003987
Douglas Gregor20b3e992009-08-24 17:42:35 +00003988 QualifierUnion.push_back(
3989 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3990 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3991 continue;
3992 }
Mike Stump1eb44332009-09-09 15:08:12 +00003993
Douglas Gregor20b3e992009-08-24 17:42:35 +00003994 const MemberPointerType *MemPtr1, *MemPtr2;
3995 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3996 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3997 Composite1 = MemPtr1->getPointeeType();
3998 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003999
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004000 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004002 if (NonStandardCompositeType &&
4003 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4004 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004005
Douglas Gregor20b3e992009-08-24 17:42:35 +00004006 QualifierUnion.push_back(
4007 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4008 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4009 MemPtr2->getClass()));
4010 continue;
4011 }
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Douglas Gregor20b3e992009-08-24 17:42:35 +00004013 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Douglas Gregor20b3e992009-08-24 17:42:35 +00004015 // Cannot unwrap any more types.
4016 break;
4017 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004019 if (NeedConstBefore && NonStandardCompositeType) {
4020 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004021 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004022 // requirements of C++ [conv.qual]p4 bullet 3.
4023 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4024 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4025 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4026 *NonStandardCompositeType = true;
4027 }
4028 }
4029 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004030
Douglas Gregor20b3e992009-08-24 17:42:35 +00004031 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004032 ContainingClassVector::reverse_iterator MOC
4033 = MemberOfClass.rbegin();
4034 for (QualifierVector::reverse_iterator
4035 I = QualifierUnion.rbegin(),
4036 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004037 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004038 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004039 if (MOC->first && MOC->second) {
4040 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004041 Composite1 = Context.getMemberPointerType(
4042 Context.getQualifiedType(Composite1, Quals),
4043 MOC->first);
4044 Composite2 = Context.getMemberPointerType(
4045 Context.getQualifiedType(Composite2, Quals),
4046 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004047 } else {
4048 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004049 Composite1
4050 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4051 Composite2
4052 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004053 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004054 }
4055
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004056 // Try to convert to the first composite pointer type.
4057 InitializedEntity Entity1
4058 = InitializedEntity::InitializeTemporary(Composite1);
4059 InitializationKind Kind
4060 = InitializationKind::CreateCopy(Loc, SourceLocation());
4061 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4062 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004064 if (E1ToC1 && E2ToC1) {
4065 // Conversion to Composite1 is viable.
4066 if (!Context.hasSameType(Composite1, Composite2)) {
4067 // Composite2 is a different type from Composite1. Check whether
4068 // Composite2 is also viable.
4069 InitializedEntity Entity2
4070 = InitializedEntity::InitializeTemporary(Composite2);
4071 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4072 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4073 if (E1ToC2 && E2ToC2) {
4074 // Both Composite1 and Composite2 are viable and are different;
4075 // this is an ambiguity.
4076 return QualType();
4077 }
4078 }
4079
4080 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004081 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004082 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004083 if (E1Result.isInvalid())
4084 return QualType();
4085 E1 = E1Result.takeAs<Expr>();
4086
4087 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004088 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004089 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004090 if (E2Result.isInvalid())
4091 return QualType();
4092 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004093
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004094 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004095 }
4096
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004097 // Check whether Composite2 is viable.
4098 InitializedEntity Entity2
4099 = InitializedEntity::InitializeTemporary(Composite2);
4100 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4101 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4102 if (!E1ToC2 || !E2ToC2)
4103 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004104
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004105 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004106 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004107 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004108 if (E1Result.isInvalid())
4109 return QualType();
4110 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004111
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004112 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004113 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004114 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004115 if (E2Result.isInvalid())
4116 return QualType();
4117 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004118
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004119 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004120}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004121
John McCall60d7b3a2010-08-24 06:29:42 +00004122ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004123 if (!E)
4124 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004125
John McCallf85e1932011-06-15 23:02:42 +00004126 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4127
4128 // If the result is a glvalue, we shouldn't bind it.
4129 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004130 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004131
John McCallf85e1932011-06-15 23:02:42 +00004132 // In ARC, calls that return a retainable type can return retained,
4133 // in which case we have to insert a consuming cast.
4134 if (getLangOptions().ObjCAutoRefCount &&
4135 E->getType()->isObjCRetainableType()) {
4136
4137 bool ReturnsRetained;
4138
4139 // For actual calls, we compute this by examining the type of the
4140 // called value.
4141 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4142 Expr *Callee = Call->getCallee()->IgnoreParens();
4143 QualType T = Callee->getType();
4144
4145 if (T == Context.BoundMemberTy) {
4146 // Handle pointer-to-members.
4147 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4148 T = BinOp->getRHS()->getType();
4149 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4150 T = Mem->getMemberDecl()->getType();
4151 }
4152
4153 if (const PointerType *Ptr = T->getAs<PointerType>())
4154 T = Ptr->getPointeeType();
4155 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4156 T = Ptr->getPointeeType();
4157 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4158 T = MemPtr->getPointeeType();
4159
4160 const FunctionType *FTy = T->getAs<FunctionType>();
4161 assert(FTy && "call to value not of function type?");
4162 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4163
4164 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4165 // type always produce a +1 object.
4166 } else if (isa<StmtExpr>(E)) {
4167 ReturnsRetained = true;
4168
4169 // For message sends and property references, we try to find an
4170 // actual method. FIXME: we should infer retention by selector in
4171 // cases where we don't have an actual method.
4172 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004173 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004174 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4175 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004176 }
4177
4178 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004179
4180 // Don't do reclaims on performSelector calls; despite their
4181 // return type, the invoked method doesn't necessarily actually
4182 // return an object.
4183 if (!ReturnsRetained &&
4184 D && D->getMethodFamily() == OMF_performSelector)
4185 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004186 }
4187
John McCall567c5862011-11-14 19:53:16 +00004188 // Don't reclaim an object of Class type.
4189 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4190 return Owned(E);
4191
John McCall7e5e5f42011-07-07 06:58:02 +00004192 ExprNeedsCleanups = true;
4193
John McCall33e56f32011-09-10 06:18:15 +00004194 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4195 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004196 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4197 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004198 }
4199
4200 if (!getLangOptions().CPlusPlus)
4201 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004202
Peter Collingbourneb4ab8432012-01-26 03:33:51 +00004203 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4204 // a fast path for the common case that the type is directly a RecordType.
4205 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4206 const RecordType *RT = 0;
4207 while (!RT) {
4208 switch (T->getTypeClass()) {
4209 case Type::Record:
4210 RT = cast<RecordType>(T);
4211 break;
4212 case Type::ConstantArray:
4213 case Type::IncompleteArray:
4214 case Type::VariableArray:
4215 case Type::DependentSizedArray:
4216 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4217 break;
4218 default:
4219 return Owned(E);
4220 }
4221 }
Mike Stump1eb44332009-09-09 15:08:12 +00004222
John McCall86ff3082010-02-04 22:26:26 +00004223 // That should be enough to guarantee that this type is complete.
4224 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004225 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004226 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004227 return Owned(E);
4228
John McCallf85e1932011-06-15 23:02:42 +00004229 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4230
4231 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4232 if (Destructor) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00004233 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004234 CheckDestructorAccess(E->getExprLoc(), Destructor,
4235 PDiag(diag::err_access_dtor_temp)
4236 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004237
John McCall80ee6e82011-11-10 05:35:25 +00004238 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004239 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004240 }
Anders Carlssondef11992009-05-30 20:36:53 +00004241 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4242}
4243
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004244ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004245Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004246 if (SubExpr.isInvalid())
4247 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004248
John McCall4765fa02010-12-06 08:20:24 +00004249 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004250}
4251
John McCall80ee6e82011-11-10 05:35:25 +00004252Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4253 assert(SubExpr && "sub expression can't be null!");
4254
Eli Friedmand2cce132012-02-02 23:15:15 +00004255 CleanupVarDeclMarking();
4256
John McCall80ee6e82011-11-10 05:35:25 +00004257 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4258 assert(ExprCleanupObjects.size() >= FirstCleanup);
4259 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4260 if (!ExprNeedsCleanups)
4261 return SubExpr;
4262
4263 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4264 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4265 ExprCleanupObjects.size() - FirstCleanup);
4266
4267 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4268 DiscardCleanupsInEvaluationContext();
4269
4270 return E;
4271}
4272
John McCall4765fa02010-12-06 08:20:24 +00004273Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004274 assert(SubStmt && "sub statement can't be null!");
4275
Eli Friedmand2cce132012-02-02 23:15:15 +00004276 CleanupVarDeclMarking();
4277
John McCallf85e1932011-06-15 23:02:42 +00004278 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004279 return SubStmt;
4280
4281 // FIXME: In order to attach the temporaries, wrap the statement into
4282 // a StmtExpr; currently this is only used for asm statements.
4283 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4284 // a new AsmStmtWithTemporaries.
4285 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4286 SourceLocation(),
4287 SourceLocation());
4288 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4289 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004290 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004291}
4292
John McCall60d7b3a2010-08-24 06:29:42 +00004293ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004294Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004295 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004296 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004297 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004298 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004299 if (Result.isInvalid()) return ExprError();
4300 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004301
John McCall3c3b7f92011-10-25 17:37:35 +00004302 Result = CheckPlaceholderExpr(Base);
4303 if (Result.isInvalid()) return ExprError();
4304 Base = Result.take();
4305
John McCall9ae2f072010-08-23 23:25:46 +00004306 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004307 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004308 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004309 // If we have a pointer to a dependent type and are using the -> operator,
4310 // the object type is the type that the pointer points to. We might still
4311 // have enough information about that type to do something useful.
4312 if (OpKind == tok::arrow)
4313 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4314 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315
John McCallb3d87482010-08-24 05:47:05 +00004316 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004317 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004318 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004319 }
Mike Stump1eb44332009-09-09 15:08:12 +00004320
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004321 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004322 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004323 // returned, with the original second operand.
4324 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004325 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004326 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004327 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004328 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004329
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004330 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004331 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4332 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004333 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004334 Base = Result.get();
4335 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004336 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004337 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004338 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004339 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004340 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004341 for (unsigned i = 0; i < Locations.size(); i++)
4342 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004343 return ExprError();
4344 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004345 }
Mike Stump1eb44332009-09-09 15:08:12 +00004346
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004347 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004348 BaseType = BaseType->getPointeeType();
4349 }
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004351 // Objective-C properties allow "." access on Objective-C pointer types,
4352 // so adjust the base type to the object type itself.
4353 if (BaseType->isObjCObjectPointerType())
4354 BaseType = BaseType->getPointeeType();
4355
4356 // C++ [basic.lookup.classref]p2:
4357 // [...] If the type of the object expression is of pointer to scalar
4358 // type, the unqualified-id is looked up in the context of the complete
4359 // postfix-expression.
4360 //
4361 // This also indicates that we could be parsing a pseudo-destructor-name.
4362 // Note that Objective-C class and object types can be pseudo-destructor
4363 // expressions or normal member (ivar or property) access expressions.
4364 if (BaseType->isObjCObjectOrInterfaceType()) {
4365 MayBePseudoDestructor = true;
4366 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004367 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004368 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004369 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004370 }
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Douglas Gregor03c57052009-11-17 05:17:33 +00004372 // The object type must be complete (or dependent).
4373 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004374 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004375 PDiag(diag::err_incomplete_member_access)))
4376 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004377
Douglas Gregorc68afe22009-09-03 21:38:09 +00004378 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004379 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004380 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004381 // type C (or of pointer to a class type C), the unqualified-id is looked
4382 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004383 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004384 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004385}
4386
John McCall60d7b3a2010-08-24 06:29:42 +00004387ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004388 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004389 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004390 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4391 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004392 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004393
Douglas Gregor77549082010-02-24 21:29:12 +00004394 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004395 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004396 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004397 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004398 /*RPLoc*/ ExpectedLParenLoc);
4399}
Douglas Gregord4dca082010-02-24 18:44:31 +00004400
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004401static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00004402 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004403 if (Base->hasPlaceholderType()) {
4404 ExprResult result = S.CheckPlaceholderExpr(Base);
4405 if (result.isInvalid()) return true;
4406 Base = result.take();
4407 }
4408 ObjectType = Base->getType();
4409
David Blaikie91ec7892011-12-16 16:03:09 +00004410 // C++ [expr.pseudo]p2:
4411 // The left-hand side of the dot operator shall be of scalar type. The
4412 // left-hand side of the arrow operator shall be of pointer to scalar type.
4413 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004414 // Note that this is rather different from the normal handling for the
4415 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00004416 if (OpKind == tok::arrow) {
4417 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4418 ObjectType = Ptr->getPointeeType();
4419 } else if (!Base->isTypeDependent()) {
4420 // The user wrote "p->" when she probably meant "p."; fix it.
4421 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4422 << ObjectType << true
4423 << FixItHint::CreateReplacement(OpLoc, ".");
4424 if (S.isSFINAEContext())
4425 return true;
4426
4427 OpKind = tok::period;
4428 }
4429 }
4430
4431 return false;
4432}
4433
John McCall60d7b3a2010-08-24 06:29:42 +00004434ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004435 SourceLocation OpLoc,
4436 tok::TokenKind OpKind,
4437 const CXXScopeSpec &SS,
4438 TypeSourceInfo *ScopeTypeInfo,
4439 SourceLocation CCLoc,
4440 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004441 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004442 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004443 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004444
Eli Friedman8c9fe202012-01-25 04:35:06 +00004445 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004446 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4447 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004448
Douglas Gregorb57fb492010-02-24 22:38:50 +00004449 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
Nico Weberdf1be862012-01-23 05:50:57 +00004450 if (getLangOptions().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004451 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004452 else
4453 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4454 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004455 return ExprError();
4456 }
4457
4458 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004459 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004460 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004461 if (DestructedTypeInfo) {
4462 QualType DestructedType = DestructedTypeInfo->getType();
4463 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004464 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004465 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4466 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4467 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4468 << ObjectType << DestructedType << Base->getSourceRange()
4469 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004470
John McCallf85e1932011-06-15 23:02:42 +00004471 // Recover by setting the destructed type to the object type.
4472 DestructedType = ObjectType;
4473 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004474 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004475 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4476 } else if (DestructedType.getObjCLifetime() !=
4477 ObjectType.getObjCLifetime()) {
4478
4479 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4480 // Okay: just pretend that the user provided the correctly-qualified
4481 // type.
4482 } else {
4483 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4484 << ObjectType << DestructedType << Base->getSourceRange()
4485 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4486 }
4487
4488 // Recover by setting the destructed type to the object type.
4489 DestructedType = ObjectType;
4490 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4491 DestructedTypeStart);
4492 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4493 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004494 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004495 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004496
Douglas Gregorb57fb492010-02-24 22:38:50 +00004497 // C++ [expr.pseudo]p2:
4498 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4499 // form
4500 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004501 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004502 //
4503 // shall designate the same scalar type.
4504 if (ScopeTypeInfo) {
4505 QualType ScopeType = ScopeTypeInfo->getType();
4506 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004507 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004509 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004510 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004511 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004512 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004513
Douglas Gregorb57fb492010-02-24 22:38:50 +00004514 ScopeType = QualType();
4515 ScopeTypeInfo = 0;
4516 }
4517 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004518
John McCall9ae2f072010-08-23 23:25:46 +00004519 Expr *Result
4520 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4521 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004522 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004523 ScopeTypeInfo,
4524 CCLoc,
4525 TildeLoc,
4526 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004527
Douglas Gregorb57fb492010-02-24 22:38:50 +00004528 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004529 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004530
John McCall9ae2f072010-08-23 23:25:46 +00004531 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004532}
4533
John McCall60d7b3a2010-08-24 06:29:42 +00004534ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004535 SourceLocation OpLoc,
4536 tok::TokenKind OpKind,
4537 CXXScopeSpec &SS,
4538 UnqualifiedId &FirstTypeName,
4539 SourceLocation CCLoc,
4540 SourceLocation TildeLoc,
4541 UnqualifiedId &SecondTypeName,
4542 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004543 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4544 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4545 "Invalid first type name in pseudo-destructor");
4546 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4547 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4548 "Invalid second type name in pseudo-destructor");
4549
Eli Friedman8c9fe202012-01-25 04:35:06 +00004550 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004551 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4552 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004553
4554 // Compute the object type that we should use for name lookup purposes. Only
4555 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004556 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004557 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004558 if (ObjectType->isRecordType())
4559 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004560 else if (ObjectType->isDependentType())
4561 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004562 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004563
4564 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004565 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004566 QualType DestructedType;
4567 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004568 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004569 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004570 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004571 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004572 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004573 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004574 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4575 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004576 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004577 // couldn't find anything useful in scope. Just store the identifier and
4578 // it's location, and we'll perform (qualified) name lookup again at
4579 // template instantiation time.
4580 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4581 SecondTypeName.StartLocation);
4582 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004583 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004584 diag::err_pseudo_dtor_destructor_non_type)
4585 << SecondTypeName.Identifier << ObjectType;
4586 if (isSFINAEContext())
4587 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004588
Douglas Gregor77549082010-02-24 21:29:12 +00004589 // Recover by assuming we had the right type all along.
4590 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004591 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004592 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004593 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004594 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004595 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004596 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4597 TemplateId->getTemplateArgs(),
4598 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004599 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4600 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004601 TemplateId->TemplateNameLoc,
4602 TemplateId->LAngleLoc,
4603 TemplateArgsPtr,
4604 TemplateId->RAngleLoc);
4605 if (T.isInvalid() || !T.get()) {
4606 // Recover by assuming we had the right type all along.
4607 DestructedType = ObjectType;
4608 } else
4609 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004610 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004611
4612 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004613 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004614 if (!DestructedType.isNull()) {
4615 if (!DestructedTypeInfo)
4616 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004617 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004618 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4619 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004620
Douglas Gregorb57fb492010-02-24 22:38:50 +00004621 // Convert the name of the scope type (the type prior to '::') into a type.
4622 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004623 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004624 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004625 FirstTypeName.Identifier) {
4626 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004627 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004628 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004629 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004630 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004631 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004632 diag::err_pseudo_dtor_destructor_non_type)
4633 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634
Douglas Gregorb57fb492010-02-24 22:38:50 +00004635 if (isSFINAEContext())
4636 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004637
Douglas Gregorb57fb492010-02-24 22:38:50 +00004638 // Just drop this type. It's unnecessary anyway.
4639 ScopeType = QualType();
4640 } else
4641 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004642 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004643 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004644 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004645 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4646 TemplateId->getTemplateArgs(),
4647 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004648 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4649 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004650 TemplateId->TemplateNameLoc,
4651 TemplateId->LAngleLoc,
4652 TemplateArgsPtr,
4653 TemplateId->RAngleLoc);
4654 if (T.isInvalid() || !T.get()) {
4655 // Recover by dropping this type.
4656 ScopeType = QualType();
4657 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004659 }
4660 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004661
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004662 if (!ScopeType.isNull() && !ScopeTypeInfo)
4663 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4664 FirstTypeName.StartLocation);
4665
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004666
John McCall9ae2f072010-08-23 23:25:46 +00004667 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004668 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004669 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004670}
4671
David Blaikie91ec7892011-12-16 16:03:09 +00004672ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4673 SourceLocation OpLoc,
4674 tok::TokenKind OpKind,
4675 SourceLocation TildeLoc,
4676 const DeclSpec& DS,
4677 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00004678 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004679 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4680 return ExprError();
4681
4682 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4683
4684 TypeLocBuilder TLB;
4685 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4686 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4687 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4688 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4689
4690 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4691 0, SourceLocation(), TildeLoc,
4692 Destructed, HasTrailingLParen);
4693}
4694
John Wiegley429bb272011-04-08 18:41:53 +00004695ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004696 CXXMethodDecl *Method,
4697 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004698 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4699 FoundDecl, Method);
4700 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004701 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004702
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004703 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004704 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004705 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004706 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004707 if (HadMultipleCandidates)
4708 ME->setHadMultipleCandidates(true);
4709
John McCallf89e55a2010-11-18 06:31:45 +00004710 QualType ResultType = Method->getResultType();
4711 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4712 ResultType = ResultType.getNonLValueExprType(Context);
4713
Eli Friedman5f2987c2012-02-02 03:46:19 +00004714 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004715 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004716 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004717 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004718 return CE;
4719}
4720
Sebastian Redl2e156222010-09-10 20:55:43 +00004721ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4722 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004723 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4724 Operand->CanThrow(Context),
4725 KeyLoc, RParen));
4726}
4727
4728ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4729 Expr *Operand, SourceLocation RParen) {
4730 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004731}
4732
John McCallf6a16482010-12-04 03:47:34 +00004733/// Perform the conversions required for an expression used in a
4734/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004735ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004736 if (E->hasPlaceholderType()) {
4737 ExprResult result = CheckPlaceholderExpr(E);
4738 if (result.isInvalid()) return Owned(E);
4739 E = result.take();
4740 }
4741
John McCalla878cda2010-12-02 02:07:15 +00004742 // C99 6.3.2.1:
4743 // [Except in specific positions,] an lvalue that does not have
4744 // array type is converted to the value stored in the
4745 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004746 if (E->isRValue()) {
4747 // In C, function designators (i.e. expressions of function type)
4748 // are r-values, but we still want to do function-to-pointer decay
4749 // on them. This is both technically correct and convenient for
4750 // some clients.
4751 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4752 return DefaultFunctionArrayConversion(E);
4753
4754 return Owned(E);
4755 }
John McCalla878cda2010-12-02 02:07:15 +00004756
John McCallf6a16482010-12-04 03:47:34 +00004757 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004758 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004759
4760 // GCC seems to also exclude expressions of incomplete enum type.
4761 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4762 if (!T->getDecl()->isComplete()) {
4763 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004764 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4765 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004766 }
4767 }
4768
John Wiegley429bb272011-04-08 18:41:53 +00004769 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4770 if (Res.isInvalid())
4771 return Owned(E);
4772 E = Res.take();
4773
John McCall85515d62010-12-04 12:29:11 +00004774 if (!E->getType()->isVoidType())
4775 RequireCompleteType(E->getExprLoc(), E->getType(),
4776 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004777 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004778}
4779
John Wiegley429bb272011-04-08 18:41:53 +00004780ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4781 ExprResult FullExpr = Owned(FE);
4782
4783 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004784 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004785
John Wiegley429bb272011-04-08 18:41:53 +00004786 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004787 return ExprError();
4788
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004789 // Top-level message sends default to 'id' when we're in a debugger.
Sean Callanan50a9a122012-02-04 01:29:37 +00004790 if (getLangOptions().DebuggerCastResultToId &&
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004791 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4792 isa<ObjCMessageExpr>(FullExpr.get())) {
4793 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4794 if (FullExpr.isInvalid())
4795 return ExprError();
4796 }
4797
John McCallfb8721c2011-04-10 19:13:55 +00004798 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4799 if (FullExpr.isInvalid())
4800 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004801
John Wiegley429bb272011-04-08 18:41:53 +00004802 FullExpr = IgnoredValueConversions(FullExpr.take());
4803 if (FullExpr.isInvalid())
4804 return ExprError();
4805
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004806 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004807 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004808}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004809
4810StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4811 if (!FullStmt) return StmtError();
4812
John McCall4765fa02010-12-06 08:20:24 +00004813 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004814}
Francois Pichet1e862692011-05-06 20:48:22 +00004815
Douglas Gregorba0513d2011-10-25 01:33:02 +00004816Sema::IfExistsResult
4817Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4818 CXXScopeSpec &SS,
4819 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004820 DeclarationName TargetName = TargetNameInfo.getName();
4821 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004822 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004823
Douglas Gregor3896fc52011-10-24 22:31:10 +00004824 // If the name itself is dependent, then the result is dependent.
4825 if (TargetName.isDependentName())
4826 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004827
Francois Pichet1e862692011-05-06 20:48:22 +00004828 // Do the redeclaration lookup in the current scope.
4829 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4830 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004831 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004832 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004833
4834 switch (R.getResultKind()) {
4835 case LookupResult::Found:
4836 case LookupResult::FoundOverloaded:
4837 case LookupResult::FoundUnresolvedValue:
4838 case LookupResult::Ambiguous:
4839 return IER_Exists;
4840
4841 case LookupResult::NotFound:
4842 return IER_DoesNotExist;
4843
4844 case LookupResult::NotFoundInCurrentInstantiation:
4845 return IER_Dependent;
4846 }
David Blaikie7530c032012-01-17 06:56:22 +00004847
4848 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00004849}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004850
Douglas Gregor65019ac2011-10-25 03:44:56 +00004851Sema::IfExistsResult
4852Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4853 bool IsIfExists, CXXScopeSpec &SS,
4854 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004855 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004856
4857 // Check for unexpanded parameter packs.
4858 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4859 collectUnexpandedParameterPacks(SS, Unexpanded);
4860 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4861 if (!Unexpanded.empty()) {
4862 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4863 IsIfExists? UPPC_IfExists
4864 : UPPC_IfNotExists,
4865 Unexpanded);
4866 return IER_Error;
4867 }
4868
Douglas Gregorba0513d2011-10-25 01:33:02 +00004869 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4870}
4871
Eli Friedmandc3b7232012-01-04 02:40:39 +00004872//===----------------------------------------------------------------------===//
4873// Lambdas.
4874//===----------------------------------------------------------------------===//
4875
Eli Friedmanec9ea722012-01-05 03:35:19 +00004876void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4877 Declarator &ParamInfo,
4878 Scope *CurScope) {
4879 DeclContext *DC = CurContext;
Eli Friedman906a7e12012-01-06 03:05:34 +00004880 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
Eli Friedmanec9ea722012-01-05 03:35:19 +00004881 DC = DC->getParent();
Eli Friedmandc3b7232012-01-04 02:40:39 +00004882
Eli Friedmanec9ea722012-01-05 03:35:19 +00004883 // Start constructing the lambda class.
4884 CXXRecordDecl *Class = CXXRecordDecl::Create(Context, TTK_Class, DC,
4885 Intro.Range.getBegin(),
4886 /*IdLoc=*/SourceLocation(),
4887 /*Id=*/0);
4888 Class->startDefinition();
Eli Friedman72899c32012-01-07 04:59:52 +00004889 Class->setLambda(true);
Eli Friedmanec9ea722012-01-05 03:35:19 +00004890 CurContext->addDecl(Class);
Eli Friedmandc3b7232012-01-04 02:40:39 +00004891
Douglas Gregora1f21142012-02-01 17:04:21 +00004892 // Build the call operator; we don't really have all the relevant information
4893 // at this point, but we need something to attach child declarations to.
4894 QualType MethodTy;
4895 TypeSourceInfo *MethodTyInfo;
4896 if (ParamInfo.getNumTypeObjects() == 0) {
4897 // C++11 [expr.prim.lambda]p4:
4898 // If a lambda-expression does not include a lambda-declarator, it is as
4899 // if the lambda-declarator were ().
4900 FunctionProtoType::ExtProtoInfo EPI;
4901 EPI.TypeQuals |= DeclSpec::TQ_const;
4902 MethodTy = Context.getFunctionType(Context.DependentTy,
4903 /*Args=*/0, /*NumArgs=*/0, EPI);
4904 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
4905 } else {
4906 assert(ParamInfo.isFunctionDeclarator() &&
4907 "lambda-declarator is a function");
4908 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
4909
4910 // C++11 [expr.prim.lambda]p5:
4911 // This function call operator is declared const (9.3.1) if and only if
4912 // the lambda-expression’s parameter-declaration-clause is not followed
Douglas Gregorb710dfe2012-02-01 17:18:19 +00004913 // by mutable. It is neither virtual nor declared volatile. [...]
Douglas Gregora1f21142012-02-01 17:04:21 +00004914 if (!FTI.hasMutableQualifier())
4915 FTI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregorb710dfe2012-02-01 17:18:19 +00004916
4917 // C++11 [expr.prim.lambda]p5:
4918 // [...] Default arguments (8.3.6) shall not be specified in the
4919 // parameter-declaration-clause of a lambda-declarator.
4920 CheckExtraCXXDefaultArguments(ParamInfo);
4921
Douglas Gregora1f21142012-02-01 17:04:21 +00004922 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
4923 // FIXME: Can these asserts actually fail?
4924 assert(MethodTyInfo && "no type from lambda-declarator");
4925 MethodTy = MethodTyInfo->getType();
4926 assert(!MethodTy.isNull() && "no type from lambda declarator");
4927 }
4928
4929 // C++11 [expr.prim.lambda]p5:
4930 // The closure type for a lambda-expression has a public inline function
4931 // call operator (13.5.4) whose parameters and return type are described by
4932 // the lambda-expression’s parameter-declaration-clause and
4933 // trailing-return-type respectively.
4934 DeclarationName MethodName
4935 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4936 CXXMethodDecl *Method
4937 = CXXMethodDecl::Create(Context,
4938 Class,
4939 ParamInfo.getSourceRange().getEnd(),
4940 DeclarationNameInfo(MethodName,
4941 /*NameLoc=*/SourceLocation()),
4942 MethodTy,
4943 MethodTyInfo,
4944 /*isStatic=*/false,
4945 SC_None,
4946 /*isInline=*/true,
4947 /*isConstExpr=*/false,
4948 ParamInfo.getSourceRange().getEnd());
4949 Method->setAccess(AS_public);
4950 Class->addDecl(Method);
4951 Method->setLexicalDeclContext(DC); // FIXME: Minor hack.
4952
4953 ProcessDeclAttributes(CurScope, Method, ParamInfo);
4954
4955 // Enter a new evaluation context to insulate the block from any
4956 // cleanups from the enclosing full-expression.
4957 PushExpressionEvaluationContext(PotentiallyEvaluated);
4958
4959 PushDeclContext(CurScope, Method);
4960
4961 // Introduce the lambda scope.
4962 PushLambdaScope(Class);
4963 LambdaScopeInfo *LSI = getCurLambda();
4964 if (Intro.Default == LCD_ByCopy)
4965 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
4966 else if (Intro.Default == LCD_ByRef)
4967 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
4968
Eli Friedmand67d0cc2012-02-03 01:39:09 +00004969 LSI->Mutable = (Method->getTypeQualifiers() & Qualifiers::Const) == 0;
4970
Douglas Gregora1f21142012-02-01 17:04:21 +00004971 // Handle explicit captures.
Eli Friedmane81d7e92012-01-07 01:08:17 +00004972 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
Douglas Gregora1f21142012-02-01 17:04:21 +00004973 C = Intro.Captures.begin(),
4974 E = Intro.Captures.end();
4975 C != E; ++C) {
Eli Friedmane81d7e92012-01-07 01:08:17 +00004976 if (C->Kind == LCK_This) {
Douglas Gregor93962e52012-02-01 01:18:43 +00004977 // C++11 [expr.prim.lambda]p8:
4978 // An identifier or this shall not appear more than once in a
4979 // lambda-capture.
Douglas Gregora1f21142012-02-01 17:04:21 +00004980 if (LSI->isCXXThisCaptured()) {
Douglas Gregor93962e52012-02-01 01:18:43 +00004981 Diag(C->Loc, diag::err_capture_more_than_once)
4982 << "'this'"
Douglas Gregora1f21142012-02-01 17:04:21 +00004983 << SourceRange(LSI->getCXXThisCapture().getLocation());
Eli Friedmane81d7e92012-01-07 01:08:17 +00004984 continue;
4985 }
4986
Douglas Gregor93962e52012-02-01 01:18:43 +00004987 // C++11 [expr.prim.lambda]p8:
4988 // If a lambda-capture includes a capture-default that is =, the
4989 // lambda-capture shall not contain this [...].
Eli Friedmane81d7e92012-01-07 01:08:17 +00004990 if (Intro.Default == LCD_ByCopy) {
4991 Diag(C->Loc, diag::err_this_capture_with_copy_default);
4992 continue;
4993 }
4994
Douglas Gregor93962e52012-02-01 01:18:43 +00004995 // C++11 [expr.prim.lambda]p12:
4996 // If this is captured by a local lambda expression, its nearest
4997 // enclosing function shall be a non-static member function.
Douglas Gregora1f21142012-02-01 17:04:21 +00004998 QualType ThisCaptureType = getCurrentThisType();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004999 if (ThisCaptureType.isNull()) {
Douglas Gregora1f21142012-02-01 17:04:21 +00005000 Diag(C->Loc, diag::err_this_capture) << true;
Eli Friedmane81d7e92012-01-07 01:08:17 +00005001 continue;
5002 }
Douglas Gregora1f21142012-02-01 17:04:21 +00005003
5004 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
Eli Friedmane81d7e92012-01-07 01:08:17 +00005005 continue;
5006 }
5007
5008 assert(C->Id && "missing identifier for capture");
5009
Douglas Gregor93962e52012-02-01 01:18:43 +00005010 // C++11 [expr.prim.lambda]p8:
5011 // If a lambda-capture includes a capture-default that is &, the
5012 // identifiers in the lambda-capture shall not be preceded by &.
5013 // If a lambda-capture includes a capture-default that is =, [...]
5014 // each identifier it contains shall be preceded by &.
Eli Friedmane81d7e92012-01-07 01:08:17 +00005015 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
5016 Diag(C->Loc, diag::err_reference_capture_with_reference_default);
5017 continue;
5018 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
5019 Diag(C->Loc, diag::err_copy_capture_with_copy_default);
5020 continue;
5021 }
5022
Eli Friedmane81d7e92012-01-07 01:08:17 +00005023 DeclarationNameInfo Name(C->Id, C->Loc);
5024 LookupResult R(*this, Name, LookupOrdinaryName);
Douglas Gregor93962e52012-02-01 01:18:43 +00005025 LookupName(R, CurScope);
Eli Friedmane81d7e92012-01-07 01:08:17 +00005026 if (R.isAmbiguous())
5027 continue;
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00005028 if (R.empty()) {
Douglas Gregor93962e52012-02-01 01:18:43 +00005029 // FIXME: Disable corrections that would add qualification?
5030 CXXScopeSpec ScopeSpec;
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00005031 DeclFilterCCC<VarDecl> Validator;
5032 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
Eli Friedmane81d7e92012-01-07 01:08:17 +00005033 continue;
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00005034 }
Eli Friedmane81d7e92012-01-07 01:08:17 +00005035
Douglas Gregor93962e52012-02-01 01:18:43 +00005036 // C++11 [expr.prim.lambda]p10:
5037 // The identifiers in a capture-list are looked up using the usual rules
5038 // for unqualified name lookup (3.4.1); each such lookup shall find a
5039 // variable with automatic storage duration declared in the reaching
5040 // scope of the local lambda expression.
Douglas Gregora1f21142012-02-01 17:04:21 +00005041 // FIXME: Check reaching scope.
Eli Friedmane81d7e92012-01-07 01:08:17 +00005042 VarDecl *Var = R.getAsSingle<VarDecl>();
5043 if (!Var) {
5044 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
5045 continue;
5046 }
5047
5048 if (!Var->hasLocalStorage()) {
5049 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
Douglas Gregor93962e52012-02-01 01:18:43 +00005050 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
Eli Friedmane81d7e92012-01-07 01:08:17 +00005051 continue;
5052 }
Douglas Gregor93962e52012-02-01 01:18:43 +00005053
5054 // C++11 [expr.prim.lambda]p8:
5055 // An identifier or this shall not appear more than once in a
5056 // lambda-capture.
Douglas Gregora1f21142012-02-01 17:04:21 +00005057 if (LSI->isCaptured(Var)) {
Douglas Gregor93962e52012-02-01 01:18:43 +00005058 Diag(C->Loc, diag::err_capture_more_than_once)
5059 << C->Id
Douglas Gregora1f21142012-02-01 17:04:21 +00005060 << SourceRange(LSI->getCapture(Var).getLocation());
Douglas Gregor93962e52012-02-01 01:18:43 +00005061 continue;
5062 }
Eli Friedmancefc7b22012-02-03 23:06:43 +00005063
5064 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
5065 TryCapture_ExplicitByVal;
5066 TryCaptureVar(Var, C->Loc, Kind);
Eli Friedmane81d7e92012-01-07 01:08:17 +00005067 }
Douglas Gregora1f21142012-02-01 17:04:21 +00005068 LSI->finishedExplicitCaptures();
Eli Friedman906a7e12012-01-06 03:05:34 +00005069
Eli Friedman906a7e12012-01-06 03:05:34 +00005070 // Set the parameters on the decl, if specified.
5071 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
5072 FunctionProtoTypeLoc Proto =
Douglas Gregora1f21142012-02-01 17:04:21 +00005073 cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
Eli Friedman906a7e12012-01-06 03:05:34 +00005074 Method->setParams(Proto.getParams());
5075 CheckParmsForFunctionDef(Method->param_begin(),
5076 Method->param_end(),
5077 /*CheckParameterNames=*/false);
Douglas Gregora1f21142012-02-01 17:04:21 +00005078
Eli Friedman906a7e12012-01-06 03:05:34 +00005079 // Introduce our parameters into the function scope
5080 for (unsigned p = 0, NumParams = Method->getNumParams(); p < NumParams; ++p) {
5081 ParmVarDecl *Param = Method->getParamDecl(p);
5082 Param->setOwningFunction(Method);
Douglas Gregora1f21142012-02-01 17:04:21 +00005083
Eli Friedman906a7e12012-01-06 03:05:34 +00005084 // If this has an identifier, add it to the scope stack.
5085 if (Param->getIdentifier()) {
5086 CheckShadow(CurScope, Param);
Douglas Gregora1f21142012-02-01 17:04:21 +00005087
Eli Friedman906a7e12012-01-06 03:05:34 +00005088 PushOnScopeChains(Param, CurScope);
5089 }
5090 }
5091 }
5092
5093 const FunctionType *Fn = MethodTy->getAs<FunctionType>();
5094 QualType RetTy = Fn->getResultType();
5095 if (RetTy != Context.DependentTy) {
5096 LSI->ReturnType = RetTy;
Eli Friedmanb69b42c2012-01-11 02:36:31 +00005097 } else {
Eli Friedman906a7e12012-01-06 03:05:34 +00005098 LSI->HasImplicitReturnType = true;
5099 }
5100
5101 // FIXME: Check return type is complete, !isObjCObjectType
5102
Eli Friedmandc3b7232012-01-04 02:40:39 +00005103}
5104
5105void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope) {
5106 // Leave the expression-evaluation context.
5107 DiscardCleanupsInEvaluationContext();
5108 PopExpressionEvaluationContext();
5109
5110 // Leave the context of the lambda.
Eli Friedmanec9ea722012-01-05 03:35:19 +00005111 PopDeclContext();
5112 PopFunctionScopeInfo();
Eli Friedmandc3b7232012-01-04 02:40:39 +00005113}
5114
5115ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc,
5116 Stmt *Body, Scope *CurScope) {
5117 // FIXME: Implement
5118 Diag(StartLoc, diag::err_lambda_unsupported);
5119 ActOnLambdaError(StartLoc, CurScope);
5120 return ExprError();
5121}