blob: 61f18795ba74c380afc198a2ebffdbf31bf60bab [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"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000032using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000033
John McCallb3d87482010-08-24 05:47:05 +000034ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000035 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000036 SourceLocation NameLoc,
37 Scope *S, CXXScopeSpec &SS,
38 ParsedType ObjectTypePtr,
39 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000040 // Determine where to perform name lookup.
41
42 // FIXME: This area of the standard is very messy, and the current
43 // wording is rather unclear about which scopes we search for the
44 // destructor name; see core issues 399 and 555. Issue 399 in
45 // particular shows where the current description of destructor name
46 // lookup is completely out of line with existing practice, e.g.,
47 // this appears to be ill-formed:
48 //
49 // namespace N {
50 // template <typename T> struct S {
51 // ~S();
52 // };
53 // }
54 //
55 // void f(N::S<int>* s) {
56 // s->N::S<int>::~S();
57 // }
58 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000059 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000060 // For this reason, we're currently only doing the C++03 version of this
61 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000062 QualType SearchType;
63 DeclContext *LookupCtx = 0;
64 bool isDependent = false;
65 bool LookInScope = false;
66
67 // If we have an object type, it's because we are in a
68 // pseudo-destructor-expression or a member access expression, and
69 // we know what type we're looking for.
70 if (ObjectTypePtr)
71 SearchType = GetTypeFromParser(ObjectTypePtr);
72
73 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000074 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000075
Douglas Gregor93649fd2010-02-23 00:15:22 +000076 bool AlreadySearched = false;
77 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000078 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000080 // the type-names are looked up as types in the scope designated by the
81 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000082 //
83 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 //
85 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000086 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000087 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000088 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000089 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000090 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000091 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000093 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // nested-name-specifier.
96 DeclContext *DC = computeDeclContext(SS, EnteringContext);
97 if (DC && DC->isFileContext()) {
98 AlreadySearched = true;
99 LookupCtx = DC;
100 isDependent = false;
101 } else if (DC && isa<CXXRecordDecl>(DC))
102 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000103
Sebastian Redlc0fee502010-07-07 23:17:38 +0000104 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000105 NestedNameSpecifier *Prefix = 0;
106 if (AlreadySearched) {
107 // Nothing left to do.
108 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000110 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000111 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000113 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000114 LookupCtx = computeDeclContext(SearchType);
115 isDependent = SearchType->isDependentType();
116 } else {
117 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000118 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000120
Douglas Gregoredc90502010-02-25 04:46:04 +0000121 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000122 } else if (ObjectTypePtr) {
123 // C++ [basic.lookup.classref]p3:
124 // If the unqualified-id is ~type-name, the type-name is looked up
125 // in the context of the entire postfix-expression. If the type T
126 // of the object expression is of a class type C, the type-name is
127 // also looked up in the scope of class C. At least one of the
128 // lookups shall find a name that refers to (possibly
129 // cv-qualified) T.
130 LookupCtx = computeDeclContext(SearchType);
131 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000132 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000133 "Caller should have completed object type");
134
135 LookInScope = true;
136 } else {
137 // Perform lookup into the current scope (only).
138 LookInScope = true;
139 }
140
141 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
142 for (unsigned Step = 0; Step != 2; ++Step) {
143 // Look for the name first in the computed lookup context (if we
144 // have one) and, if that fails to find a match, in the sope (if
145 // we're allowed to look there).
146 Found.clear();
147 if (Step == 0 && LookupCtx)
148 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000149 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000150 LookupName(Found, S);
151 else
152 continue;
153
154 // FIXME: Should we be suppressing ambiguities here?
155 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000156 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000157
158 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
159 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000160
161 if (SearchType.isNull() || SearchType->isDependentType() ||
162 Context.hasSameUnqualifiedType(T, SearchType)) {
163 // We found our type!
164
John McCallb3d87482010-08-24 05:47:05 +0000165 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000166 }
167 }
168
169 // If the name that we found is a class template name, and it is
170 // the same name as the template name in the last part of the
171 // nested-name-specifier (if present) or the object type, then
172 // this is the destructor for that class.
173 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000174 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000175 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
176 QualType MemberOfType;
177 if (SS.isSet()) {
178 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
179 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000180 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
181 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000182 }
183 }
184 if (MemberOfType.isNull())
185 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000186
Douglas Gregor124b8782010-02-16 19:09:40 +0000187 if (MemberOfType.isNull())
188 continue;
189
190 // We're referring into a class template specialization. If the
191 // class template we found is the same as the template being
192 // specialized, we found what we are looking for.
193 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
194 if (ClassTemplateSpecializationDecl *Spec
195 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
196 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
197 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000198 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000199 }
200
201 continue;
202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000203
Douglas Gregor124b8782010-02-16 19:09:40 +0000204 // We're referring to an unresolved class template
205 // specialization. Determine whether we class template we found
206 // is the same as the template being specialized or, if we don't
207 // know which template is being specialized, that it at least
208 // has the same name.
209 if (const TemplateSpecializationType *SpecType
210 = MemberOfType->getAs<TemplateSpecializationType>()) {
211 TemplateName SpecName = SpecType->getTemplateName();
212
213 // The class template we found is the same template being
214 // specialized.
215 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
216 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000217 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000218
219 continue;
220 }
221
222 // The class template we found has the same name as the
223 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000224 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000225 = SpecName.getAsDependentTemplateName()) {
226 if (DepTemplate->isIdentifier() &&
227 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000228 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000229
230 continue;
231 }
232 }
233 }
234 }
235
236 if (isDependent) {
237 // We didn't find our type, but that's okay: it's dependent
238 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000239
240 // FIXME: What if we have no nested-name-specifier?
241 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
242 SS.getWithLocInContext(Context),
243 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000244 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000245 }
246
247 if (ObjectTypePtr)
248 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000249 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000250 else
251 Diag(NameLoc, diag::err_destructor_class_name);
252
John McCallb3d87482010-08-24 05:47:05 +0000253 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000254}
255
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000256/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000257ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000258 SourceLocation TypeidLoc,
259 TypeSourceInfo *Operand,
260 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000261 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000262 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000263 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000264 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000265 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000266 Qualifiers Quals;
267 QualType T
268 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
269 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000270 if (T->getAs<RecordType>() &&
271 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
272 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000273
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000274 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
275 Operand,
276 SourceRange(TypeidLoc, RParenLoc)));
277}
278
279/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000280ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000281 SourceLocation TypeidLoc,
282 Expr *E,
283 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000284 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000285 if (E && !E->isTypeDependent()) {
286 QualType T = E->getType();
287 if (const RecordType *RecordT = T->getAs<RecordType>()) {
288 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
289 // C++ [expr.typeid]p3:
290 // [...] If the type of the expression is a class type, the class
291 // shall be completely-defined.
292 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
293 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000295 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000296 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000297 // polymorphic class type [...] [the] expression is an unevaluated
298 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000299 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000300 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000301
302 // We require a vtable to query the type at run time.
303 MarkVTableUsed(TypeidLoc, RecordD);
304 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000306
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 // C++ [expr.typeid]p4:
308 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000309 // cv-qualified type, the result of the typeid expression refers to a
310 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000311 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000312 Qualifiers Quals;
313 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
314 if (!Context.hasSameType(T, UnqualT)) {
315 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000316 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000317 }
318 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000319
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000320 // If this is an unevaluated operand, clear out the set of
321 // declaration references we have been computing and eliminate any
322 // temporaries introduced in its computation.
323 if (isUnevaluatedOperand)
324 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000325
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000326 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000327 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000329}
330
331/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000332ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000333Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
334 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000335 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000336 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000337 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000338
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000339 if (!CXXTypeInfoDecl) {
340 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
341 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
342 LookupQualifiedName(R, getStdNamespace());
343 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
344 if (!CXXTypeInfoDecl)
345 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
346 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000347
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000348 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000349
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000350 if (isType) {
351 // The operand is a type; handle it as such.
352 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000353 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
354 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000355 if (T.isNull())
356 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000358 if (!TInfo)
359 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000360
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000361 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000364 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000365 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000366}
367
Francois Pichet6915c522010-12-27 01:32:00 +0000368/// Retrieve the UuidAttr associated with QT.
369static UuidAttr *GetUuidAttrOfType(QualType QT) {
370 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000371 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000372 if (QT->isPointerType() || QT->isReferenceType())
373 Ty = QT->getPointeeType().getTypePtr();
374 else if (QT->isArrayType())
375 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
376
Francois Pichet6915c522010-12-27 01:32:00 +0000377 // Loop all class definition and declaration looking for an uuid attribute.
378 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
379 while (RD) {
380 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
381 return Uuid;
382 RD = RD->getPreviousDeclaration();
383 }
384 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000385}
386
Francois Pichet01b7c302010-09-08 12:20:18 +0000387/// \brief Build a Microsoft __uuidof expression with a type operand.
388ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
389 SourceLocation TypeidLoc,
390 TypeSourceInfo *Operand,
391 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000392 if (!Operand->getType()->isDependentType()) {
393 if (!GetUuidAttrOfType(Operand->getType()))
394 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
395 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000396
Francois Pichet01b7c302010-09-08 12:20:18 +0000397 // FIXME: add __uuidof semantic analysis for type operand.
398 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
399 Operand,
400 SourceRange(TypeidLoc, RParenLoc)));
401}
402
403/// \brief Build a Microsoft __uuidof expression with an expression operand.
404ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
405 SourceLocation TypeidLoc,
406 Expr *E,
407 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000408 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000409 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000410 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
411 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
412 }
413 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000414 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
415 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000416 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000417}
418
419/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
420ExprResult
421Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
422 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000424 if (!MSVCGuidDecl) {
425 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
426 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
427 LookupQualifiedName(R, Context.getTranslationUnitDecl());
428 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
429 if (!MSVCGuidDecl)
430 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431 }
432
Francois Pichet01b7c302010-09-08 12:20:18 +0000433 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000434
Francois Pichet01b7c302010-09-08 12:20:18 +0000435 if (isType) {
436 // The operand is a type; handle it as such.
437 TypeSourceInfo *TInfo = 0;
438 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
439 &TInfo);
440 if (T.isNull())
441 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000442
Francois Pichet01b7c302010-09-08 12:20:18 +0000443 if (!TInfo)
444 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
445
446 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
447 }
448
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000449 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000450 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
451}
452
Steve Naroff1b273c42007-09-16 14:56:35 +0000453/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000454ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000455Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000456 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000458 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
459 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000460}
Chris Lattner50dd2892008-02-26 00:51:44 +0000461
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000462/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000463ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000464Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
465 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
466}
467
Chris Lattner50dd2892008-02-26 00:51:44 +0000468/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000469ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000470Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000471 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000472 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000473 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000474 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000475
Sebastian Redl972041f2009-04-27 20:27:31 +0000476 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
477 return ExprError();
478 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
479}
480
481/// CheckCXXThrowOperand - Validate the operand of a throw.
482bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
483 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000484 // A throw-expression initializes a temporary object, called the exception
485 // object, the type of which is determined by removing any top-level
486 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000487 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000488 // or "pointer to function returning T", [...]
489 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000490 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000491 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000492
Sebastian Redl972041f2009-04-27 20:27:31 +0000493 DefaultFunctionArrayConversion(E);
494
495 // If the type of the exception would be an incomplete type or a pointer
496 // to an incomplete type other than (cv) void the program is ill-formed.
497 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000498 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000499 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000500 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000501 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000502 }
503 if (!isPointer || !Ty->isVoidType()) {
504 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000505 PDiag(isPointer ? diag::err_throw_incomplete_ptr
506 : diag::err_throw_incomplete)
507 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000508 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000509
Douglas Gregorbf422f92010-04-15 18:05:39 +0000510 if (RequireNonAbstractType(ThrowLoc, E->getType(),
511 PDiag(diag::err_throw_abstract_type)
512 << E->getSourceRange()))
513 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000514 }
515
John McCallac418162010-04-22 01:10:34 +0000516 // Initialize the exception result. This implicitly weeds out
517 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000518 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
519
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000520 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000521 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000522 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
523 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000525 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000526 if (Res.isInvalid())
527 return true;
528 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000529
Eli Friedman5ed9b932010-06-03 20:39:03 +0000530 // If the exception has class type, we need additional handling.
531 const RecordType *RecordTy = Ty->getAs<RecordType>();
532 if (!RecordTy)
533 return false;
534 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
535
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000536 // If we are throwing a polymorphic class type or pointer thereof,
537 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000538 MarkVTableUsed(ThrowLoc, RD);
539
Eli Friedman98efb9f2010-10-12 20:32:36 +0000540 // If a pointer is thrown, the referenced object will not be destroyed.
541 if (isPointer)
542 return false;
543
Eli Friedman5ed9b932010-06-03 20:39:03 +0000544 // If the class has a non-trivial destructor, we must be able to call it.
545 if (RD->hasTrivialDestructor())
546 return false;
547
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000548 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000549 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000550 if (!Destructor)
551 return false;
552
553 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
554 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000555 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000556 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000557}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000558
John McCall5808ce42011-02-03 08:15:49 +0000559CXXMethodDecl *Sema::tryCaptureCXXThis() {
560 // Ignore block scopes: we can capture through them.
561 // Ignore nested enum scopes: we'll diagnose non-constant expressions
562 // where they're invalid, and other uses are legitimate.
563 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000564 DeclContext *DC = CurContext;
John McCall5808ce42011-02-03 08:15:49 +0000565 while (true) {
566 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
567 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
568 else break;
569 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000570
John McCall5808ce42011-02-03 08:15:49 +0000571 // If we're not in an instance method, error out.
John McCall469a1eb2011-02-02 13:00:07 +0000572 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
573 if (!method || !method->isInstance())
John McCall5808ce42011-02-03 08:15:49 +0000574 return 0;
John McCall469a1eb2011-02-02 13:00:07 +0000575
576 // Mark that we're closing on 'this' in all the block scopes, if applicable.
577 for (unsigned idx = FunctionScopes.size() - 1;
578 isa<BlockScopeInfo>(FunctionScopes[idx]);
579 --idx)
580 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
581
John McCall5808ce42011-02-03 08:15:49 +0000582 return method;
583}
584
585ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
586 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
587 /// is a non-lvalue expression whose value is the address of the object for
588 /// which the function is called.
589
590 CXXMethodDecl *method = tryCaptureCXXThis();
591 if (!method) return Diag(loc, diag::err_invalid_this_use);
592
593 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
John McCall469a1eb2011-02-02 13:00:07 +0000594 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000595}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000596
John McCall60d7b3a2010-08-24 06:29:42 +0000597ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000598Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000599 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000600 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000601 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000602 if (!TypeRep)
603 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604
John McCall9d125032010-01-15 18:39:57 +0000605 TypeSourceInfo *TInfo;
606 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
607 if (!TInfo)
608 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000609
610 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
611}
612
613/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
614/// Can be interpreted either as function-style casting ("int(x)")
615/// or class type construction ("ClassType(x,y,z)")
616/// or creation of a value-initialized type ("int()").
617ExprResult
618Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
619 SourceLocation LParenLoc,
620 MultiExprArg exprs,
621 SourceLocation RParenLoc) {
622 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000623 unsigned NumExprs = exprs.size();
624 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000625 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000626 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
627
Sebastian Redlf53597f2009-03-15 17:47:39 +0000628 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000629 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000630 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Douglas Gregorab6677e2010-09-08 00:15:04 +0000632 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000633 LParenLoc,
634 Exprs, NumExprs,
635 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000636 }
637
Anders Carlssonbb60a502009-08-27 03:53:50 +0000638 if (Ty->isArrayType())
639 return ExprError(Diag(TyBeginLoc,
640 diag::err_value_init_for_array_type) << FullRange);
641 if (!Ty->isVoidType() &&
642 RequireCompleteType(TyBeginLoc, Ty,
643 PDiag(diag::err_invalid_incomplete_type_use)
644 << FullRange))
645 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000646
Anders Carlssonbb60a502009-08-27 03:53:50 +0000647 if (RequireNonAbstractType(TyBeginLoc, Ty,
648 diag::err_allocation_of_abstract_type))
649 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000650
651
Douglas Gregor506ae412009-01-16 18:33:17 +0000652 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000653 // If the expression list is a single expression, the type conversion
654 // expression is equivalent (in definedness, and if defined in meaning) to the
655 // corresponding cast expression.
656 //
657 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000658 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000659 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000660 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000662 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000663 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000664 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000665
666 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000667
John McCallf871d0c2010-08-07 06:22:56 +0000668 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000669 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000670 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000671 Exprs[0], &BasePath,
672 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000673 }
674
Douglas Gregor19311e72010-09-08 21:40:08 +0000675 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
676 InitializationKind Kind
677 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
678 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000679 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000680 LParenLoc, RParenLoc);
681 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
682 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000683
Douglas Gregor19311e72010-09-08 21:40:08 +0000684 // FIXME: Improve AST representation?
685 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000686}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000687
John McCall6ec278d2011-01-27 09:37:56 +0000688/// doesUsualArrayDeleteWantSize - Answers whether the usual
689/// operator delete[] for the given type has a size_t parameter.
690static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
691 QualType allocType) {
692 const RecordType *record =
693 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
694 if (!record) return false;
695
696 // Try to find an operator delete[] in class scope.
697
698 DeclarationName deleteName =
699 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
700 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
701 S.LookupQualifiedName(ops, record->getDecl());
702
703 // We're just doing this for information.
704 ops.suppressDiagnostics();
705
706 // Very likely: there's no operator delete[].
707 if (ops.empty()) return false;
708
709 // If it's ambiguous, it should be illegal to call operator delete[]
710 // on this thing, so it doesn't matter if we allocate extra space or not.
711 if (ops.isAmbiguous()) return false;
712
713 LookupResult::Filter filter = ops.makeFilter();
714 while (filter.hasNext()) {
715 NamedDecl *del = filter.next()->getUnderlyingDecl();
716
717 // C++0x [basic.stc.dynamic.deallocation]p2:
718 // A template instance is never a usual deallocation function,
719 // regardless of its signature.
720 if (isa<FunctionTemplateDecl>(del)) {
721 filter.erase();
722 continue;
723 }
724
725 // C++0x [basic.stc.dynamic.deallocation]p2:
726 // If class T does not declare [an operator delete[] with one
727 // parameter] but does declare a member deallocation function
728 // named operator delete[] with exactly two parameters, the
729 // second of which has type std::size_t, then this function
730 // is a usual deallocation function.
731 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
732 filter.erase();
733 continue;
734 }
735 }
736 filter.done();
737
738 if (!ops.isSingleResult()) return false;
739
740 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
741 return (del->getNumParams() == 2);
742}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000743
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000744/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
745/// @code new (memory) int[size][4] @endcode
746/// or
747/// @code ::new Foo(23, "hello") @endcode
748/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000749ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000750Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000751 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000752 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000753 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000754 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000755 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000756 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
757
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000758 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000759 // If the specified type is an array, unwrap it and save the expression.
760 if (D.getNumTypeObjects() > 0 &&
761 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
762 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000763 if (TypeContainsAuto)
764 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
765 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000766 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000767 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
768 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000769 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000770 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
771 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000772
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000773 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000774 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000775 }
776
Douglas Gregor043cad22009-09-11 00:18:58 +0000777 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000778 if (ArraySize) {
779 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000780 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
781 break;
782
783 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
784 if (Expr *NumElts = (Expr *)Array.NumElts) {
785 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
786 !NumElts->isIntegerConstantExpr(Context)) {
787 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
788 << NumElts->getSourceRange();
789 return ExprError();
790 }
791 }
792 }
793 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000794
Richard Smith34b41d92011-02-20 03:19:35 +0000795 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
796 /*AllowAuto=*/true);
John McCallbf1a0282010-06-04 23:28:52 +0000797 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000798 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000799 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000800
Mike Stump1eb44332009-09-09 15:08:12 +0000801 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000802 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000803 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000804 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000805 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000806 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000807 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000808 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000809 ConstructorLParen,
810 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000811 ConstructorRParen,
812 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000813}
814
John McCall60d7b3a2010-08-24 06:29:42 +0000815ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000816Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
817 SourceLocation PlacementLParen,
818 MultiExprArg PlacementArgs,
819 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000820 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000821 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000822 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000823 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000824 SourceLocation ConstructorLParen,
825 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000826 SourceLocation ConstructorRParen,
827 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000828 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000829
Richard Smith34b41d92011-02-20 03:19:35 +0000830 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
831 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
832 if (ConstructorArgs.size() == 0)
833 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
834 << AllocType << TypeRange);
835 if (ConstructorArgs.size() != 1) {
836 Expr *FirstBad = ConstructorArgs.get()[1];
837 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
838 diag::err_auto_new_ctor_multiple_expressions)
839 << AllocType << TypeRange);
840 }
841 QualType DeducedType;
842 if (!DeduceAutoType(AllocType, ConstructorArgs.get()[0], DeducedType))
843 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
844 << AllocType
845 << ConstructorArgs.get()[0]->getType()
846 << TypeRange
847 << ConstructorArgs.get()[0]->getSourceRange());
848
849 AllocType = DeducedType;
850 AllocTypeInfo = Context.getTrivialTypeSourceInfo(AllocType, StartLoc);
851 }
852
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000853 // Per C++0x [expr.new]p5, the type being constructed may be a
854 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000855 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000856 if (const ConstantArrayType *Array
857 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000858 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
859 Context.getSizeType(),
860 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000861 AllocType = Array->getElementType();
862 }
863 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000864
Douglas Gregora0750762010-10-06 16:00:31 +0000865 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
866 return ExprError();
867
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000868 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000869
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000870 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
871 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000872 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000873
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000874 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000875
John McCall60d7b3a2010-08-24 06:29:42 +0000876 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000877 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000878 PDiag(diag::err_array_size_not_integral),
879 PDiag(diag::err_array_size_incomplete_type)
880 << ArraySize->getSourceRange(),
881 PDiag(diag::err_array_size_explicit_conversion),
882 PDiag(diag::note_array_size_conversion),
883 PDiag(diag::err_array_size_ambiguous_conversion),
884 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000885 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000886 : diag::ext_array_size_conversion));
887 if (ConvertedSize.isInvalid())
888 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000889
John McCall9ae2f072010-08-23 23:25:46 +0000890 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000891 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000892 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000893 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000894
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000895 // Let's see if this is a constant < 0. If so, we reject it out of hand.
896 // We don't care about special rules, so we tell the machinery it's not
897 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000898 if (!ArraySize->isValueDependent()) {
899 llvm::APSInt Value;
900 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
901 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000902 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000903 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000904 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000905 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000906 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000907
Douglas Gregor2767ce22010-08-18 00:39:00 +0000908 if (!AllocType->isDependentType()) {
909 unsigned ActiveSizeBits
910 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
911 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000912 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000913 diag::err_array_too_large)
914 << Value.toString(10)
915 << ArraySize->getSourceRange();
916 return ExprError();
917 }
918 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000919 } else if (TypeIdParens.isValid()) {
920 // Can't have dynamic array size when the type-id is in parentheses.
921 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
922 << ArraySize->getSourceRange()
923 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
924 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000925
Douglas Gregor4bd40312010-07-13 15:54:32 +0000926 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000927 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000928 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000929
Eli Friedman73c39ab2009-10-20 08:27:19 +0000930 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000931 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000932 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000933
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000934 FunctionDecl *OperatorNew = 0;
935 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000936 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
937 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000938
Sebastian Redl28507842009-02-26 14:39:58 +0000939 if (!AllocType->isDependentType() &&
940 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
941 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000942 SourceRange(PlacementLParen, PlacementRParen),
943 UseGlobal, AllocType, ArraySize, PlaceArgs,
944 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000945 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000946
947 // If this is an array allocation, compute whether the usual array
948 // deallocation function for the type has a size_t parameter.
949 bool UsualArrayDeleteWantsSize = false;
950 if (ArraySize && !AllocType->isDependentType())
951 UsualArrayDeleteWantsSize
952 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
953
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000954 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000955 if (OperatorNew) {
956 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000957 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000958 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000959 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000960 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000961
Anders Carlsson28e94832010-05-03 02:07:56 +0000962 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000963 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000964 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000965 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000966
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000967 NumPlaceArgs = AllPlaceArgs.size();
968 if (NumPlaceArgs > 0)
969 PlaceArgs = &AllPlaceArgs[0];
970 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000971
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000972 bool Init = ConstructorLParen.isValid();
973 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000974 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000975 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
976 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000977 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000978
Anders Carlsson48c95012010-05-03 15:45:23 +0000979 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000980 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000981 SourceRange InitRange(ConsArgs[0]->getLocStart(),
982 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983
Anders Carlsson48c95012010-05-03 15:45:23 +0000984 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
985 return ExprError();
986 }
987
Douglas Gregor99a2e602009-12-16 01:38:02 +0000988 if (!AllocType->isDependentType() &&
989 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
990 // C++0x [expr.new]p15:
991 // A new-expression that creates an object of type T initializes that
992 // object as follows:
993 InitializationKind Kind
994 // - If the new-initializer is omitted, the object is default-
995 // initialized (8.5); if no initialization is performed,
996 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000997 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000998 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +0000999 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001000 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001001 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001002 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001003
Douglas Gregor99a2e602009-12-16 01:38:02 +00001004 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001005 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001006 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001008 move(ConstructorArgs));
1009 if (FullInit.isInvalid())
1010 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011
1012 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001013 // constructor call, which CXXNewExpr handles directly.
1014 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1015 if (CXXBindTemporaryExpr *Binder
1016 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1017 FullInitExpr = Binder->getSubExpr();
1018 if (CXXConstructExpr *Construct
1019 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1020 Constructor = Construct->getConstructor();
1021 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1022 AEnd = Construct->arg_end();
1023 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001024 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001025 } else {
1026 // Take the converted initializer.
1027 ConvertedConstructorArgs.push_back(FullInit.release());
1028 }
1029 } else {
1030 // No initialization required.
1031 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001032
Douglas Gregor99a2e602009-12-16 01:38:02 +00001033 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001034 NumConsArgs = ConvertedConstructorArgs.size();
1035 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001036 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001037
Douglas Gregor6d908702010-02-26 05:06:18 +00001038 // Mark the new and delete operators as referenced.
1039 if (OperatorNew)
1040 MarkDeclarationReferenced(StartLoc, OperatorNew);
1041 if (OperatorDelete)
1042 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1043
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001044 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045
Sebastian Redlf53597f2009-03-15 17:47:39 +00001046 PlacementArgs.release();
1047 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001048
Ted Kremenekad7fe862010-02-11 22:51:03 +00001049 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001050 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001051 ArraySize, Constructor, Init,
1052 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001053 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001054 ResultType, AllocTypeInfo,
1055 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001056 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001057 TypeRange.getEnd(),
1058 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001059}
1060
1061/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1062/// in a new-expression.
1063/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001064bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001065 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001066 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1067 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001068 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001069 return Diag(Loc, diag::err_bad_new_type)
1070 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001071 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001072 return Diag(Loc, diag::err_bad_new_type)
1073 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001074 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001075 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001076 PDiag(diag::err_new_incomplete_type)
1077 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001078 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001079 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001080 diag::err_allocation_of_abstract_type))
1081 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001082 else if (AllocType->isVariablyModifiedType())
1083 return Diag(Loc, diag::err_variably_modified_new_type)
1084 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001086 return false;
1087}
1088
Douglas Gregor6d908702010-02-26 05:06:18 +00001089/// \brief Determine whether the given function is a non-placement
1090/// deallocation function.
1091static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1092 if (FD->isInvalidDecl())
1093 return false;
1094
1095 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1096 return Method->isUsualDeallocationFunction();
1097
1098 return ((FD->getOverloadedOperator() == OO_Delete ||
1099 FD->getOverloadedOperator() == OO_Array_Delete) &&
1100 FD->getNumParams() == 1);
1101}
1102
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001103/// FindAllocationFunctions - Finds the overloads of operator new and delete
1104/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001105bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1106 bool UseGlobal, QualType AllocType,
1107 bool IsArray, Expr **PlaceArgs,
1108 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001109 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001110 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001111 // --- Choosing an allocation function ---
1112 // C++ 5.3.4p8 - 14 & 18
1113 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1114 // in the scope of the allocated class.
1115 // 2) If an array size is given, look for operator new[], else look for
1116 // operator new.
1117 // 3) The first argument is always size_t. Append the arguments from the
1118 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001119
1120 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1121 // We don't care about the actual value of this argument.
1122 // FIXME: Should the Sema create the expression and embed it in the syntax
1123 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001124 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001125 Context.Target.getPointerWidth(0)),
1126 Context.getSizeType(),
1127 SourceLocation());
1128 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001129 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1130
Douglas Gregor6d908702010-02-26 05:06:18 +00001131 // C++ [expr.new]p8:
1132 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001133 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001134 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001135 // type, the allocation function's name is operator new[] and the
1136 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001137 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1138 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001139 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1140 IsArray ? OO_Array_Delete : OO_Delete);
1141
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001142 QualType AllocElemType = Context.getBaseElementType(AllocType);
1143
1144 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001145 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001146 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001147 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001148 AllocArgs.size(), Record, /*AllowMissing=*/true,
1149 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001150 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001151 }
1152 if (!OperatorNew) {
1153 // Didn't find a member overload. Look for a global one.
1154 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001155 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001156 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001157 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1158 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001159 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001160 }
1161
John McCall9c82afc2010-04-20 02:18:25 +00001162 // We don't need an operator delete if we're running under
1163 // -fno-exceptions.
1164 if (!getLangOptions().Exceptions) {
1165 OperatorDelete = 0;
1166 return false;
1167 }
1168
Anders Carlssond9583892009-05-31 20:26:12 +00001169 // FindAllocationOverload can change the passed in arguments, so we need to
1170 // copy them back.
1171 if (NumPlaceArgs > 0)
1172 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Douglas Gregor6d908702010-02-26 05:06:18 +00001174 // C++ [expr.new]p19:
1175 //
1176 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001177 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001178 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001179 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001180 // the scope of T. If this lookup fails to find the name, or if
1181 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001182 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001183 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001184 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001185 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001186 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001187 LookupQualifiedName(FoundDelete, RD);
1188 }
John McCall90c8c572010-03-18 08:19:33 +00001189 if (FoundDelete.isAmbiguous())
1190 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001191
1192 if (FoundDelete.empty()) {
1193 DeclareGlobalNewDelete();
1194 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1195 }
1196
1197 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001198
1199 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1200
John McCalledeb6c92010-09-14 21:34:24 +00001201 // Whether we're looking for a placement operator delete is dictated
1202 // by whether we selected a placement operator new, not by whether
1203 // we had explicit placement arguments. This matters for things like
1204 // struct A { void *operator new(size_t, int = 0); ... };
1205 // A *a = new A()
1206 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1207
1208 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001209 // C++ [expr.new]p20:
1210 // A declaration of a placement deallocation function matches the
1211 // declaration of a placement allocation function if it has the
1212 // same number of parameters and, after parameter transformations
1213 // (8.3.5), all parameter types except the first are
1214 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001215 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001216 // To perform this comparison, we compute the function type that
1217 // the deallocation function should have, and use that type both
1218 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001219 //
1220 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001221 QualType ExpectedFunctionType;
1222 {
1223 const FunctionProtoType *Proto
1224 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001225
Douglas Gregor6d908702010-02-26 05:06:18 +00001226 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001227 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001228 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1229 ArgTypes.push_back(Proto->getArgType(I));
1230
John McCalle23cf432010-12-14 08:05:40 +00001231 FunctionProtoType::ExtProtoInfo EPI;
1232 EPI.Variadic = Proto->isVariadic();
1233
Douglas Gregor6d908702010-02-26 05:06:18 +00001234 ExpectedFunctionType
1235 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001236 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001237 }
1238
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001239 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001240 DEnd = FoundDelete.end();
1241 D != DEnd; ++D) {
1242 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001243 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001244 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1245 // Perform template argument deduction to try to match the
1246 // expected function type.
1247 TemplateDeductionInfo Info(Context, StartLoc);
1248 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1249 continue;
1250 } else
1251 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1252
1253 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001254 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001255 }
1256 } else {
1257 // C++ [expr.new]p20:
1258 // [...] Any non-placement deallocation function matches a
1259 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001260 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001261 DEnd = FoundDelete.end();
1262 D != DEnd; ++D) {
1263 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1264 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001265 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001266 }
1267 }
1268
1269 // C++ [expr.new]p20:
1270 // [...] If the lookup finds a single matching deallocation
1271 // function, that function will be called; otherwise, no
1272 // deallocation function will be called.
1273 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001274 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001275
1276 // C++0x [expr.new]p20:
1277 // If the lookup finds the two-parameter form of a usual
1278 // deallocation function (3.7.4.2) and that function, considered
1279 // as a placement deallocation function, would have been
1280 // selected as a match for the allocation function, the program
1281 // is ill-formed.
1282 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1283 isNonPlacementDeallocationFunction(OperatorDelete)) {
1284 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001285 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001286 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1287 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1288 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001289 } else {
1290 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001291 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001292 }
1293 }
1294
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001295 return false;
1296}
1297
Sebastian Redl7f662392008-12-04 22:20:51 +00001298/// FindAllocationOverload - Find an fitting overload for the allocation
1299/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001300bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1301 DeclarationName Name, Expr** Args,
1302 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001303 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001304 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1305 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001306 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001307 if (AllowMissing)
1308 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001309 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001310 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001311 }
1312
John McCall90c8c572010-03-18 08:19:33 +00001313 if (R.isAmbiguous())
1314 return true;
1315
1316 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001317
John McCall5769d612010-02-08 23:07:23 +00001318 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001319 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001320 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001321 // Even member operator new/delete are implicitly treated as
1322 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001323 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001324
John McCall9aa472c2010-03-19 07:35:19 +00001325 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1326 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001327 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1328 Candidates,
1329 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001330 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001331 }
1332
John McCall9aa472c2010-03-19 07:35:19 +00001333 FunctionDecl *Fn = cast<FunctionDecl>(D);
1334 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001335 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001336 }
1337
1338 // Do the resolution.
1339 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001340 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001341 case OR_Success: {
1342 // Got one!
1343 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001344 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001345 // The first argument is size_t, and the first parameter must be size_t,
1346 // too. This is checked on declaration and can be assumed. (It can't be
1347 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001348 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001349 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1350 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001351 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001352 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001353 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001354 FnDecl->getParamDecl(i)),
1355 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001356 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001357 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001358 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001360 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001361 }
1362 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001363 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001364 return false;
1365 }
1366
1367 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001368 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001369 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001370 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001371 return true;
1372
1373 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001374 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001375 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001376 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001377 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001378
1379 case OR_Deleted:
1380 Diag(StartLoc, diag::err_ovl_deleted_call)
1381 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00001382 << Name
1383 << Best->Function->getMessageUnavailableAttr(
1384 !Best->Function->isDeleted())
1385 << Range;
John McCall120d63c2010-08-24 20:38:10 +00001386 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001387 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001388 }
1389 assert(false && "Unreachable, bad result from BestViableFunction");
1390 return true;
1391}
1392
1393
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001394/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1395/// delete. These are:
1396/// @code
1397/// void* operator new(std::size_t) throw(std::bad_alloc);
1398/// void* operator new[](std::size_t) throw(std::bad_alloc);
1399/// void operator delete(void *) throw();
1400/// void operator delete[](void *) throw();
1401/// @endcode
1402/// Note that the placement and nothrow forms of new are *not* implicitly
1403/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001404void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001405 if (GlobalNewDeleteDeclared)
1406 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001408 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409 // [...] The following allocation and deallocation functions (18.4) are
1410 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001411 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001412 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001413 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414 // void* operator new[](std::size_t) throw(std::bad_alloc);
1415 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001416 // void operator delete[](void*) throw();
1417 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001418 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001419 // new, operator new[], operator delete, operator delete[].
1420 //
1421 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1422 // "std" or "bad_alloc" as necessary to form the exception specification.
1423 // However, we do not make these implicit declarations visible to name
1424 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001425 if (!StdBadAlloc) {
1426 // The "std::bad_alloc" class has not yet been declared, so build it
1427 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001428 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1429 getOrCreateStdNamespace(),
1430 SourceLocation(),
1431 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001432 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001433 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001434 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001435
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001436 GlobalNewDeleteDeclared = true;
1437
1438 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1439 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001440 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001441
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001442 DeclareGlobalAllocationFunction(
1443 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001444 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001445 DeclareGlobalAllocationFunction(
1446 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001447 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001448 DeclareGlobalAllocationFunction(
1449 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1450 Context.VoidTy, VoidPtr);
1451 DeclareGlobalAllocationFunction(
1452 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1453 Context.VoidTy, VoidPtr);
1454}
1455
1456/// DeclareGlobalAllocationFunction - Declares a single implicit global
1457/// allocation function if it doesn't already exist.
1458void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001459 QualType Return, QualType Argument,
1460 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001461 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1462
1463 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001464 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001465 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001466 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001467 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001468 // Only look at non-template functions, as it is the predefined,
1469 // non-templated allocation function we are trying to declare here.
1470 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1471 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001472 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001473 Func->getParamDecl(0)->getType().getUnqualifiedType());
1474 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001475 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1476 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001477 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001478 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001479 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001480 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001481 }
1482 }
1483
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001484 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001485 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001486 = (Name.getCXXOverloadedOperator() == OO_New ||
1487 Name.getCXXOverloadedOperator() == OO_Array_New);
1488 if (HasBadAllocExceptionSpec) {
1489 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001490 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001491 }
John McCalle23cf432010-12-14 08:05:40 +00001492
1493 FunctionProtoType::ExtProtoInfo EPI;
1494 EPI.HasExceptionSpec = true;
1495 if (HasBadAllocExceptionSpec) {
1496 EPI.NumExceptions = 1;
1497 EPI.Exceptions = &BadAllocType;
1498 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001499
John McCalle23cf432010-12-14 08:05:40 +00001500 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001501 FunctionDecl *Alloc =
1502 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001503 FnType, /*TInfo=*/0, SC_None,
1504 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001505 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001506
Nuno Lopesfc284482009-12-16 16:59:22 +00001507 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001508 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001509
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001510 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001511 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001512 SC_None,
1513 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001514 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001515
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001516 // FIXME: Also add this declaration to the IdentifierResolver, but
1517 // make sure it is at the end of the chain to coincide with the
1518 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001519 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001520}
1521
Anders Carlsson78f74552009-11-15 18:45:20 +00001522bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1523 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001524 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001525 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001526 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001527 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001528
John McCalla24dc2e2009-11-17 02:14:36 +00001529 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001530 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001531
Chandler Carruth23893242010-06-28 00:30:51 +00001532 Found.suppressDiagnostics();
1533
John McCall046a7462010-08-04 00:31:26 +00001534 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001535 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1536 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001537 NamedDecl *ND = (*F)->getUnderlyingDecl();
1538
1539 // Ignore template operator delete members from the check for a usual
1540 // deallocation function.
1541 if (isa<FunctionTemplateDecl>(ND))
1542 continue;
1543
1544 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001545 Matches.push_back(F.getPair());
1546 }
1547
1548 // There's exactly one suitable operator; pick it.
1549 if (Matches.size() == 1) {
1550 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1551 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1552 Matches[0]);
1553 return false;
1554
1555 // We found multiple suitable operators; complain about the ambiguity.
1556 } else if (!Matches.empty()) {
1557 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1558 << Name << RD;
1559
1560 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1561 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1562 Diag((*F)->getUnderlyingDecl()->getLocation(),
1563 diag::note_member_declared_here) << Name;
1564 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001565 }
1566
1567 // We did find operator delete/operator delete[] declarations, but
1568 // none of them were suitable.
1569 if (!Found.empty()) {
1570 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1571 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001572
Anders Carlsson78f74552009-11-15 18:45:20 +00001573 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001574 F != FEnd; ++F)
1575 Diag((*F)->getUnderlyingDecl()->getLocation(),
1576 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001577
1578 return true;
1579 }
1580
1581 // Look for a global declaration.
1582 DeclareGlobalNewDelete();
1583 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001584
Anders Carlsson78f74552009-11-15 18:45:20 +00001585 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1586 Expr* DeallocArgs[1];
1587 DeallocArgs[0] = &Null;
1588 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1589 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1590 Operator))
1591 return true;
1592
1593 assert(Operator && "Did not find a deallocation function!");
1594 return false;
1595}
1596
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001597/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1598/// @code ::delete ptr; @endcode
1599/// or
1600/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001601ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001602Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001603 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001604 // C++ [expr.delete]p1:
1605 // The operand shall have a pointer type, or a class type having a single
1606 // conversion function to a pointer type. The result has type void.
1607 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001608 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1609
Anders Carlssond67c4c32009-08-16 20:29:29 +00001610 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001611 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001612 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Sebastian Redl28507842009-02-26 14:39:58 +00001614 if (!Ex->isTypeDependent()) {
1615 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001616
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001617 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001618 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001619 PDiag(diag::err_delete_incomplete_class_type)))
1620 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001621
John McCall32daa422010-03-31 01:36:47 +00001622 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1623
Fariborz Jahanian53462782009-09-11 21:44:33 +00001624 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001625 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001626 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001627 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001628 NamedDecl *D = I.getDecl();
1629 if (isa<UsingShadowDecl>(D))
1630 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1631
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001632 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001633 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001634 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001635
John McCall32daa422010-03-31 01:36:47 +00001636 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001637
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001638 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1639 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001640 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001641 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001642 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001643 if (ObjectPtrConversions.size() == 1) {
1644 // We have a single conversion to a pointer-to-object type. Perform
1645 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001646 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001647 if (!PerformImplicitConversion(Ex,
1648 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001649 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001650 Type = Ex->getType();
1651 }
1652 }
1653 else if (ObjectPtrConversions.size() > 1) {
1654 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1655 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001656 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1657 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001658 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001659 }
Sebastian Redl28507842009-02-26 14:39:58 +00001660 }
1661
Sebastian Redlf53597f2009-03-15 17:47:39 +00001662 if (!Type->isPointerType())
1663 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1664 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001665
Ted Kremenek6217b802009-07-29 21:53:49 +00001666 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001667 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001668 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001669 // effectively bans deletion of "void*". However, most compilers support
1670 // this, so we treat it as a warning unless we're in a SFINAE context.
1671 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1672 << Type << Ex->getSourceRange();
1673 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001674 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1675 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001676 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001677 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001678 PDiag(diag::warn_delete_incomplete)
1679 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001680 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001681
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001682 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001683 // [Note: a pointer to a const type can be the operand of a
1684 // delete-expression; it is not necessary to cast away the constness
1685 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001686 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001687 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001688 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001689
1690 if (Pointee->isArrayType() && !ArrayForm) {
1691 Diag(StartLoc, diag::warn_delete_array_type)
1692 << Type << Ex->getSourceRange()
1693 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1694 ArrayForm = true;
1695 }
1696
Anders Carlssond67c4c32009-08-16 20:29:29 +00001697 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1698 ArrayForm ? OO_Array_Delete : OO_Delete);
1699
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001700 QualType PointeeElem = Context.getBaseElementType(Pointee);
1701 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001702 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1703
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001705 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001706 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001707
John McCall6ec278d2011-01-27 09:37:56 +00001708 // If we're allocating an array of records, check whether the
1709 // usual operator delete[] has a size_t parameter.
1710 if (ArrayForm) {
1711 // If the user specifically asked to use the global allocator,
1712 // we'll need to do the lookup into the class.
1713 if (UseGlobal)
1714 UsualArrayDeleteWantsSize =
1715 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1716
1717 // Otherwise, the usual operator delete[] should be the
1718 // function we just found.
1719 else if (isa<CXXMethodDecl>(OperatorDelete))
1720 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1721 }
1722
Anders Carlsson78f74552009-11-15 18:45:20 +00001723 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001724 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001725 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001726 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001727 DiagnoseUseOfDecl(Dtor, StartLoc);
1728 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001729 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001730
Anders Carlssond67c4c32009-08-16 20:29:29 +00001731 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001732 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001733 DeclareGlobalNewDelete();
1734 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001735 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001736 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001737 OperatorDelete))
1738 return ExprError();
1739 }
Mike Stump1eb44332009-09-09 15:08:12 +00001740
John McCall9c82afc2010-04-20 02:18:25 +00001741 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001742
Douglas Gregord880f522011-02-01 15:50:11 +00001743 // Check access and ambiguity of operator delete and destructor.
1744 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1745 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1746 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1747 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1748 PDiag(diag::err_access_dtor) << PointeeElem);
1749 }
1750 }
1751
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001752 }
1753
Sebastian Redlf53597f2009-03-15 17:47:39 +00001754 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001755 ArrayFormAsWritten,
1756 UsualArrayDeleteWantsSize,
1757 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001758}
1759
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001760/// \brief Check the use of the given variable as a C++ condition in an if,
1761/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001762ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001763 SourceLocation StmtLoc,
1764 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001765 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001766
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001767 // C++ [stmt.select]p2:
1768 // The declarator shall not specify a function or an array.
1769 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001770 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001771 diag::err_invalid_use_of_function_type)
1772 << ConditionVar->getSourceRange());
1773 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001774 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001775 diag::err_invalid_use_of_array_type)
1776 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001777
Douglas Gregor40d96a62011-02-28 21:54:11 +00001778 Expr *Condition = DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1779 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001781 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001782 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001783 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001784 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785
Douglas Gregor586596f2010-05-06 17:25:47 +00001786 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001787}
1788
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001789/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1790bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1791 // C++ 6.4p4:
1792 // The value of a condition that is an initialized declaration in a statement
1793 // other than a switch statement is the value of the declared variable
1794 // implicitly converted to type bool. If that conversion is ill-formed, the
1795 // program is ill-formed.
1796 // The value of a condition that is an expression is the value of the
1797 // expression, implicitly converted to bool.
1798 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001799 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001800}
Douglas Gregor77a52232008-09-12 00:47:35 +00001801
1802/// Helper function to determine whether this is the (deprecated) C++
1803/// conversion from a string literal to a pointer to non-const char or
1804/// non-const wchar_t (for narrow and wide string literals,
1805/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001806bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001807Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1808 // Look inside the implicit cast, if it exists.
1809 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1810 From = Cast->getSubExpr();
1811
1812 // A string literal (2.13.4) that is not a wide string literal can
1813 // be converted to an rvalue of type "pointer to char"; a wide
1814 // string literal can be converted to an rvalue of type "pointer
1815 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001816 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001817 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001818 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001819 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001820 // This conversion is considered only when there is an
1821 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001822 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001823 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1824 (!StrLit->isWide() &&
1825 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1826 ToPointeeType->getKind() == BuiltinType::Char_S))))
1827 return true;
1828 }
1829
1830 return false;
1831}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001832
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001833static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001834 SourceLocation CastLoc,
1835 QualType Ty,
1836 CastKind Kind,
1837 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001838 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001839 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001840 switch (Kind) {
1841 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001842 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001843 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001844
Douglas Gregorba70ab62010-04-16 22:17:36 +00001845 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001846 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001847 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001848 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001849
1850 ExprResult Result =
1851 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001852 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001853 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1854 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001855 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001856 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001857
Douglas Gregorba70ab62010-04-16 22:17:36 +00001858 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1859 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001860
John McCall2de56d12010-08-25 11:45:40 +00001861 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001862 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863
Douglas Gregorba70ab62010-04-16 22:17:36 +00001864 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001865 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001866 if (Result.isInvalid())
1867 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001868
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001869 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001870 }
1871 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001872}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001873
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001874/// PerformImplicitConversion - Perform an implicit conversion of the
1875/// expression From to the type ToType using the pre-computed implicit
1876/// conversion sequence ICS. Returns true if there was an error, false
1877/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001878/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001879/// used in the error message.
1880bool
1881Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1882 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001883 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001884 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001885 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001886 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001887 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001888 return true;
1889 break;
1890
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001891 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001892
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001893 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001894 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001895 QualType BeforeToType;
1896 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001897 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001898
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001899 // If the user-defined conversion is specified by a conversion function,
1900 // the initial standard conversion sequence converts the source type to
1901 // the implicit object parameter of the conversion function.
1902 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001903 } else {
1904 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001905 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001906 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001907 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001908 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001909 // initial standard conversion sequence converts the source type to the
1910 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001911 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1912 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001913 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001914 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001915 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001916 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001917 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001918 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001919 return true;
1920 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921
1922 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001923 = BuildCXXCastArgument(*this,
1924 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001925 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001926 CastKind, cast<CXXMethodDecl>(FD),
1927 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001928 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001929
1930 if (CastArg.isInvalid())
1931 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001932
1933 From = CastArg.takeAs<Expr>();
1934
Eli Friedmand8889622009-11-27 04:41:50 +00001935 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001936 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001937 }
John McCall1d318332010-01-12 00:44:57 +00001938
1939 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001940 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001941 PDiag(diag::err_typecheck_ambiguous_condition)
1942 << From->getSourceRange());
1943 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001944
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001945 case ImplicitConversionSequence::EllipsisConversion:
1946 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001947 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001948
1949 case ImplicitConversionSequence::BadConversion:
1950 return true;
1951 }
1952
1953 // Everything went well.
1954 return false;
1955}
1956
1957/// PerformImplicitConversion - Perform an implicit conversion of the
1958/// expression From to the type ToType by following the standard
1959/// conversion sequence SCS. Returns true if there was an error, false
1960/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001961/// expression. Flavor is the context in which we're performing this
1962/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001963bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001964Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001965 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001966 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001967 // Overall FIXME: we are recomputing too many types here and doing far too
1968 // much extra work. What this means is that we need to keep track of more
1969 // information that is computed when we try the implicit conversion initially,
1970 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001971 QualType FromType = From->getType();
1972
Douglas Gregor225c41e2008-11-03 19:09:14 +00001973 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001974 // FIXME: When can ToType be a reference type?
1975 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001976 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001977 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001978 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001979 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001980 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001981 ConstructorArgs))
1982 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001983 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001984 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1985 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001986 move_arg(ConstructorArgs),
1987 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001988 CXXConstructExpr::CK_Complete,
1989 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001990 if (FromResult.isInvalid())
1991 return true;
1992 From = FromResult.takeAs<Expr>();
1993 return false;
1994 }
John McCall60d7b3a2010-08-24 06:29:42 +00001995 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001996 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1997 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001998 MultiExprArg(*this, &From, 1),
1999 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00002000 CXXConstructExpr::CK_Complete,
2001 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002003 if (FromResult.isInvalid())
2004 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002006 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00002007 return false;
2008 }
2009
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002010 // Resolve overloaded function references.
2011 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2012 DeclAccessPair Found;
2013 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2014 true, Found);
2015 if (!Fn)
2016 return true;
2017
2018 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2019 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002020
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002021 From = FixOverloadedFunctionReference(From, Found, Fn);
2022 FromType = From->getType();
2023 }
2024
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002025 // Perform the first implicit conversion.
2026 switch (SCS.First) {
2027 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002028 // Nothing to do.
2029 break;
2030
John McCallf6a16482010-12-04 03:47:34 +00002031 case ICK_Lvalue_To_Rvalue:
2032 // Should this get its own ICK?
2033 if (From->getObjectKind() == OK_ObjCProperty) {
2034 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00002035 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002036 }
2037
Chandler Carruth35001ca2011-02-17 21:10:52 +00002038 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00002039 CheckArrayAccess(From);
Chandler Carruth35001ca2011-02-17 21:10:52 +00002040
John McCallf6a16482010-12-04 03:47:34 +00002041 FromType = FromType.getUnqualifiedType();
2042 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2043 From, 0, VK_RValue);
2044 break;
2045
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002046 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002047 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002048 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002049 break;
2050
2051 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002052 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002053 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002054 break;
2055
2056 default:
2057 assert(false && "Improper first standard conversion");
2058 break;
2059 }
2060
2061 // Perform the second implicit conversion
2062 switch (SCS.Second) {
2063 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002064 // If both sides are functions (or pointers/references to them), there could
2065 // be incompatible exception declarations.
2066 if (CheckExceptionSpecCompatibility(From, ToType))
2067 return true;
2068 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002069 break;
2070
Douglas Gregor43c79c22009-12-09 00:47:37 +00002071 case ICK_NoReturn_Adjustment:
2072 // If both sides are functions (or pointers/references to them), there could
2073 // be incompatible exception declarations.
2074 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002075 return true;
2076
John McCalle6a365d2010-12-19 02:44:49 +00002077 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002078 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002080 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002081 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002082 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002083 break;
2084
2085 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002086 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002087 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002088 break;
2089
2090 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002091 case ICK_Complex_Conversion: {
2092 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2093 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2094 CastKind CK;
2095 if (FromEl->isRealFloatingType()) {
2096 if (ToEl->isRealFloatingType())
2097 CK = CK_FloatingComplexCast;
2098 else
2099 CK = CK_FloatingComplexToIntegralComplex;
2100 } else if (ToEl->isRealFloatingType()) {
2101 CK = CK_IntegralComplexToFloatingComplex;
2102 } else {
2103 CK = CK_IntegralComplexCast;
2104 }
2105 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002106 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002107 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002108
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002109 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002110 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002111 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002112 else
John McCall2de56d12010-08-25 11:45:40 +00002113 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002114 break;
2115
Douglas Gregorf9201e02009-02-11 23:02:49 +00002116 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002117 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002118 break;
2119
Anders Carlsson61faec12009-09-12 04:46:44 +00002120 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002121 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002122 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002123 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002124 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002125 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002126 << From->getSourceRange();
2127 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002128
John McCalldaa8e4e2010-11-15 09:13:47 +00002129 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002130 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002131 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002132 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002133 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002134 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002135 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002136
Anders Carlsson61faec12009-09-12 04:46:44 +00002137 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002138 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002139 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002140 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002141 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002142 if (CheckExceptionSpecCompatibility(From, ToType))
2143 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002144 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002145 break;
2146 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002147 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002148 CastKind Kind = CK_Invalid;
2149 switch (FromType->getScalarTypeKind()) {
2150 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2151 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2152 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2153 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2154 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2155 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2156 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2157 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002158
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002159 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002160 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002161 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002162
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002163 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002164 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002165 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002166 ToType.getNonReferenceType(),
2167 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002168 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002169 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002170 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002171 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002172
Sebastian Redl906082e2010-07-20 04:20:21 +00002173 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002174 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002175 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002176 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002177 }
2178
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002179 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002180 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002181 break;
2182
2183 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002184 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002185 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002186
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002187 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002188 // Case 1. x -> _Complex y
2189 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2190 QualType ElType = ToComplex->getElementType();
2191 bool isFloatingComplex = ElType->isRealFloatingType();
2192
2193 // x -> y
2194 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2195 // do nothing
2196 } else if (From->getType()->isRealFloatingType()) {
2197 ImpCastExprToType(From, ElType,
2198 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2199 } else {
2200 assert(From->getType()->isIntegerType());
2201 ImpCastExprToType(From, ElType,
2202 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2203 }
2204 // y -> _Complex y
2205 ImpCastExprToType(From, ToType,
2206 isFloatingComplex ? CK_FloatingRealToComplex
2207 : CK_IntegralRealToComplex);
2208
2209 // Case 2. _Complex x -> y
2210 } else {
2211 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2212 assert(FromComplex);
2213
2214 QualType ElType = FromComplex->getElementType();
2215 bool isFloatingComplex = ElType->isRealFloatingType();
2216
2217 // _Complex x -> x
2218 ImpCastExprToType(From, ElType,
2219 isFloatingComplex ? CK_FloatingComplexToReal
2220 : CK_IntegralComplexToReal);
2221
2222 // x -> y
2223 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2224 // do nothing
2225 } else if (ToType->isRealFloatingType()) {
2226 ImpCastExprToType(From, ToType,
2227 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2228 } else {
2229 assert(ToType->isIntegerType());
2230 ImpCastExprToType(From, ToType,
2231 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2232 }
2233 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002234 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002235
2236 case ICK_Block_Pointer_Conversion: {
2237 ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue);
2238 break;
2239 }
2240
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002241 case ICK_Lvalue_To_Rvalue:
2242 case ICK_Array_To_Pointer:
2243 case ICK_Function_To_Pointer:
2244 case ICK_Qualification:
2245 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002246 assert(false && "Improper second standard conversion");
2247 break;
2248 }
2249
2250 switch (SCS.Third) {
2251 case ICK_Identity:
2252 // Nothing to do.
2253 break;
2254
Sebastian Redl906082e2010-07-20 04:20:21 +00002255 case ICK_Qualification: {
2256 // The qualification keeps the category of the inner expression, unless the
2257 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002258 ExprValueKind VK = ToType->isReferenceType() ?
2259 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002260 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002261 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002262
2263 if (SCS.DeprecatedStringLiteralToCharPtr)
2264 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2265 << ToType.getNonReferenceType();
2266
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002267 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002268 }
2269
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002270 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002271 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002272 break;
2273 }
2274
2275 return false;
2276}
2277
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002278ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002279 SourceLocation KWLoc,
2280 ParsedType Ty,
2281 SourceLocation RParen) {
2282 TypeSourceInfo *TSInfo;
2283 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002285 if (!TSInfo)
2286 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002287 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002288}
2289
Sebastian Redlf8aca862010-09-14 23:40:14 +00002290static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2291 SourceLocation KeyLoc) {
Douglas Gregora0506182011-01-27 20:35:44 +00002292 // FIXME: For many of these traits, we need a complete type before we can
2293 // check these properties.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002294 assert(!T->isDependentType() &&
2295 "Cannot evaluate traits for dependent types.");
2296 ASTContext &C = Self.Context;
2297 switch(UTT) {
2298 default: assert(false && "Unknown type trait or not implemented");
2299 case UTT_IsPOD: return T->isPODType();
2300 case UTT_IsLiteral: return T->isLiteralType();
2301 case UTT_IsClass: // Fallthrough
2302 case UTT_IsUnion:
2303 if (const RecordType *Record = T->getAs<RecordType>()) {
2304 bool Union = Record->getDecl()->isUnion();
2305 return UTT == UTT_IsUnion ? Union : !Union;
2306 }
2307 return false;
2308 case UTT_IsEnum: return T->isEnumeralType();
2309 case UTT_IsPolymorphic:
2310 if (const RecordType *Record = T->getAs<RecordType>()) {
2311 // Type traits are only parsed in C++, so we've got CXXRecords.
2312 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2313 }
2314 return false;
2315 case UTT_IsAbstract:
2316 if (const RecordType *RT = T->getAs<RecordType>())
2317 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2318 return false;
2319 case UTT_IsEmpty:
2320 if (const RecordType *Record = T->getAs<RecordType>()) {
2321 return !Record->getDecl()->isUnion()
2322 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2323 }
2324 return false;
2325 case UTT_HasTrivialConstructor:
2326 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2327 // If __is_pod (type) is true then the trait is true, else if type is
2328 // a cv class or union type (or array thereof) with a trivial default
2329 // constructor ([class.ctor]) then the trait is true, else it is false.
2330 if (T->isPODType())
2331 return true;
2332 if (const RecordType *RT =
2333 C.getBaseElementType(T)->getAs<RecordType>())
2334 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2335 return false;
2336 case UTT_HasTrivialCopy:
2337 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2338 // If __is_pod (type) is true or type is a reference type then
2339 // the trait is true, else if type is a cv class or union type
2340 // with a trivial copy constructor ([class.copy]) then the trait
2341 // is true, else it is false.
2342 if (T->isPODType() || T->isReferenceType())
2343 return true;
2344 if (const RecordType *RT = T->getAs<RecordType>())
2345 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2346 return false;
2347 case UTT_HasTrivialAssign:
2348 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2349 // If type is const qualified or is a reference type then the
2350 // trait is false. Otherwise if __is_pod (type) is true then the
2351 // trait is true, else if type is a cv class or union type with
2352 // a trivial copy assignment ([class.copy]) then the trait is
2353 // true, else it is false.
2354 // Note: the const and reference restrictions are interesting,
2355 // given that const and reference members don't prevent a class
2356 // from having a trivial copy assignment operator (but do cause
2357 // errors if the copy assignment operator is actually used, q.v.
2358 // [class.copy]p12).
2359
2360 if (C.getBaseElementType(T).isConstQualified())
2361 return false;
2362 if (T->isPODType())
2363 return true;
2364 if (const RecordType *RT = T->getAs<RecordType>())
2365 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2366 return false;
2367 case UTT_HasTrivialDestructor:
2368 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2369 // If __is_pod (type) is true or type is a reference type
2370 // then the trait is true, else if type is a cv class or union
2371 // type (or array thereof) with a trivial destructor
2372 // ([class.dtor]) then the trait is true, else it is
2373 // false.
2374 if (T->isPODType() || T->isReferenceType())
2375 return true;
2376 if (const RecordType *RT =
2377 C.getBaseElementType(T)->getAs<RecordType>())
2378 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2379 return false;
2380 // TODO: Propagate nothrowness for implicitly declared special members.
2381 case UTT_HasNothrowAssign:
2382 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2383 // If type is const qualified or is a reference type then the
2384 // trait is false. Otherwise if __has_trivial_assign (type)
2385 // is true then the trait is true, else if type is a cv class
2386 // or union type with copy assignment operators that are known
2387 // not to throw an exception then the trait is true, else it is
2388 // false.
2389 if (C.getBaseElementType(T).isConstQualified())
2390 return false;
2391 if (T->isReferenceType())
2392 return false;
2393 if (T->isPODType())
2394 return true;
2395 if (const RecordType *RT = T->getAs<RecordType>()) {
2396 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2397 if (RD->hasTrivialCopyAssignment())
2398 return true;
2399
2400 bool FoundAssign = false;
2401 bool AllNoThrow = true;
2402 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002403 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2404 Sema::LookupOrdinaryName);
2405 if (Self.LookupQualifiedName(Res, RD)) {
2406 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2407 Op != OpEnd; ++Op) {
2408 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2409 if (Operator->isCopyAssignmentOperator()) {
2410 FoundAssign = true;
2411 const FunctionProtoType *CPT
2412 = Operator->getType()->getAs<FunctionProtoType>();
2413 if (!CPT->hasEmptyExceptionSpec()) {
2414 AllNoThrow = false;
2415 break;
2416 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002417 }
2418 }
2419 }
2420
2421 return FoundAssign && AllNoThrow;
2422 }
2423 return false;
2424 case UTT_HasNothrowCopy:
2425 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2426 // If __has_trivial_copy (type) is true then the trait is true, else
2427 // if type is a cv class or union type with copy constructors that are
2428 // known not to throw an exception then the trait is true, else it is
2429 // false.
2430 if (T->isPODType() || T->isReferenceType())
2431 return true;
2432 if (const RecordType *RT = T->getAs<RecordType>()) {
2433 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2434 if (RD->hasTrivialCopyConstructor())
2435 return true;
2436
2437 bool FoundConstructor = false;
2438 bool AllNoThrow = true;
2439 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002440 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002441 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002442 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002443 // A template constructor is never a copy constructor.
2444 // FIXME: However, it may actually be selected at the actual overload
2445 // resolution point.
2446 if (isa<FunctionTemplateDecl>(*Con))
2447 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002448 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2449 if (Constructor->isCopyConstructor(FoundTQs)) {
2450 FoundConstructor = true;
2451 const FunctionProtoType *CPT
2452 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002453 // TODO: check whether evaluating default arguments can throw.
2454 // For now, we'll be conservative and assume that they can throw.
2455 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002456 AllNoThrow = false;
2457 break;
2458 }
2459 }
2460 }
2461
2462 return FoundConstructor && AllNoThrow;
2463 }
2464 return false;
2465 case UTT_HasNothrowConstructor:
2466 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2467 // If __has_trivial_constructor (type) is true then the trait is
2468 // true, else if type is a cv class or union type (or array
2469 // thereof) with a default constructor that is known not to
2470 // throw an exception then the trait is true, else it is false.
2471 if (T->isPODType())
2472 return true;
2473 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2474 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2475 if (RD->hasTrivialConstructor())
2476 return true;
2477
Sebastian Redl751025d2010-09-13 22:02:47 +00002478 DeclContext::lookup_const_iterator Con, ConEnd;
2479 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2480 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002481 // FIXME: In C++0x, a constructor template can be a default constructor.
2482 if (isa<FunctionTemplateDecl>(*Con))
2483 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002484 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2485 if (Constructor->isDefaultConstructor()) {
2486 const FunctionProtoType *CPT
2487 = Constructor->getType()->getAs<FunctionProtoType>();
2488 // TODO: check whether evaluating default arguments can throw.
2489 // For now, we'll be conservative and assume that they can throw.
2490 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2491 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002492 }
2493 }
2494 return false;
2495 case UTT_HasVirtualDestructor:
2496 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2497 // If type is a class type with a virtual destructor ([class.dtor])
2498 // then the trait is true, else it is false.
2499 if (const RecordType *Record = T->getAs<RecordType>()) {
2500 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002501 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002502 return Destructor->isVirtual();
2503 }
2504 return false;
2505 }
2506}
2507
2508ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002509 SourceLocation KWLoc,
2510 TypeSourceInfo *TSInfo,
2511 SourceLocation RParen) {
2512 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002513
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002514 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2515 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002516 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002517 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002518 QualType E = T;
2519 if (T->isIncompleteArrayType())
2520 E = Context.getAsArrayType(T)->getElementType();
2521 if (!T->isVoidType() &&
2522 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002523 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002524 return ExprError();
2525 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002526
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002527 bool Value = false;
2528 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002529 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002530
2531 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002532 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002533}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002534
Francois Pichet6ad6f282010-12-07 00:08:36 +00002535ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2536 SourceLocation KWLoc,
2537 ParsedType LhsTy,
2538 ParsedType RhsTy,
2539 SourceLocation RParen) {
2540 TypeSourceInfo *LhsTSInfo;
2541 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2542 if (!LhsTSInfo)
2543 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2544
2545 TypeSourceInfo *RhsTSInfo;
2546 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2547 if (!RhsTSInfo)
2548 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2549
2550 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2551}
2552
2553static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2554 QualType LhsT, QualType RhsT,
2555 SourceLocation KeyLoc) {
2556 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2557 "Cannot evaluate traits for dependent types.");
2558
2559 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00002560 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002561 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00002562 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00002563 // Base and Derived are not unions and name the same class type without
2564 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00002565
John McCalld89d30f2011-01-28 22:02:36 +00002566 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2567 if (!lhsRecord) return false;
2568
2569 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2570 if (!rhsRecord) return false;
2571
2572 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2573 == (lhsRecord == rhsRecord));
2574
2575 if (lhsRecord == rhsRecord)
2576 return !lhsRecord->getDecl()->isUnion();
2577
2578 // C++0x [meta.rel]p2:
2579 // If Base and Derived are class types and are different types
2580 // (ignoring possible cv-qualifiers) then Derived shall be a
2581 // complete type.
2582 if (Self.RequireCompleteType(KeyLoc, RhsT,
2583 diag::err_incomplete_type_used_in_type_trait_expr))
2584 return false;
2585
2586 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2587 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2588 }
2589
Francois Pichetf1872372010-12-08 22:35:30 +00002590 case BTT_TypeCompatible:
2591 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2592 RhsT.getUnqualifiedType());
Douglas Gregor9f361132011-01-27 20:28:01 +00002593
2594 case BTT_IsConvertibleTo: {
2595 // C++0x [meta.rel]p4:
2596 // Given the following function prototype:
2597 //
2598 // template <class T>
2599 // typename add_rvalue_reference<T>::type create();
2600 //
2601 // the predicate condition for a template specialization
2602 // is_convertible<From, To> shall be satisfied if and only if
2603 // the return expression in the following code would be
2604 // well-formed, including any implicit conversions to the return
2605 // type of the function:
2606 //
2607 // To test() {
2608 // return create<From>();
2609 // }
2610 //
2611 // Access checking is performed as if in a context unrelated to To and
2612 // From. Only the validity of the immediate context of the expression
2613 // of the return-statement (including conversions to the return type)
2614 // is considered.
2615 //
2616 // We model the initialization as a copy-initialization of a temporary
2617 // of the appropriate type, which for this expression is identical to the
2618 // return statement (since NRVO doesn't apply).
2619 if (LhsT->isObjectType() || LhsT->isFunctionType())
2620 LhsT = Self.Context.getRValueReferenceType(LhsT);
2621
2622 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00002623 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00002624 Expr::getValueKindForType(LhsT));
2625 Expr *FromPtr = &From;
2626 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2627 SourceLocation()));
2628
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002629 // Perform the initialization within a SFINAE trap at translation unit
2630 // scope.
2631 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2632 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002633 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2634 if (Init.getKind() == InitializationSequence::FailedSequence)
2635 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002636
Douglas Gregor9f361132011-01-27 20:28:01 +00002637 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2638 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2639 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002640 }
2641 llvm_unreachable("Unknown type trait or not implemented");
2642}
2643
2644ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2645 SourceLocation KWLoc,
2646 TypeSourceInfo *LhsTSInfo,
2647 TypeSourceInfo *RhsTSInfo,
2648 SourceLocation RParen) {
2649 QualType LhsT = LhsTSInfo->getType();
2650 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002651
John McCalld89d30f2011-01-28 22:02:36 +00002652 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00002653 if (getLangOptions().CPlusPlus) {
2654 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2655 << SourceRange(KWLoc, RParen);
2656 return ExprError();
2657 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002658 }
2659
2660 bool Value = false;
2661 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2662 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2663
Francois Pichetf1872372010-12-08 22:35:30 +00002664 // Select trait result type.
2665 QualType ResultType;
2666 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002667 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2668 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002669 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002670 }
2671
Francois Pichet6ad6f282010-12-07 00:08:36 +00002672 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2673 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002674 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002675}
2676
John McCallf89e55a2010-11-18 06:31:45 +00002677QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2678 ExprValueKind &VK,
2679 SourceLocation Loc,
2680 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002681 const char *OpSpelling = isIndirect ? "->*" : ".*";
2682 // C++ 5.5p2
2683 // The binary operator .* [p3: ->*] binds its second operand, which shall
2684 // be of type "pointer to member of T" (where T is a completely-defined
2685 // class type) [...]
2686 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002687 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002688 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002689 Diag(Loc, diag::err_bad_memptr_rhs)
2690 << OpSpelling << RType << rex->getSourceRange();
2691 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002692 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002693
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002694 QualType Class(MemPtr->getClass(), 0);
2695
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002696 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2697 // member pointer points must be completely-defined. However, there is no
2698 // reason for this semantic distinction, and the rule is not enforced by
2699 // other compilers. Therefore, we do not check this property, as it is
2700 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002701
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002702 // C++ 5.5p2
2703 // [...] to its first operand, which shall be of class T or of a class of
2704 // which T is an unambiguous and accessible base class. [p3: a pointer to
2705 // such a class]
2706 QualType LType = lex->getType();
2707 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002708 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002709 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002710 else {
2711 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002712 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002713 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002714 return QualType();
2715 }
2716 }
2717
Douglas Gregora4923eb2009-11-16 21:35:15 +00002718 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002719 // If we want to check the hierarchy, we need a complete type.
2720 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2721 << OpSpelling << (int)isIndirect)) {
2722 return QualType();
2723 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002724 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002725 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002726 // FIXME: Would it be useful to print full ambiguity paths, or is that
2727 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002728 if (!IsDerivedFrom(LType, Class, Paths) ||
2729 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2730 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002731 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002732 return QualType();
2733 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002734 // Cast LHS to type of use.
2735 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002736 ExprValueKind VK =
2737 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002738
John McCallf871d0c2010-08-07 06:22:56 +00002739 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002740 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002741 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002742 }
2743
Douglas Gregored8abf12010-07-08 06:14:04 +00002744 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002745 // Diagnose use of pointer-to-member type which when used as
2746 // the functional cast in a pointer-to-member expression.
2747 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2748 return QualType();
2749 }
John McCallf89e55a2010-11-18 06:31:45 +00002750
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002751 // C++ 5.5p2
2752 // The result is an object or a function of the type specified by the
2753 // second operand.
2754 // The cv qualifiers are the union of those in the pointer and the left side,
2755 // in accordance with 5.5p5 and 5.2.5.
2756 // FIXME: This returns a dereferenced member function pointer as a normal
2757 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002758 // calling them. There's also a GCC extension to get a function pointer to the
2759 // thing, which is another complication, because this type - unlike the type
2760 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002761 // argument.
2762 // We probably need a "MemberFunctionClosureType" or something like that.
2763 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002764 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002765
Douglas Gregor6b4df912011-01-26 16:40:18 +00002766 // C++0x [expr.mptr.oper]p6:
2767 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002768 // ill-formed if the second operand is a pointer to member function with
2769 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2770 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002771 // is a pointer to member function with ref-qualifier &&.
2772 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2773 switch (Proto->getRefQualifier()) {
2774 case RQ_None:
2775 // Do nothing
2776 break;
2777
2778 case RQ_LValue:
2779 if (!isIndirect && !lex->Classify(Context).isLValue())
2780 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2781 << RType << 1 << lex->getSourceRange();
2782 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002783
Douglas Gregor6b4df912011-01-26 16:40:18 +00002784 case RQ_RValue:
2785 if (isIndirect || !lex->Classify(Context).isRValue())
2786 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2787 << RType << 0 << lex->getSourceRange();
2788 break;
2789 }
2790 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002791
John McCallf89e55a2010-11-18 06:31:45 +00002792 // C++ [expr.mptr.oper]p6:
2793 // The result of a .* expression whose second operand is a pointer
2794 // to a data member is of the same value category as its
2795 // first operand. The result of a .* expression whose second
2796 // operand is a pointer to a member function is a prvalue. The
2797 // result of an ->* expression is an lvalue if its second operand
2798 // is a pointer to data member and a prvalue otherwise.
2799 if (Result->isFunctionType())
2800 VK = VK_RValue;
2801 else if (isIndirect)
2802 VK = VK_LValue;
2803 else
2804 VK = lex->getValueKind();
2805
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002806 return Result;
2807}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002808
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002809/// \brief Try to convert a type to another according to C++0x 5.16p3.
2810///
2811/// This is part of the parameter validation for the ? operator. If either
2812/// value operand is a class type, the two operands are attempted to be
2813/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002814/// It returns true if the program is ill-formed and has already been diagnosed
2815/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002816static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2817 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002818 bool &HaveConversion,
2819 QualType &ToType) {
2820 HaveConversion = false;
2821 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002822
2823 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002824 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002825 // C++0x 5.16p3
2826 // The process for determining whether an operand expression E1 of type T1
2827 // can be converted to match an operand expression E2 of type T2 is defined
2828 // as follows:
2829 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002830 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002831 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002832 // E1 can be converted to match E2 if E1 can be implicitly converted to
2833 // type "lvalue reference to T2", subject to the constraint that in the
2834 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002835 QualType T = Self.Context.getLValueReferenceType(ToType);
2836 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002837
Douglas Gregorb70cf442010-03-26 20:14:36 +00002838 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2839 if (InitSeq.isDirectReferenceBinding()) {
2840 ToType = T;
2841 HaveConversion = true;
2842 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002843 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002844
Douglas Gregorb70cf442010-03-26 20:14:36 +00002845 if (InitSeq.isAmbiguous())
2846 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002847 }
John McCallb1bdc622010-02-25 01:37:24 +00002848
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002849 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2850 // -- if E1 and E2 have class type, and the underlying class types are
2851 // the same or one is a base class of the other:
2852 QualType FTy = From->getType();
2853 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002854 const RecordType *FRec = FTy->getAs<RecordType>();
2855 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002856 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002857 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002859 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002860 // E1 can be converted to match E2 if the class of T2 is the
2861 // same type as, or a base class of, the class of T1, and
2862 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002863 if (FRec == TRec || FDerivedFromT) {
2864 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002865 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2866 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2867 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2868 HaveConversion = true;
2869 return false;
2870 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871
Douglas Gregorb70cf442010-03-26 20:14:36 +00002872 if (InitSeq.isAmbiguous())
2873 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002874 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002875 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876
Douglas Gregorb70cf442010-03-26 20:14:36 +00002877 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002878 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002879
Douglas Gregorb70cf442010-03-26 20:14:36 +00002880 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2881 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002882 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002883 // an rvalue).
2884 //
2885 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2886 // to the array-to-pointer or function-to-pointer conversions.
2887 if (!TTy->getAs<TagType>())
2888 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002889
Douglas Gregorb70cf442010-03-26 20:14:36 +00002890 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2891 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002892 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002893 ToType = TTy;
2894 if (InitSeq.isAmbiguous())
2895 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2896
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002897 return false;
2898}
2899
2900/// \brief Try to find a common type for two according to C++0x 5.16p5.
2901///
2902/// This is part of the parameter validation for the ? operator. If either
2903/// value operand is a class type, overload resolution is used to find a
2904/// conversion to a common type.
2905static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00002906 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002907 Expr *Args[2] = { LHS, RHS };
Chandler Carruth82214a82011-02-18 23:54:50 +00002908 OverloadCandidateSet CandidateSet(QuestionLoc);
2909 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2910 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002911
2912 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00002913 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002914 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002915 // We found a match. Perform the conversions on the arguments and move on.
2916 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002917 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002918 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002919 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002920 break;
Chandler Carruth25ca4212011-02-25 19:41:05 +00002921 if (Best->Function)
2922 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002923 return false;
2924
Douglas Gregor20093b42009-12-09 23:02:17 +00002925 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00002926
2927 // Emit a better diagnostic if one of the expressions is a null pointer
2928 // constant and the other is a pointer type. In this case, the user most
2929 // likely forgot to take the address of the other expression.
2930 if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
2931 return true;
2932
2933 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002934 << LHS->getType() << RHS->getType()
2935 << LHS->getSourceRange() << RHS->getSourceRange();
2936 return true;
2937
Douglas Gregor20093b42009-12-09 23:02:17 +00002938 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00002939 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002940 << LHS->getType() << RHS->getType()
2941 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002942 // FIXME: Print the possible common types by printing the return types of
2943 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002944 break;
2945
Douglas Gregor20093b42009-12-09 23:02:17 +00002946 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002947 assert(false && "Conditional operator has only built-in overloads");
2948 break;
2949 }
2950 return true;
2951}
2952
Sebastian Redl76458502009-04-17 16:30:52 +00002953/// \brief Perform an "extended" implicit conversion as returned by
2954/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002955static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2956 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2957 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2958 SourceLocation());
2959 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002960 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002961 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002962 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002963
Douglas Gregorb70cf442010-03-26 20:14:36 +00002964 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002965 return false;
2966}
2967
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002968/// \brief Check the operands of ?: under C++ semantics.
2969///
2970/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2971/// extension. In this case, LHS == Cond. (But they're not aliases.)
2972QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00002973 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002974 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002975 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2976 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002977
2978 // C++0x 5.16p1
2979 // The first expression is contextually converted to bool.
2980 if (!Cond->isTypeDependent()) {
2981 if (CheckCXXBooleanCondition(Cond))
2982 return QualType();
2983 }
2984
John McCallf89e55a2010-11-18 06:31:45 +00002985 // Assume r-value.
2986 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002987 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002988
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002989 // Either of the arguments dependent?
2990 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2991 return Context.DependentTy;
2992
2993 // C++0x 5.16p2
2994 // If either the second or the third operand has type (cv) void, ...
2995 QualType LTy = LHS->getType();
2996 QualType RTy = RHS->getType();
2997 bool LVoid = LTy->isVoidType();
2998 bool RVoid = RTy->isVoidType();
2999 if (LVoid || RVoid) {
3000 // ... then the [l2r] conversions are performed on the second and third
3001 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00003002 DefaultFunctionArrayLvalueConversion(LHS);
3003 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003004 LTy = LHS->getType();
3005 RTy = RHS->getType();
3006
3007 // ... and one of the following shall hold:
3008 // -- The second or the third operand (but not both) is a throw-
3009 // expression; the result is of the type of the other and is an rvalue.
3010 bool LThrow = isa<CXXThrowExpr>(LHS);
3011 bool RThrow = isa<CXXThrowExpr>(RHS);
3012 if (LThrow && !RThrow)
3013 return RTy;
3014 if (RThrow && !LThrow)
3015 return LTy;
3016
3017 // -- Both the second and third operands have type void; the result is of
3018 // type void and is an rvalue.
3019 if (LVoid && RVoid)
3020 return Context.VoidTy;
3021
3022 // Neither holds, error.
3023 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3024 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3025 << LHS->getSourceRange() << RHS->getSourceRange();
3026 return QualType();
3027 }
3028
3029 // Neither is void.
3030
3031 // C++0x 5.16p3
3032 // Otherwise, if the second and third operand have different types, and
3033 // either has (cv) class type, and attempt is made to convert each of those
3034 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003035 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003036 (LTy->isRecordType() || RTy->isRecordType())) {
3037 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3038 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003039 QualType L2RType, R2LType;
3040 bool HaveL2R, HaveR2L;
3041 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003042 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003043 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003044 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003045
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003046 // If both can be converted, [...] the program is ill-formed.
3047 if (HaveL2R && HaveR2L) {
3048 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3049 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3050 return QualType();
3051 }
3052
3053 // If exactly one conversion is possible, that conversion is applied to
3054 // the chosen operand and the converted operands are used in place of the
3055 // original operands for the remainder of this section.
3056 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003057 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003058 return QualType();
3059 LTy = LHS->getType();
3060 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003061 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003062 return QualType();
3063 RTy = RHS->getType();
3064 }
3065 }
3066
3067 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003068 // If the second and third operands are glvalues of the same value
3069 // category and have the same type, the result is of that type and
3070 // value category and it is a bit-field if the second or the third
3071 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003072 // We only extend this to bitfields, not to the crazy other kinds of
3073 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003074 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003075 if (Same &&
John McCall56ca35d2011-02-17 10:25:35 +00003076 LHS->isGLValue() &&
John McCallf89e55a2010-11-18 06:31:45 +00003077 LHS->getValueKind() == RHS->getValueKind() &&
John McCall56ca35d2011-02-17 10:25:35 +00003078 LHS->isOrdinaryOrBitFieldObject() &&
3079 RHS->isOrdinaryOrBitFieldObject()) {
John McCallf89e55a2010-11-18 06:31:45 +00003080 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00003081 if (LHS->getObjectKind() == OK_BitField ||
3082 RHS->getObjectKind() == OK_BitField)
3083 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003084 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003085 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003086
3087 // C++0x 5.16p5
3088 // Otherwise, the result is an rvalue. If the second and third operands
3089 // do not have the same type, and either has (cv) class type, ...
3090 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3091 // ... overload resolution is used to determine the conversions (if any)
3092 // to be applied to the operands. If the overload resolution fails, the
3093 // program is ill-formed.
3094 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3095 return QualType();
3096 }
3097
3098 // C++0x 5.16p6
3099 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3100 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00003101 DefaultFunctionArrayLvalueConversion(LHS);
3102 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003103 LTy = LHS->getType();
3104 RTy = RHS->getType();
3105
3106 // After those conversions, one of the following shall hold:
3107 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003108 // is of that type. If the operands have class type, the result
3109 // is a prvalue temporary of the result type, which is
3110 // copy-initialized from either the second operand or the third
3111 // operand depending on the value of the first operand.
3112 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3113 if (LTy->isRecordType()) {
3114 // The operands have class type. Make a temporary copy.
3115 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003116 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3117 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003118 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003119 if (LHSCopy.isInvalid())
3120 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121
3122 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3123 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003124 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003125 if (RHSCopy.isInvalid())
3126 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127
Douglas Gregorb65a4582010-05-19 23:40:50 +00003128 LHS = LHSCopy.takeAs<Expr>();
3129 RHS = RHSCopy.takeAs<Expr>();
3130 }
3131
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003132 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003133 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003134
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003135 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003136 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003137 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3138
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003139 // -- The second and third operands have arithmetic or enumeration type;
3140 // the usual arithmetic conversions are performed to bring them to a
3141 // common type, and the result is of that type.
3142 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3143 UsualArithmeticConversions(LHS, RHS);
3144 return LHS->getType();
3145 }
3146
3147 // -- The second and third operands have pointer type, or one has pointer
3148 // type and the other is a null pointer constant; pointer conversions
3149 // and qualification conversions are performed to bring them to their
3150 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003151 // -- The second and third operands have pointer to member type, or one has
3152 // pointer to member type and the other is a null pointer constant;
3153 // pointer to member conversions and qualification conversions are
3154 // performed to bring them to a common type, whose cv-qualification
3155 // shall match the cv-qualification of either the second or the third
3156 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003157 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003158 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003159 isSFINAEContext()? 0 : &NonStandardCompositeType);
3160 if (!Composite.isNull()) {
3161 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003162 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003163 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3164 << LTy << RTy << Composite
3165 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003166
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003167 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003168 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003169
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003170 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003171 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3172 if (!Composite.isNull())
3173 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003174
Chandler Carruth7ef93242011-02-19 00:13:59 +00003175 // Check if we are using a null with a non-pointer type.
3176 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
3177 return QualType();
3178
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003179 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3180 << LHS->getType() << RHS->getType()
3181 << LHS->getSourceRange() << RHS->getSourceRange();
3182 return QualType();
3183}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003184
3185/// \brief Find a merged pointer type and convert the two expressions to it.
3186///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003187/// This finds the composite pointer type (or member pointer type) for @p E1
3188/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3189/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003190/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003191///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003192/// \param Loc The location of the operator requiring these two expressions to
3193/// be converted to the composite pointer type.
3194///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003195/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3196/// a non-standard (but still sane) composite type to which both expressions
3197/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3198/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003200 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003201 bool *NonStandardCompositeType) {
3202 if (NonStandardCompositeType)
3203 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003204
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003205 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3206 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003208 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3209 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003210 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003211
3212 // C++0x 5.9p2
3213 // Pointer conversions and qualification conversions are performed on
3214 // pointer operands to bring them to their composite pointer type. If
3215 // one operand is a null pointer constant, the composite pointer type is
3216 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003217 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003218 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003219 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003220 else
John McCall404cd162010-11-13 01:35:44 +00003221 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003222 return T2;
3223 }
Douglas Gregorce940492009-09-25 04:25:58 +00003224 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003225 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003226 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003227 else
John McCall404cd162010-11-13 01:35:44 +00003228 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003229 return T1;
3230 }
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Douglas Gregor20b3e992009-08-24 17:42:35 +00003232 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003233 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3234 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003235 return QualType();
3236
3237 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3238 // the other has type "pointer to cv2 T" and the composite pointer type is
3239 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3240 // Otherwise, the composite pointer type is a pointer type similar to the
3241 // type of one of the operands, with a cv-qualification signature that is
3242 // the union of the cv-qualification signatures of the operand types.
3243 // In practice, the first part here is redundant; it's subsumed by the second.
3244 // What we do here is, we build the two possible composite types, and try the
3245 // conversions in both directions. If only one works, or if the two composite
3246 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003247 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003248 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3249 QualifierVector QualifierUnion;
3250 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3251 ContainingClassVector;
3252 ContainingClassVector MemberOfClass;
3253 QualType Composite1 = Context.getCanonicalType(T1),
3254 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003256 do {
3257 const PointerType *Ptr1, *Ptr2;
3258 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3259 (Ptr2 = Composite2->getAs<PointerType>())) {
3260 Composite1 = Ptr1->getPointeeType();
3261 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003262
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003263 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003265 if (NonStandardCompositeType &&
3266 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3267 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268
Douglas Gregor20b3e992009-08-24 17:42:35 +00003269 QualifierUnion.push_back(
3270 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3271 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3272 continue;
3273 }
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Douglas Gregor20b3e992009-08-24 17:42:35 +00003275 const MemberPointerType *MemPtr1, *MemPtr2;
3276 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3277 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3278 Composite1 = MemPtr1->getPointeeType();
3279 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003280
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003281 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003282 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003283 if (NonStandardCompositeType &&
3284 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3285 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003286
Douglas Gregor20b3e992009-08-24 17:42:35 +00003287 QualifierUnion.push_back(
3288 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3289 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3290 MemPtr2->getClass()));
3291 continue;
3292 }
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Douglas Gregor20b3e992009-08-24 17:42:35 +00003294 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Douglas Gregor20b3e992009-08-24 17:42:35 +00003296 // Cannot unwrap any more types.
3297 break;
3298 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003299
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003300 if (NeedConstBefore && NonStandardCompositeType) {
3301 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003302 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003303 // requirements of C++ [conv.qual]p4 bullet 3.
3304 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3305 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3306 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3307 *NonStandardCompositeType = true;
3308 }
3309 }
3310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003311
Douglas Gregor20b3e992009-08-24 17:42:35 +00003312 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003313 ContainingClassVector::reverse_iterator MOC
3314 = MemberOfClass.rbegin();
3315 for (QualifierVector::reverse_iterator
3316 I = QualifierUnion.rbegin(),
3317 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003318 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003319 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003320 if (MOC->first && MOC->second) {
3321 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003322 Composite1 = Context.getMemberPointerType(
3323 Context.getQualifiedType(Composite1, Quals),
3324 MOC->first);
3325 Composite2 = Context.getMemberPointerType(
3326 Context.getQualifiedType(Composite2, Quals),
3327 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003328 } else {
3329 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003330 Composite1
3331 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3332 Composite2
3333 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003334 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003335 }
3336
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003337 // Try to convert to the first composite pointer type.
3338 InitializedEntity Entity1
3339 = InitializedEntity::InitializeTemporary(Composite1);
3340 InitializationKind Kind
3341 = InitializationKind::CreateCopy(Loc, SourceLocation());
3342 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3343 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003345 if (E1ToC1 && E2ToC1) {
3346 // Conversion to Composite1 is viable.
3347 if (!Context.hasSameType(Composite1, Composite2)) {
3348 // Composite2 is a different type from Composite1. Check whether
3349 // Composite2 is also viable.
3350 InitializedEntity Entity2
3351 = InitializedEntity::InitializeTemporary(Composite2);
3352 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3353 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3354 if (E1ToC2 && E2ToC2) {
3355 // Both Composite1 and Composite2 are viable and are different;
3356 // this is an ambiguity.
3357 return QualType();
3358 }
3359 }
3360
3361 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003362 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003363 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003364 if (E1Result.isInvalid())
3365 return QualType();
3366 E1 = E1Result.takeAs<Expr>();
3367
3368 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003369 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003370 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003371 if (E2Result.isInvalid())
3372 return QualType();
3373 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003374
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003375 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003376 }
3377
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003378 // Check whether Composite2 is viable.
3379 InitializedEntity Entity2
3380 = InitializedEntity::InitializeTemporary(Composite2);
3381 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3382 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3383 if (!E1ToC2 || !E2ToC2)
3384 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003386 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003387 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003388 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003389 if (E1Result.isInvalid())
3390 return QualType();
3391 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003393 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003394 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003395 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003396 if (E2Result.isInvalid())
3397 return QualType();
3398 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003400 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003401}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003402
John McCall60d7b3a2010-08-24 06:29:42 +00003403ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003404 if (!E)
3405 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003406
Anders Carlsson089c2602009-08-15 23:41:35 +00003407 if (!Context.getLangOptions().CPlusPlus)
3408 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003409
Douglas Gregor51326552009-12-24 18:51:59 +00003410 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3411
Ted Kremenek6217b802009-07-29 21:53:49 +00003412 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003413 if (!RT)
3414 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Douglas Gregor5e6fcd42011-02-08 02:14:35 +00003416 // If the result is a glvalue, we shouldn't bind it.
3417 if (E->Classify(Context).isGLValue())
3418 return Owned(E);
John McCall86ff3082010-02-04 22:26:26 +00003419
3420 // That should be enough to guarantee that this type is complete.
3421 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003422 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003423 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003424 return Owned(E);
3425
Douglas Gregordb89f282010-07-01 22:47:18 +00003426 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003427 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003428 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003429 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003430 CheckDestructorAccess(E->getExprLoc(), Destructor,
3431 PDiag(diag::err_access_dtor_temp)
3432 << E->getType());
3433 }
Anders Carlssondef11992009-05-30 20:36:53 +00003434 // FIXME: Add the temporary to the temporaries vector.
3435 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3436}
3437
John McCall4765fa02010-12-06 08:20:24 +00003438Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003439 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003441 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3442 assert(ExprTemporaries.size() >= FirstTemporary);
3443 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003444 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003445
John McCall4765fa02010-12-06 08:20:24 +00003446 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3447 &ExprTemporaries[FirstTemporary],
3448 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003449 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3450 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003452 return E;
3453}
3454
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003455ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003456Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003457 if (SubExpr.isInvalid())
3458 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003459
John McCall4765fa02010-12-06 08:20:24 +00003460 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003461}
3462
John McCall4765fa02010-12-06 08:20:24 +00003463Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003464 assert(SubStmt && "sub statement can't be null!");
3465
3466 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3467 assert(ExprTemporaries.size() >= FirstTemporary);
3468 if (ExprTemporaries.size() == FirstTemporary)
3469 return SubStmt;
3470
3471 // FIXME: In order to attach the temporaries, wrap the statement into
3472 // a StmtExpr; currently this is only used for asm statements.
3473 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3474 // a new AsmStmtWithTemporaries.
3475 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3476 SourceLocation(),
3477 SourceLocation());
3478 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3479 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003480 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003481}
3482
John McCall60d7b3a2010-08-24 06:29:42 +00003483ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003484Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003485 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003486 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003487 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003488 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003489 if (Result.isInvalid()) return ExprError();
3490 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003491
John McCall9ae2f072010-08-23 23:25:46 +00003492 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003493 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003494 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003495 // If we have a pointer to a dependent type and are using the -> operator,
3496 // the object type is the type that the pointer points to. We might still
3497 // have enough information about that type to do something useful.
3498 if (OpKind == tok::arrow)
3499 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3500 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003501
John McCallb3d87482010-08-24 05:47:05 +00003502 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003503 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003504 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003505 }
Mike Stump1eb44332009-09-09 15:08:12 +00003506
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003507 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003508 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003509 // returned, with the original second operand.
3510 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003511 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003512 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003513 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003514 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003516 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003517 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3518 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003519 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003520 Base = Result.get();
3521 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003522 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003523 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003524 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003525 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003526 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003527 for (unsigned i = 0; i < Locations.size(); i++)
3528 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003529 return ExprError();
3530 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003531 }
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Douglas Gregor31658df2009-11-20 19:58:21 +00003533 if (BaseType->isPointerType())
3534 BaseType = BaseType->getPointeeType();
3535 }
Mike Stump1eb44332009-09-09 15:08:12 +00003536
3537 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003538 // vector types or Objective-C interfaces. Just return early and let
3539 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003540 if (!BaseType->isRecordType()) {
3541 // C++ [basic.lookup.classref]p2:
3542 // [...] If the type of the object expression is of pointer to scalar
3543 // type, the unqualified-id is looked up in the context of the complete
3544 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003545 //
3546 // This also indicates that we should be parsing a
3547 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003548 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003549 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003550 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003551 }
Mike Stump1eb44332009-09-09 15:08:12 +00003552
Douglas Gregor03c57052009-11-17 05:17:33 +00003553 // The object type must be complete (or dependent).
3554 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003555 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003556 PDiag(diag::err_incomplete_member_access)))
3557 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003558
Douglas Gregorc68afe22009-09-03 21:38:09 +00003559 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003560 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003561 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003562 // type C (or of pointer to a class type C), the unqualified-id is looked
3563 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003564 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003565 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003566}
3567
John McCall60d7b3a2010-08-24 06:29:42 +00003568ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003569 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003570 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003571 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3572 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003573 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003574
Douglas Gregor77549082010-02-24 21:29:12 +00003575 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003576 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003577 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003578 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003579 /*RPLoc*/ ExpectedLParenLoc);
3580}
Douglas Gregord4dca082010-02-24 18:44:31 +00003581
John McCall60d7b3a2010-08-24 06:29:42 +00003582ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003583 SourceLocation OpLoc,
3584 tok::TokenKind OpKind,
3585 const CXXScopeSpec &SS,
3586 TypeSourceInfo *ScopeTypeInfo,
3587 SourceLocation CCLoc,
3588 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003589 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00003590 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003591 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003592
Douglas Gregorb57fb492010-02-24 22:38:50 +00003593 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003594 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003595 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003597 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003598 if (OpKind == tok::arrow) {
3599 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3600 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003601 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003602 // The user wrote "p->" when she probably meant "p."; fix it.
3603 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3604 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003605 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003606 if (isSFINAEContext())
3607 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003608
Douglas Gregorb57fb492010-02-24 22:38:50 +00003609 OpKind = tok::period;
3610 }
3611 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003612
Douglas Gregorb57fb492010-02-24 22:38:50 +00003613 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3614 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003615 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003616 return ExprError();
3617 }
3618
3619 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003620 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003621 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003622 if (DestructedTypeInfo) {
3623 QualType DestructedType = DestructedTypeInfo->getType();
3624 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003625 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003626 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3627 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3628 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003629 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003630 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003631
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003632 // Recover by setting the destructed type to the object type.
3633 DestructedType = ObjectType;
3634 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3635 DestructedTypeStart);
3636 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3637 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003638 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003639
Douglas Gregorb57fb492010-02-24 22:38:50 +00003640 // C++ [expr.pseudo]p2:
3641 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3642 // form
3643 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003644 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003645 //
3646 // shall designate the same scalar type.
3647 if (ScopeTypeInfo) {
3648 QualType ScopeType = ScopeTypeInfo->getType();
3649 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003650 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003651
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003652 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003653 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003654 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003655 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003656
Douglas Gregorb57fb492010-02-24 22:38:50 +00003657 ScopeType = QualType();
3658 ScopeTypeInfo = 0;
3659 }
3660 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003661
John McCall9ae2f072010-08-23 23:25:46 +00003662 Expr *Result
3663 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3664 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00003665 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00003666 ScopeTypeInfo,
3667 CCLoc,
3668 TildeLoc,
3669 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670
Douglas Gregorb57fb492010-02-24 22:38:50 +00003671 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003672 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673
John McCall9ae2f072010-08-23 23:25:46 +00003674 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003675}
3676
John McCall60d7b3a2010-08-24 06:29:42 +00003677ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003678 SourceLocation OpLoc,
3679 tok::TokenKind OpKind,
3680 CXXScopeSpec &SS,
3681 UnqualifiedId &FirstTypeName,
3682 SourceLocation CCLoc,
3683 SourceLocation TildeLoc,
3684 UnqualifiedId &SecondTypeName,
3685 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00003686 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3687 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3688 "Invalid first type name in pseudo-destructor");
3689 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3690 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3691 "Invalid second type name in pseudo-destructor");
3692
Douglas Gregor77549082010-02-24 21:29:12 +00003693 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003695 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003696 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003697 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003698 if (OpKind == tok::arrow) {
3699 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3700 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003701 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003702 // The user wrote "p->" when she probably meant "p."; fix it.
3703 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003704 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003705 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003706 if (isSFINAEContext())
3707 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708
Douglas Gregor77549082010-02-24 21:29:12 +00003709 OpKind = tok::period;
3710 }
3711 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003712
3713 // Compute the object type that we should use for name lookup purposes. Only
3714 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003715 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003716 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00003717 if (ObjectType->isRecordType())
3718 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00003719 else if (ObjectType->isDependentType())
3720 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003721 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003722
3723 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003724 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003725 QualType DestructedType;
3726 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003727 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003728 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003729 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003730 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003731 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003732 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003733 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3734 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003735 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003736 // couldn't find anything useful in scope. Just store the identifier and
3737 // it's location, and we'll perform (qualified) name lookup again at
3738 // template instantiation time.
3739 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3740 SecondTypeName.StartLocation);
3741 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003742 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003743 diag::err_pseudo_dtor_destructor_non_type)
3744 << SecondTypeName.Identifier << ObjectType;
3745 if (isSFINAEContext())
3746 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003747
Douglas Gregor77549082010-02-24 21:29:12 +00003748 // Recover by assuming we had the right type all along.
3749 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003750 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003751 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003752 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003753 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003754 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003755 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3756 TemplateId->getTemplateArgs(),
3757 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003758 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003759 TemplateId->TemplateNameLoc,
3760 TemplateId->LAngleLoc,
3761 TemplateArgsPtr,
3762 TemplateId->RAngleLoc);
3763 if (T.isInvalid() || !T.get()) {
3764 // Recover by assuming we had the right type all along.
3765 DestructedType = ObjectType;
3766 } else
3767 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003768 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003769
3770 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003771 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003772 if (!DestructedType.isNull()) {
3773 if (!DestructedTypeInfo)
3774 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003775 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003776 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3777 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778
Douglas Gregorb57fb492010-02-24 22:38:50 +00003779 // Convert the name of the scope type (the type prior to '::') into a type.
3780 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003781 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003782 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003783 FirstTypeName.Identifier) {
3784 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003786 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00003787 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003788 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003789 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003790 diag::err_pseudo_dtor_destructor_non_type)
3791 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
Douglas Gregorb57fb492010-02-24 22:38:50 +00003793 if (isSFINAEContext())
3794 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003795
Douglas Gregorb57fb492010-02-24 22:38:50 +00003796 // Just drop this type. It's unnecessary anyway.
3797 ScopeType = QualType();
3798 } else
3799 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003800 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003801 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003802 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003803 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3804 TemplateId->getTemplateArgs(),
3805 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003806 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003807 TemplateId->TemplateNameLoc,
3808 TemplateId->LAngleLoc,
3809 TemplateArgsPtr,
3810 TemplateId->RAngleLoc);
3811 if (T.isInvalid() || !T.get()) {
3812 // Recover by dropping this type.
3813 ScopeType = QualType();
3814 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003815 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003816 }
3817 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003818
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003819 if (!ScopeType.isNull() && !ScopeTypeInfo)
3820 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3821 FirstTypeName.StartLocation);
3822
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
John McCall9ae2f072010-08-23 23:25:46 +00003824 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003825 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003826 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003827}
3828
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003829ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3830 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003831 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3832 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003833 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003834
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003836 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003837 SourceLocation(), Method->getType(),
3838 VK_RValue, OK_Ordinary);
3839 QualType ResultType = Method->getResultType();
3840 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3841 ResultType = ResultType.getNonLValueExprType(Context);
3842
Douglas Gregor7edfb692009-11-23 12:27:39 +00003843 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3844 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003845 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003846 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003847 return CE;
3848}
3849
Sebastian Redl2e156222010-09-10 20:55:43 +00003850ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3851 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003852 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3853 Operand->CanThrow(Context),
3854 KeyLoc, RParen));
3855}
3856
3857ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3858 Expr *Operand, SourceLocation RParen) {
3859 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003860}
3861
John McCallf6a16482010-12-04 03:47:34 +00003862/// Perform the conversions required for an expression used in a
3863/// context that ignores the result.
3864void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003865 // C99 6.3.2.1:
3866 // [Except in specific positions,] an lvalue that does not have
3867 // array type is converted to the value stored in the
3868 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003869 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003870
John McCallf6a16482010-12-04 03:47:34 +00003871 // We always want to do this on ObjC property references.
3872 if (E->getObjectKind() == OK_ObjCProperty) {
3873 ConvertPropertyForRValue(E);
3874 if (E->isRValue()) return;
3875 }
3876
3877 // Otherwise, this rule does not apply in C++, at least not for the moment.
3878 if (getLangOptions().CPlusPlus) return;
3879
3880 // GCC seems to also exclude expressions of incomplete enum type.
3881 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3882 if (!T->getDecl()->isComplete()) {
3883 // FIXME: stupid workaround for a codegen bug!
3884 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3885 return;
3886 }
3887 }
3888
3889 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003890 if (!E->getType()->isVoidType())
3891 RequireCompleteType(E->getExprLoc(), E->getType(),
3892 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003893}
3894
3895ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003897 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003898
Douglas Gregord0937222010-12-13 22:49:22 +00003899 if (DiagnoseUnexpandedParameterPack(FullExpr))
3900 return ExprError();
3901
John McCallf6a16482010-12-04 03:47:34 +00003902 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003903 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003904 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003905}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003906
3907StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3908 if (!FullStmt) return StmtError();
3909
John McCall4765fa02010-12-06 08:20:24 +00003910 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003911}