blob: cf2e10d531f9cfaf6f4b180b80cb9d35ea5112b7 [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"
19#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000020#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000027#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000032
John McCallb3d87482010-08-24 05:47:05 +000033ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000034 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000035 SourceLocation NameLoc,
36 Scope *S, CXXScopeSpec &SS,
37 ParsedType ObjectTypePtr,
38 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000039 // Determine where to perform name lookup.
40
41 // FIXME: This area of the standard is very messy, and the current
42 // wording is rather unclear about which scopes we search for the
43 // destructor name; see core issues 399 and 555. Issue 399 in
44 // particular shows where the current description of destructor name
45 // lookup is completely out of line with existing practice, e.g.,
46 // this appears to be ill-formed:
47 //
48 // namespace N {
49 // template <typename T> struct S {
50 // ~S();
51 // };
52 // }
53 //
54 // void f(N::S<int>* s) {
55 // s->N::S<int>::~S();
56 // }
57 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000058 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000059 // For this reason, we're currently only doing the C++03 version of this
60 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000061 QualType SearchType;
62 DeclContext *LookupCtx = 0;
63 bool isDependent = false;
64 bool LookInScope = false;
65
66 // If we have an object type, it's because we are in a
67 // pseudo-destructor-expression or a member access expression, and
68 // we know what type we're looking for.
69 if (ObjectTypePtr)
70 SearchType = GetTypeFromParser(ObjectTypePtr);
71
72 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000073 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000074
Douglas Gregor93649fd2010-02-23 00:15:22 +000075 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000077 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000078 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000079 // the type-names are looked up as types in the scope designated by the
80 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000081 //
82 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000083 //
84 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000085 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000086 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000087 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000089 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000090 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000092 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000093 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000094 // nested-name-specifier.
95 DeclContext *DC = computeDeclContext(SS, EnteringContext);
96 if (DC && DC->isFileContext()) {
97 AlreadySearched = true;
98 LookupCtx = DC;
99 isDependent = false;
100 } else if (DC && isa<CXXRecordDecl>(DC))
101 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000102
Sebastian Redlc0fee502010-07-07 23:17:38 +0000103 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000104 NestedNameSpecifier *Prefix = 0;
105 if (AlreadySearched) {
106 // Nothing left to do.
107 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
108 CXXScopeSpec PrefixSS;
109 PrefixSS.setScopeRep(Prefix);
110 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
111 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000112 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000113 LookupCtx = computeDeclContext(SearchType);
114 isDependent = SearchType->isDependentType();
115 } else {
116 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000117 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000119
Douglas Gregoredc90502010-02-25 04:46:04 +0000120 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000121 } else if (ObjectTypePtr) {
122 // C++ [basic.lookup.classref]p3:
123 // If the unqualified-id is ~type-name, the type-name is looked up
124 // in the context of the entire postfix-expression. If the type T
125 // of the object expression is of a class type C, the type-name is
126 // also looked up in the scope of class C. At least one of the
127 // lookups shall find a name that refers to (possibly
128 // cv-qualified) T.
129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000131 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000132 "Caller should have completed object type");
133
134 LookInScope = true;
135 } else {
136 // Perform lookup into the current scope (only).
137 LookInScope = true;
138 }
139
140 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
141 for (unsigned Step = 0; Step != 2; ++Step) {
142 // Look for the name first in the computed lookup context (if we
143 // have one) and, if that fails to find a match, in the sope (if
144 // we're allowed to look there).
145 Found.clear();
146 if (Step == 0 && LookupCtx)
147 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000148 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000149 LookupName(Found, S);
150 else
151 continue;
152
153 // FIXME: Should we be suppressing ambiguities here?
154 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000155 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000156
157 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
158 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000159
160 if (SearchType.isNull() || SearchType->isDependentType() ||
161 Context.hasSameUnqualifiedType(T, SearchType)) {
162 // We found our type!
163
John McCallb3d87482010-08-24 05:47:05 +0000164 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 }
166 }
167
168 // If the name that we found is a class template name, and it is
169 // the same name as the template name in the last part of the
170 // nested-name-specifier (if present) or the object type, then
171 // this is the destructor for that class.
172 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000173 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000174 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
175 QualType MemberOfType;
176 if (SS.isSet()) {
177 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
178 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000179 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
180 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000181 }
182 }
183 if (MemberOfType.isNull())
184 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000185
Douglas Gregor124b8782010-02-16 19:09:40 +0000186 if (MemberOfType.isNull())
187 continue;
188
189 // We're referring into a class template specialization. If the
190 // class template we found is the same as the template being
191 // specialized, we found what we are looking for.
192 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
193 if (ClassTemplateSpecializationDecl *Spec
194 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
195 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
196 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000197 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000198 }
199
200 continue;
201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000202
Douglas Gregor124b8782010-02-16 19:09:40 +0000203 // We're referring to an unresolved class template
204 // specialization. Determine whether we class template we found
205 // is the same as the template being specialized or, if we don't
206 // know which template is being specialized, that it at least
207 // has the same name.
208 if (const TemplateSpecializationType *SpecType
209 = MemberOfType->getAs<TemplateSpecializationType>()) {
210 TemplateName SpecName = SpecType->getTemplateName();
211
212 // The class template we found is the same template being
213 // specialized.
214 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
215 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000216 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000217
218 continue;
219 }
220
221 // The class template we found has the same name as the
222 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000223 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000224 = SpecName.getAsDependentTemplateName()) {
225 if (DepTemplate->isIdentifier() &&
226 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000227 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000228
229 continue;
230 }
231 }
232 }
233 }
234
235 if (isDependent) {
236 // We didn't find our type, but that's okay: it's dependent
237 // anyway.
238 NestedNameSpecifier *NNS = 0;
239 SourceRange Range;
240 if (SS.isSet()) {
241 NNS = (NestedNameSpecifier *)SS.getScopeRep();
242 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
243 } else {
244 NNS = NestedNameSpecifier::Create(Context, &II);
245 Range = SourceRange(NameLoc);
246 }
247
John McCallb3d87482010-08-24 05:47:05 +0000248 QualType T = CheckTypenameType(ETK_None, NNS, II,
249 SourceLocation(),
250 Range, NameLoc);
251 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000252 }
253
254 if (ObjectTypePtr)
255 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000256 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000257 else
258 Diag(NameLoc, diag::err_destructor_class_name);
259
John McCallb3d87482010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000261}
262
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000263/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000264ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000265 SourceLocation TypeidLoc,
266 TypeSourceInfo *Operand,
267 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000268 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000269 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000270 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000271 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000272 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000273 Qualifiers Quals;
274 QualType T
275 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
276 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000277 if (T->getAs<RecordType>() &&
278 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
279 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000280
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000281 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
282 Operand,
283 SourceRange(TypeidLoc, RParenLoc)));
284}
285
286/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 Expr *E,
290 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 if (E && !E->isTypeDependent()) {
293 QualType T = E->getType();
294 if (const RecordType *RecordT = T->getAs<RecordType>()) {
295 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
296 // C++ [expr.typeid]p3:
297 // [...] If the type of the expression is a class type, the class
298 // shall be completely-defined.
299 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
300 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000301
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000302 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000303 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 // polymorphic class type [...] [the] expression is an unevaluated
305 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000306 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000308
309 // We require a vtable to query the type at run time.
310 MarkVTableUsed(TypeidLoc, RecordD);
311 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000313
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000318 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000319 Qualifiers Quals;
320 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
321 if (!Context.hasSameType(T, UnqualT)) {
322 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000323 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000324 }
325 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000326
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000327 // If this is an unevaluated operand, clear out the set of
328 // declaration references we have been computing and eliminate any
329 // temporaries introduced in its computation.
330 if (isUnevaluatedOperand)
331 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000332
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000334 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000335 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000336}
337
338/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000339ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000340Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
341 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000342 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000343 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000344 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000345
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000346 if (!CXXTypeInfoDecl) {
347 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
348 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
349 LookupQualifiedName(R, getStdNamespace());
350 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
351 if (!CXXTypeInfoDecl)
352 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
353 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000355 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000356
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000357 if (isType) {
358 // The operand is a type; handle it as such.
359 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000360 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
361 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362 if (T.isNull())
363 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000364
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000365 if (!TInfo)
366 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000367
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000373}
374
Francois Pichet6915c522010-12-27 01:32:00 +0000375/// Retrieve the UuidAttr associated with QT.
376static UuidAttr *GetUuidAttrOfType(QualType QT) {
377 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000378 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000379 if (QT->isPointerType() || QT->isReferenceType())
380 Ty = QT->getPointeeType().getTypePtr();
381 else if (QT->isArrayType())
382 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
383
Francois Pichet6915c522010-12-27 01:32:00 +0000384 // Loop all class definition and declaration looking for an uuid attribute.
385 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
386 while (RD) {
387 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
388 return Uuid;
389 RD = RD->getPreviousDeclaration();
390 }
391 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000392}
393
Francois Pichet01b7c302010-09-08 12:20:18 +0000394/// \brief Build a Microsoft __uuidof expression with a type operand.
395ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
396 SourceLocation TypeidLoc,
397 TypeSourceInfo *Operand,
398 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000399 if (!Operand->getType()->isDependentType()) {
400 if (!GetUuidAttrOfType(Operand->getType()))
401 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
402 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000403
Francois Pichet01b7c302010-09-08 12:20:18 +0000404 // FIXME: add __uuidof semantic analysis for type operand.
405 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
406 Operand,
407 SourceRange(TypeidLoc, RParenLoc)));
408}
409
410/// \brief Build a Microsoft __uuidof expression with an expression operand.
411ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
412 SourceLocation TypeidLoc,
413 Expr *E,
414 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000415 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000416 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000417 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
418 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
419 }
420 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000421 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
422 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000424}
425
426/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
427ExprResult
428Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
429 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000430 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000431 if (!MSVCGuidDecl) {
432 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
433 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
434 LookupQualifiedName(R, Context.getTranslationUnitDecl());
435 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
436 if (!MSVCGuidDecl)
437 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000438 }
439
Francois Pichet01b7c302010-09-08 12:20:18 +0000440 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000441
Francois Pichet01b7c302010-09-08 12:20:18 +0000442 if (isType) {
443 // The operand is a type; handle it as such.
444 TypeSourceInfo *TInfo = 0;
445 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
446 &TInfo);
447 if (T.isNull())
448 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000449
Francois Pichet01b7c302010-09-08 12:20:18 +0000450 if (!TInfo)
451 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
452
453 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
454 }
455
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000456 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000457 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
458}
459
Steve Naroff1b273c42007-09-16 14:56:35 +0000460/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000461ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000462Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000463 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
466 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000467}
Chris Lattner50dd2892008-02-26 00:51:44 +0000468
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000469/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000470ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000471Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
472 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
473}
474
Chris Lattner50dd2892008-02-26 00:51:44 +0000475/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000476ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000477Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000478 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
479 return ExprError();
480 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
481}
482
483/// CheckCXXThrowOperand - Validate the operand of a throw.
484bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
485 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000486 // A throw-expression initializes a temporary object, called the exception
487 // object, the type of which is determined by removing any top-level
488 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000489 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000490 // or "pointer to function returning T", [...]
491 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000492 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000493 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000494
Sebastian Redl972041f2009-04-27 20:27:31 +0000495 DefaultFunctionArrayConversion(E);
496
497 // If the type of the exception would be an incomplete type or a pointer
498 // to an incomplete type other than (cv) void the program is ill-formed.
499 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000500 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000501 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000502 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000503 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000504 }
505 if (!isPointer || !Ty->isVoidType()) {
506 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000507 PDiag(isPointer ? diag::err_throw_incomplete_ptr
508 : diag::err_throw_incomplete)
509 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000510 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000511
Douglas Gregorbf422f92010-04-15 18:05:39 +0000512 if (RequireNonAbstractType(ThrowLoc, E->getType(),
513 PDiag(diag::err_throw_abstract_type)
514 << E->getSourceRange()))
515 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000516 }
517
John McCallac418162010-04-22 01:10:34 +0000518 // Initialize the exception result. This implicitly weeds out
519 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000520 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
521
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000522 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000523 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000524 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
525 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000526 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000527 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000528 if (Res.isInvalid())
529 return true;
530 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000531
Eli Friedman5ed9b932010-06-03 20:39:03 +0000532 // If the exception has class type, we need additional handling.
533 const RecordType *RecordTy = Ty->getAs<RecordType>();
534 if (!RecordTy)
535 return false;
536 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
537
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000538 // If we are throwing a polymorphic class type or pointer thereof,
539 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000540 MarkVTableUsed(ThrowLoc, RD);
541
Eli Friedman98efb9f2010-10-12 20:32:36 +0000542 // If a pointer is thrown, the referenced object will not be destroyed.
543 if (isPointer)
544 return false;
545
Eli Friedman5ed9b932010-06-03 20:39:03 +0000546 // If the class has a non-trivial destructor, we must be able to call it.
547 if (RD->hasTrivialDestructor())
548 return false;
549
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000551 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000552 if (!Destructor)
553 return false;
554
555 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
556 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000557 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000558 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000559}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000560
John McCall60d7b3a2010-08-24 06:29:42 +0000561ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000562 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
563 /// is a non-lvalue expression whose value is the address of the object for
564 /// which the function is called.
565
John McCallea1471e2010-05-20 01:18:31 +0000566 DeclContext *DC = getFunctionLevelDeclContext();
567 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000568 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000569 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000570 MD->getThisType(Context),
571 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000572
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000574}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000575
John McCall60d7b3a2010-08-24 06:29:42 +0000576ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000577Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000578 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000579 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000580 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000581 if (!TypeRep)
582 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
John McCall9d125032010-01-15 18:39:57 +0000584 TypeSourceInfo *TInfo;
585 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
586 if (!TInfo)
587 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000588
589 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
590}
591
592/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
593/// Can be interpreted either as function-style casting ("int(x)")
594/// or class type construction ("ClassType(x,y,z)")
595/// or creation of a value-initialized type ("int()").
596ExprResult
597Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
598 SourceLocation LParenLoc,
599 MultiExprArg exprs,
600 SourceLocation RParenLoc) {
601 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000602 unsigned NumExprs = exprs.size();
603 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000604 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000605 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
606
Sebastian Redlf53597f2009-03-15 17:47:39 +0000607 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000608 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000609 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Douglas Gregorab6677e2010-09-08 00:15:04 +0000611 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000612 LParenLoc,
613 Exprs, NumExprs,
614 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000615 }
616
Anders Carlssonbb60a502009-08-27 03:53:50 +0000617 if (Ty->isArrayType())
618 return ExprError(Diag(TyBeginLoc,
619 diag::err_value_init_for_array_type) << FullRange);
620 if (!Ty->isVoidType() &&
621 RequireCompleteType(TyBeginLoc, Ty,
622 PDiag(diag::err_invalid_incomplete_type_use)
623 << FullRange))
624 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000625
Anders Carlssonbb60a502009-08-27 03:53:50 +0000626 if (RequireNonAbstractType(TyBeginLoc, Ty,
627 diag::err_allocation_of_abstract_type))
628 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000629
630
Douglas Gregor506ae412009-01-16 18:33:17 +0000631 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000632 // If the expression list is a single expression, the type conversion
633 // expression is equivalent (in definedness, and if defined in meaning) to the
634 // corresponding cast expression.
635 //
636 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000637 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000638 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000639 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000640 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000641 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000642 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000643 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000644
645 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000646
John McCallf871d0c2010-08-07 06:22:56 +0000647 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000648 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000649 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000650 Exprs[0], &BasePath,
651 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000652 }
653
Douglas Gregor19311e72010-09-08 21:40:08 +0000654 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
655 InitializationKind Kind
656 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
657 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000658 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000659 LParenLoc, RParenLoc);
660 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
661 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000662
Douglas Gregor19311e72010-09-08 21:40:08 +0000663 // FIXME: Improve AST representation?
664 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000665}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000666
John McCall6ec278d2011-01-27 09:37:56 +0000667/// doesUsualArrayDeleteWantSize - Answers whether the usual
668/// operator delete[] for the given type has a size_t parameter.
669static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
670 QualType allocType) {
671 const RecordType *record =
672 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
673 if (!record) return false;
674
675 // Try to find an operator delete[] in class scope.
676
677 DeclarationName deleteName =
678 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
679 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
680 S.LookupQualifiedName(ops, record->getDecl());
681
682 // We're just doing this for information.
683 ops.suppressDiagnostics();
684
685 // Very likely: there's no operator delete[].
686 if (ops.empty()) return false;
687
688 // If it's ambiguous, it should be illegal to call operator delete[]
689 // on this thing, so it doesn't matter if we allocate extra space or not.
690 if (ops.isAmbiguous()) return false;
691
692 LookupResult::Filter filter = ops.makeFilter();
693 while (filter.hasNext()) {
694 NamedDecl *del = filter.next()->getUnderlyingDecl();
695
696 // C++0x [basic.stc.dynamic.deallocation]p2:
697 // A template instance is never a usual deallocation function,
698 // regardless of its signature.
699 if (isa<FunctionTemplateDecl>(del)) {
700 filter.erase();
701 continue;
702 }
703
704 // C++0x [basic.stc.dynamic.deallocation]p2:
705 // If class T does not declare [an operator delete[] with one
706 // parameter] but does declare a member deallocation function
707 // named operator delete[] with exactly two parameters, the
708 // second of which has type std::size_t, then this function
709 // is a usual deallocation function.
710 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
711 filter.erase();
712 continue;
713 }
714 }
715 filter.done();
716
717 if (!ops.isSingleResult()) return false;
718
719 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
720 return (del->getNumParams() == 2);
721}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000722
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000723/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
724/// @code new (memory) int[size][4] @endcode
725/// or
726/// @code ::new Foo(23, "hello") @endcode
727/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000728ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000729Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000730 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000731 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000732 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000733 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000734 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000735 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000736 // If the specified type is an array, unwrap it and save the expression.
737 if (D.getNumTypeObjects() > 0 &&
738 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
739 DeclaratorChunk &Chunk = D.getTypeObject(0);
740 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000741 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
742 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000743 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000744 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
745 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000746
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000747 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000748 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000749 }
750
Douglas Gregor043cad22009-09-11 00:18:58 +0000751 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000752 if (ArraySize) {
753 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000754 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
755 break;
756
757 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
758 if (Expr *NumElts = (Expr *)Array.NumElts) {
759 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
760 !NumElts->isIntegerConstantExpr(Context)) {
761 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
762 << NumElts->getSourceRange();
763 return ExprError();
764 }
765 }
766 }
767 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000768
John McCallbf1a0282010-06-04 23:28:52 +0000769 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
770 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000771 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000772 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000773
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000774 if (!TInfo)
775 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000776
Mike Stump1eb44332009-09-09 15:08:12 +0000777 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000778 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000779 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000780 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000781 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000782 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000783 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000784 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000785 ConstructorLParen,
786 move(ConstructorArgs),
787 ConstructorRParen);
788}
789
John McCall60d7b3a2010-08-24 06:29:42 +0000790ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000791Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
792 SourceLocation PlacementLParen,
793 MultiExprArg PlacementArgs,
794 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000795 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000796 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000797 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000798 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000799 SourceLocation ConstructorLParen,
800 MultiExprArg ConstructorArgs,
801 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000802 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000803
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000804 // Per C++0x [expr.new]p5, the type being constructed may be a
805 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000806 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000807 if (const ConstantArrayType *Array
808 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000809 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
810 Context.getSizeType(),
811 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000812 AllocType = Array->getElementType();
813 }
814 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000815
Douglas Gregora0750762010-10-06 16:00:31 +0000816 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
817 return ExprError();
818
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000819 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000820
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000821 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
822 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000823 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000824
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000825 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000826
John McCall60d7b3a2010-08-24 06:29:42 +0000827 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000828 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000829 PDiag(diag::err_array_size_not_integral),
830 PDiag(diag::err_array_size_incomplete_type)
831 << ArraySize->getSourceRange(),
832 PDiag(diag::err_array_size_explicit_conversion),
833 PDiag(diag::note_array_size_conversion),
834 PDiag(diag::err_array_size_ambiguous_conversion),
835 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000836 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000837 : diag::ext_array_size_conversion));
838 if (ConvertedSize.isInvalid())
839 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000840
John McCall9ae2f072010-08-23 23:25:46 +0000841 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000842 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000843 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000844 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000845
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000846 // Let's see if this is a constant < 0. If so, we reject it out of hand.
847 // We don't care about special rules, so we tell the machinery it's not
848 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000849 if (!ArraySize->isValueDependent()) {
850 llvm::APSInt Value;
851 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
852 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000853 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000854 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000855 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000856 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000857 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000858
Douglas Gregor2767ce22010-08-18 00:39:00 +0000859 if (!AllocType->isDependentType()) {
860 unsigned ActiveSizeBits
861 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
862 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000863 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000864 diag::err_array_too_large)
865 << Value.toString(10)
866 << ArraySize->getSourceRange();
867 return ExprError();
868 }
869 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000870 } else if (TypeIdParens.isValid()) {
871 // Can't have dynamic array size when the type-id is in parentheses.
872 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
873 << ArraySize->getSourceRange()
874 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
875 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000876
Douglas Gregor4bd40312010-07-13 15:54:32 +0000877 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000878 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000879 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000880
Eli Friedman73c39ab2009-10-20 08:27:19 +0000881 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000882 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000883 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000884
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000885 FunctionDecl *OperatorNew = 0;
886 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000887 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
888 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000889
Sebastian Redl28507842009-02-26 14:39:58 +0000890 if (!AllocType->isDependentType() &&
891 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
892 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000893 SourceRange(PlacementLParen, PlacementRParen),
894 UseGlobal, AllocType, ArraySize, PlaceArgs,
895 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000896 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000897
898 // If this is an array allocation, compute whether the usual array
899 // deallocation function for the type has a size_t parameter.
900 bool UsualArrayDeleteWantsSize = false;
901 if (ArraySize && !AllocType->isDependentType())
902 UsualArrayDeleteWantsSize
903 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
904
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000905 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000906 if (OperatorNew) {
907 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000908 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000909 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000910 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000911 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000912
Anders Carlsson28e94832010-05-03 02:07:56 +0000913 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000914 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000915 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000916 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000917
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000918 NumPlaceArgs = AllPlaceArgs.size();
919 if (NumPlaceArgs > 0)
920 PlaceArgs = &AllPlaceArgs[0];
921 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000922
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000923 bool Init = ConstructorLParen.isValid();
924 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000925 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000926 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
927 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000928 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000929
Anders Carlsson48c95012010-05-03 15:45:23 +0000930 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000931 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000932 SourceRange InitRange(ConsArgs[0]->getLocStart(),
933 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000934
Anders Carlsson48c95012010-05-03 15:45:23 +0000935 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
936 return ExprError();
937 }
938
Douglas Gregor99a2e602009-12-16 01:38:02 +0000939 if (!AllocType->isDependentType() &&
940 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
941 // C++0x [expr.new]p15:
942 // A new-expression that creates an object of type T initializes that
943 // object as follows:
944 InitializationKind Kind
945 // - If the new-initializer is omitted, the object is default-
946 // initialized (8.5); if no initialization is performed,
947 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000948 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +0000950 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000951 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000952 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000953 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954
Douglas Gregor99a2e602009-12-16 01:38:02 +0000955 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000956 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000957 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000958 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000959 move(ConstructorArgs));
960 if (FullInit.isInvalid())
961 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000962
963 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +0000964 // constructor call, which CXXNewExpr handles directly.
965 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
966 if (CXXBindTemporaryExpr *Binder
967 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
968 FullInitExpr = Binder->getSubExpr();
969 if (CXXConstructExpr *Construct
970 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
971 Constructor = Construct->getConstructor();
972 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
973 AEnd = Construct->arg_end();
974 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +0000975 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000976 } else {
977 // Take the converted initializer.
978 ConvertedConstructorArgs.push_back(FullInit.release());
979 }
980 } else {
981 // No initialization required.
982 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983
Douglas Gregor99a2e602009-12-16 01:38:02 +0000984 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000985 NumConsArgs = ConvertedConstructorArgs.size();
986 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000987 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000988
Douglas Gregor6d908702010-02-26 05:06:18 +0000989 // Mark the new and delete operators as referenced.
990 if (OperatorNew)
991 MarkDeclarationReferenced(StartLoc, OperatorNew);
992 if (OperatorDelete)
993 MarkDeclarationReferenced(StartLoc, OperatorDelete);
994
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000995 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996
Sebastian Redlf53597f2009-03-15 17:47:39 +0000997 PlacementArgs.release();
998 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000999
Ted Kremenekad7fe862010-02-11 22:51:03 +00001000 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001001 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001002 ArraySize, Constructor, Init,
1003 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001004 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001005 ResultType, AllocTypeInfo,
1006 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001007 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001008 TypeRange.getEnd(),
1009 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001010}
1011
1012/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1013/// in a new-expression.
1014/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001015bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001016 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001017 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1018 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001019 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001020 return Diag(Loc, diag::err_bad_new_type)
1021 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001022 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001023 return Diag(Loc, diag::err_bad_new_type)
1024 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001025 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001026 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001027 PDiag(diag::err_new_incomplete_type)
1028 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001029 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001030 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001031 diag::err_allocation_of_abstract_type))
1032 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001033 else if (AllocType->isVariablyModifiedType())
1034 return Diag(Loc, diag::err_variably_modified_new_type)
1035 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001036
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001037 return false;
1038}
1039
Douglas Gregor6d908702010-02-26 05:06:18 +00001040/// \brief Determine whether the given function is a non-placement
1041/// deallocation function.
1042static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1043 if (FD->isInvalidDecl())
1044 return false;
1045
1046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1047 return Method->isUsualDeallocationFunction();
1048
1049 return ((FD->getOverloadedOperator() == OO_Delete ||
1050 FD->getOverloadedOperator() == OO_Array_Delete) &&
1051 FD->getNumParams() == 1);
1052}
1053
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001054/// FindAllocationFunctions - Finds the overloads of operator new and delete
1055/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001056bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1057 bool UseGlobal, QualType AllocType,
1058 bool IsArray, Expr **PlaceArgs,
1059 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001060 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001061 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001062 // --- Choosing an allocation function ---
1063 // C++ 5.3.4p8 - 14 & 18
1064 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1065 // in the scope of the allocated class.
1066 // 2) If an array size is given, look for operator new[], else look for
1067 // operator new.
1068 // 3) The first argument is always size_t. Append the arguments from the
1069 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001070
1071 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1072 // We don't care about the actual value of this argument.
1073 // FIXME: Should the Sema create the expression and embed it in the syntax
1074 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001075 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001076 Context.Target.getPointerWidth(0)),
1077 Context.getSizeType(),
1078 SourceLocation());
1079 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001080 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1081
Douglas Gregor6d908702010-02-26 05:06:18 +00001082 // C++ [expr.new]p8:
1083 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001084 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001085 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001086 // type, the allocation function's name is operator new[] and the
1087 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001088 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1089 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001090 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1091 IsArray ? OO_Array_Delete : OO_Delete);
1092
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001093 QualType AllocElemType = Context.getBaseElementType(AllocType);
1094
1095 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001096 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001097 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001098 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001099 AllocArgs.size(), Record, /*AllowMissing=*/true,
1100 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001101 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001102 }
1103 if (!OperatorNew) {
1104 // Didn't find a member overload. Look for a global one.
1105 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001106 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001107 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001108 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1109 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001110 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001111 }
1112
John McCall9c82afc2010-04-20 02:18:25 +00001113 // We don't need an operator delete if we're running under
1114 // -fno-exceptions.
1115 if (!getLangOptions().Exceptions) {
1116 OperatorDelete = 0;
1117 return false;
1118 }
1119
Anders Carlssond9583892009-05-31 20:26:12 +00001120 // FindAllocationOverload can change the passed in arguments, so we need to
1121 // copy them back.
1122 if (NumPlaceArgs > 0)
1123 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Douglas Gregor6d908702010-02-26 05:06:18 +00001125 // C++ [expr.new]p19:
1126 //
1127 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001128 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001129 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001130 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001131 // the scope of T. If this lookup fails to find the name, or if
1132 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001133 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001134 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001135 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001136 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001137 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001138 LookupQualifiedName(FoundDelete, RD);
1139 }
John McCall90c8c572010-03-18 08:19:33 +00001140 if (FoundDelete.isAmbiguous())
1141 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001142
1143 if (FoundDelete.empty()) {
1144 DeclareGlobalNewDelete();
1145 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1146 }
1147
1148 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001149
1150 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1151
John McCalledeb6c92010-09-14 21:34:24 +00001152 // Whether we're looking for a placement operator delete is dictated
1153 // by whether we selected a placement operator new, not by whether
1154 // we had explicit placement arguments. This matters for things like
1155 // struct A { void *operator new(size_t, int = 0); ... };
1156 // A *a = new A()
1157 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1158
1159 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001160 // C++ [expr.new]p20:
1161 // A declaration of a placement deallocation function matches the
1162 // declaration of a placement allocation function if it has the
1163 // same number of parameters and, after parameter transformations
1164 // (8.3.5), all parameter types except the first are
1165 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001166 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001167 // To perform this comparison, we compute the function type that
1168 // the deallocation function should have, and use that type both
1169 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001170 //
1171 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001172 QualType ExpectedFunctionType;
1173 {
1174 const FunctionProtoType *Proto
1175 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001176
Douglas Gregor6d908702010-02-26 05:06:18 +00001177 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001178 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001179 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1180 ArgTypes.push_back(Proto->getArgType(I));
1181
John McCalle23cf432010-12-14 08:05:40 +00001182 FunctionProtoType::ExtProtoInfo EPI;
1183 EPI.Variadic = Proto->isVariadic();
1184
Douglas Gregor6d908702010-02-26 05:06:18 +00001185 ExpectedFunctionType
1186 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001187 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001188 }
1189
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001190 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001191 DEnd = FoundDelete.end();
1192 D != DEnd; ++D) {
1193 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001195 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1196 // Perform template argument deduction to try to match the
1197 // expected function type.
1198 TemplateDeductionInfo Info(Context, StartLoc);
1199 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1200 continue;
1201 } else
1202 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1203
1204 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001205 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001206 }
1207 } else {
1208 // C++ [expr.new]p20:
1209 // [...] Any non-placement deallocation function matches a
1210 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001211 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001212 DEnd = FoundDelete.end();
1213 D != DEnd; ++D) {
1214 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1215 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001216 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001217 }
1218 }
1219
1220 // C++ [expr.new]p20:
1221 // [...] If the lookup finds a single matching deallocation
1222 // function, that function will be called; otherwise, no
1223 // deallocation function will be called.
1224 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001225 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001226
1227 // C++0x [expr.new]p20:
1228 // If the lookup finds the two-parameter form of a usual
1229 // deallocation function (3.7.4.2) and that function, considered
1230 // as a placement deallocation function, would have been
1231 // selected as a match for the allocation function, the program
1232 // is ill-formed.
1233 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1234 isNonPlacementDeallocationFunction(OperatorDelete)) {
1235 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001236 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001237 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1238 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1239 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001240 } else {
1241 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001242 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001243 }
1244 }
1245
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001246 return false;
1247}
1248
Sebastian Redl7f662392008-12-04 22:20:51 +00001249/// FindAllocationOverload - Find an fitting overload for the allocation
1250/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001251bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1252 DeclarationName Name, Expr** Args,
1253 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001254 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001255 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1256 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001257 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001258 if (AllowMissing)
1259 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001260 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001261 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001262 }
1263
John McCall90c8c572010-03-18 08:19:33 +00001264 if (R.isAmbiguous())
1265 return true;
1266
1267 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001268
John McCall5769d612010-02-08 23:07:23 +00001269 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001270 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001271 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001272 // Even member operator new/delete are implicitly treated as
1273 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001274 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001275
John McCall9aa472c2010-03-19 07:35:19 +00001276 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1277 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001278 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1279 Candidates,
1280 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001281 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001282 }
1283
John McCall9aa472c2010-03-19 07:35:19 +00001284 FunctionDecl *Fn = cast<FunctionDecl>(D);
1285 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001286 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001287 }
1288
1289 // Do the resolution.
1290 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001291 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001292 case OR_Success: {
1293 // Got one!
1294 FunctionDecl *FnDecl = Best->Function;
1295 // The first argument is size_t, and the first parameter must be size_t,
1296 // too. This is checked on declaration and can be assumed. (It can't be
1297 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001298 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001299 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1300 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001301 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001302 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001303 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001304 FnDecl->getParamDecl(i)),
1305 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001306 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001307 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001308 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001309
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001310 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001311 }
1312 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001313 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001314 return false;
1315 }
1316
1317 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001318 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001319 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001320 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001321 return true;
1322
1323 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001324 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001325 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001326 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001327 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001328
1329 case OR_Deleted:
1330 Diag(StartLoc, diag::err_ovl_deleted_call)
1331 << Best->Function->isDeleted()
1332 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001333 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001334 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001335 }
1336 assert(false && "Unreachable, bad result from BestViableFunction");
1337 return true;
1338}
1339
1340
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001341/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1342/// delete. These are:
1343/// @code
1344/// void* operator new(std::size_t) throw(std::bad_alloc);
1345/// void* operator new[](std::size_t) throw(std::bad_alloc);
1346/// void operator delete(void *) throw();
1347/// void operator delete[](void *) throw();
1348/// @endcode
1349/// Note that the placement and nothrow forms of new are *not* implicitly
1350/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001351void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001352 if (GlobalNewDeleteDeclared)
1353 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001354
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001355 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001356 // [...] The following allocation and deallocation functions (18.4) are
1357 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001358 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001360 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001361 // void* operator new[](std::size_t) throw(std::bad_alloc);
1362 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001363 // void operator delete[](void*) throw();
1364 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001366 // new, operator new[], operator delete, operator delete[].
1367 //
1368 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1369 // "std" or "bad_alloc" as necessary to form the exception specification.
1370 // However, we do not make these implicit declarations visible to name
1371 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001372 if (!StdBadAlloc) {
1373 // The "std::bad_alloc" class has not yet been declared, so build it
1374 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001375 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1376 getOrCreateStdNamespace(),
1377 SourceLocation(),
1378 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001379 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001380 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001381 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001382
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001383 GlobalNewDeleteDeclared = true;
1384
1385 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1386 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001387 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001388
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001389 DeclareGlobalAllocationFunction(
1390 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001391 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001392 DeclareGlobalAllocationFunction(
1393 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001394 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001395 DeclareGlobalAllocationFunction(
1396 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1397 Context.VoidTy, VoidPtr);
1398 DeclareGlobalAllocationFunction(
1399 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1400 Context.VoidTy, VoidPtr);
1401}
1402
1403/// DeclareGlobalAllocationFunction - Declares a single implicit global
1404/// allocation function if it doesn't already exist.
1405void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001406 QualType Return, QualType Argument,
1407 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001408 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1409
1410 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001411 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001412 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001413 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001414 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001415 // Only look at non-template functions, as it is the predefined,
1416 // non-templated allocation function we are trying to declare here.
1417 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1418 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001419 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001420 Func->getParamDecl(0)->getType().getUnqualifiedType());
1421 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001422 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1423 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001424 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001425 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001426 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001427 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001428 }
1429 }
1430
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001431 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001432 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001433 = (Name.getCXXOverloadedOperator() == OO_New ||
1434 Name.getCXXOverloadedOperator() == OO_Array_New);
1435 if (HasBadAllocExceptionSpec) {
1436 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001437 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001438 }
John McCalle23cf432010-12-14 08:05:40 +00001439
1440 FunctionProtoType::ExtProtoInfo EPI;
1441 EPI.HasExceptionSpec = true;
1442 if (HasBadAllocExceptionSpec) {
1443 EPI.NumExceptions = 1;
1444 EPI.Exceptions = &BadAllocType;
1445 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001446
John McCalle23cf432010-12-14 08:05:40 +00001447 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001448 FunctionDecl *Alloc =
1449 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001450 FnType, /*TInfo=*/0, SC_None,
1451 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001452 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001453
Nuno Lopesfc284482009-12-16 16:59:22 +00001454 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001455 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001456
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001457 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001458 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001459 SC_None,
1460 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001461 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001462
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001463 // FIXME: Also add this declaration to the IdentifierResolver, but
1464 // make sure it is at the end of the chain to coincide with the
1465 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001466 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001467}
1468
Anders Carlsson78f74552009-11-15 18:45:20 +00001469bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1470 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001471 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001472 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001473 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001474 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001475
John McCalla24dc2e2009-11-17 02:14:36 +00001476 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001477 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001478
Chandler Carruth23893242010-06-28 00:30:51 +00001479 Found.suppressDiagnostics();
1480
John McCall046a7462010-08-04 00:31:26 +00001481 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001482 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1483 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001484 NamedDecl *ND = (*F)->getUnderlyingDecl();
1485
1486 // Ignore template operator delete members from the check for a usual
1487 // deallocation function.
1488 if (isa<FunctionTemplateDecl>(ND))
1489 continue;
1490
1491 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001492 Matches.push_back(F.getPair());
1493 }
1494
1495 // There's exactly one suitable operator; pick it.
1496 if (Matches.size() == 1) {
1497 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1498 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1499 Matches[0]);
1500 return false;
1501
1502 // We found multiple suitable operators; complain about the ambiguity.
1503 } else if (!Matches.empty()) {
1504 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1505 << Name << RD;
1506
1507 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1508 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1509 Diag((*F)->getUnderlyingDecl()->getLocation(),
1510 diag::note_member_declared_here) << Name;
1511 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001512 }
1513
1514 // We did find operator delete/operator delete[] declarations, but
1515 // none of them were suitable.
1516 if (!Found.empty()) {
1517 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1518 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001519
Anders Carlsson78f74552009-11-15 18:45:20 +00001520 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001521 F != FEnd; ++F)
1522 Diag((*F)->getUnderlyingDecl()->getLocation(),
1523 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001524
1525 return true;
1526 }
1527
1528 // Look for a global declaration.
1529 DeclareGlobalNewDelete();
1530 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001531
Anders Carlsson78f74552009-11-15 18:45:20 +00001532 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1533 Expr* DeallocArgs[1];
1534 DeallocArgs[0] = &Null;
1535 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1536 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1537 Operator))
1538 return true;
1539
1540 assert(Operator && "Did not find a deallocation function!");
1541 return false;
1542}
1543
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001544/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1545/// @code ::delete ptr; @endcode
1546/// or
1547/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001548ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001549Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001550 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001551 // C++ [expr.delete]p1:
1552 // The operand shall have a pointer type, or a class type having a single
1553 // conversion function to a pointer type. The result has type void.
1554 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001555 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1556
Anders Carlssond67c4c32009-08-16 20:29:29 +00001557 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001558 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001559 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Sebastian Redl28507842009-02-26 14:39:58 +00001561 if (!Ex->isTypeDependent()) {
1562 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001563
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001564 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001565 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001566 PDiag(diag::err_delete_incomplete_class_type)))
1567 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001568
John McCall32daa422010-03-31 01:36:47 +00001569 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1570
Fariborz Jahanian53462782009-09-11 21:44:33 +00001571 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001572 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001573 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001574 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001575 NamedDecl *D = I.getDecl();
1576 if (isa<UsingShadowDecl>(D))
1577 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1578
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001579 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001580 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001581 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001582
John McCall32daa422010-03-31 01:36:47 +00001583 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001584
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001585 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1586 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001587 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001588 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001589 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001590 if (ObjectPtrConversions.size() == 1) {
1591 // We have a single conversion to a pointer-to-object type. Perform
1592 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001593 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001594 if (!PerformImplicitConversion(Ex,
1595 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001596 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001597 Type = Ex->getType();
1598 }
1599 }
1600 else if (ObjectPtrConversions.size() > 1) {
1601 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1602 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001603 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1604 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001605 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001606 }
Sebastian Redl28507842009-02-26 14:39:58 +00001607 }
1608
Sebastian Redlf53597f2009-03-15 17:47:39 +00001609 if (!Type->isPointerType())
1610 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1611 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001612
Ted Kremenek6217b802009-07-29 21:53:49 +00001613 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001614 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001616 // effectively bans deletion of "void*". However, most compilers support
1617 // this, so we treat it as a warning unless we're in a SFINAE context.
1618 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1619 << Type << Ex->getSourceRange();
1620 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001621 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1622 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001623 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001624 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001625 PDiag(diag::warn_delete_incomplete)
1626 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001627 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001628
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001629 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630 // [Note: a pointer to a const type can be the operand of a
1631 // delete-expression; it is not necessary to cast away the constness
1632 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001633 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001634 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001635 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001636
1637 if (Pointee->isArrayType() && !ArrayForm) {
1638 Diag(StartLoc, diag::warn_delete_array_type)
1639 << Type << Ex->getSourceRange()
1640 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1641 ArrayForm = true;
1642 }
1643
Anders Carlssond67c4c32009-08-16 20:29:29 +00001644 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1645 ArrayForm ? OO_Array_Delete : OO_Delete);
1646
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001647 QualType PointeeElem = Context.getBaseElementType(Pointee);
1648 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001649 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1650
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001651 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001652 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001653 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001654
John McCall6ec278d2011-01-27 09:37:56 +00001655 // If we're allocating an array of records, check whether the
1656 // usual operator delete[] has a size_t parameter.
1657 if (ArrayForm) {
1658 // If the user specifically asked to use the global allocator,
1659 // we'll need to do the lookup into the class.
1660 if (UseGlobal)
1661 UsualArrayDeleteWantsSize =
1662 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1663
1664 // Otherwise, the usual operator delete[] should be the
1665 // function we just found.
1666 else if (isa<CXXMethodDecl>(OperatorDelete))
1667 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1668 }
1669
Anders Carlsson78f74552009-11-15 18:45:20 +00001670 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001671 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001672 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001673 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001674 DiagnoseUseOfDecl(Dtor, StartLoc);
1675 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001676 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677
Anders Carlssond67c4c32009-08-16 20:29:29 +00001678 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001679 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001680 DeclareGlobalNewDelete();
1681 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001682 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001683 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001684 OperatorDelete))
1685 return ExprError();
1686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
John McCall9c82afc2010-04-20 02:18:25 +00001688 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001689
Sebastian Redl28507842009-02-26 14:39:58 +00001690 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001691 }
1692
Sebastian Redlf53597f2009-03-15 17:47:39 +00001693 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001694 ArrayFormAsWritten,
1695 UsualArrayDeleteWantsSize,
1696 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001697}
1698
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001699/// \brief Check the use of the given variable as a C++ condition in an if,
1700/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001701ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001702 SourceLocation StmtLoc,
1703 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001704 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001705
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001706 // C++ [stmt.select]p2:
1707 // The declarator shall not specify a function or an array.
1708 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001709 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001710 diag::err_invalid_use_of_function_type)
1711 << ConditionVar->getSourceRange());
1712 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001713 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001714 diag::err_invalid_use_of_array_type)
1715 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001716
Douglas Gregor586596f2010-05-06 17:25:47 +00001717 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001718 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001719 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001720 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001721 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001722 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001723
Douglas Gregor586596f2010-05-06 17:25:47 +00001724 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001725}
1726
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001727/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1728bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1729 // C++ 6.4p4:
1730 // The value of a condition that is an initialized declaration in a statement
1731 // other than a switch statement is the value of the declared variable
1732 // implicitly converted to type bool. If that conversion is ill-formed, the
1733 // program is ill-formed.
1734 // The value of a condition that is an expression is the value of the
1735 // expression, implicitly converted to bool.
1736 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001737 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001738}
Douglas Gregor77a52232008-09-12 00:47:35 +00001739
1740/// Helper function to determine whether this is the (deprecated) C++
1741/// conversion from a string literal to a pointer to non-const char or
1742/// non-const wchar_t (for narrow and wide string literals,
1743/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001744bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001745Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1746 // Look inside the implicit cast, if it exists.
1747 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1748 From = Cast->getSubExpr();
1749
1750 // A string literal (2.13.4) that is not a wide string literal can
1751 // be converted to an rvalue of type "pointer to char"; a wide
1752 // string literal can be converted to an rvalue of type "pointer
1753 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001754 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001755 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001756 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001757 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001758 // This conversion is considered only when there is an
1759 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001760 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001761 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1762 (!StrLit->isWide() &&
1763 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1764 ToPointeeType->getKind() == BuiltinType::Char_S))))
1765 return true;
1766 }
1767
1768 return false;
1769}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001770
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001771static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001772 SourceLocation CastLoc,
1773 QualType Ty,
1774 CastKind Kind,
1775 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001776 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001777 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001778 switch (Kind) {
1779 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001780 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001781 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782
Douglas Gregorba70ab62010-04-16 22:17:36 +00001783 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001784 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001785 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001786 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787
1788 ExprResult Result =
1789 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001790 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001791 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1792 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001793 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001794 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795
Douglas Gregorba70ab62010-04-16 22:17:36 +00001796 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1797 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798
John McCall2de56d12010-08-25 11:45:40 +00001799 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001800 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001801
Douglas Gregorba70ab62010-04-16 22:17:36 +00001802 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001803 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001804 if (Result.isInvalid())
1805 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001807 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001808 }
1809 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001810}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001811
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001812/// PerformImplicitConversion - Perform an implicit conversion of the
1813/// expression From to the type ToType using the pre-computed implicit
1814/// conversion sequence ICS. Returns true if there was an error, false
1815/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001816/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001817/// used in the error message.
1818bool
1819Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1820 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001821 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001822 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001823 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001824 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001825 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001826 return true;
1827 break;
1828
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001829 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001830
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001831 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001832 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001833 QualType BeforeToType;
1834 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001835 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001836
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001837 // If the user-defined conversion is specified by a conversion function,
1838 // the initial standard conversion sequence converts the source type to
1839 // the implicit object parameter of the conversion function.
1840 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001841 } else {
1842 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001843 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001844 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001845 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001846 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001847 // initial standard conversion sequence converts the source type to the
1848 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001849 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1850 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001851 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001852 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001853 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001854 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001855 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001856 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001857 return true;
1858 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001859
1860 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001861 = BuildCXXCastArgument(*this,
1862 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001863 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001864 CastKind, cast<CXXMethodDecl>(FD),
1865 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001866 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001867
1868 if (CastArg.isInvalid())
1869 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001870
1871 From = CastArg.takeAs<Expr>();
1872
Eli Friedmand8889622009-11-27 04:41:50 +00001873 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001874 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001875 }
John McCall1d318332010-01-12 00:44:57 +00001876
1877 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001878 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001879 PDiag(diag::err_typecheck_ambiguous_condition)
1880 << From->getSourceRange());
1881 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001882
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001883 case ImplicitConversionSequence::EllipsisConversion:
1884 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001885 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001886
1887 case ImplicitConversionSequence::BadConversion:
1888 return true;
1889 }
1890
1891 // Everything went well.
1892 return false;
1893}
1894
1895/// PerformImplicitConversion - Perform an implicit conversion of the
1896/// expression From to the type ToType by following the standard
1897/// conversion sequence SCS. Returns true if there was an error, false
1898/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001899/// expression. Flavor is the context in which we're performing this
1900/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001901bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001902Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001903 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001904 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001905 // Overall FIXME: we are recomputing too many types here and doing far too
1906 // much extra work. What this means is that we need to keep track of more
1907 // information that is computed when we try the implicit conversion initially,
1908 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001909 QualType FromType = From->getType();
1910
Douglas Gregor225c41e2008-11-03 19:09:14 +00001911 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001912 // FIXME: When can ToType be a reference type?
1913 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001914 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001915 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001916 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001917 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001918 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001919 ConstructorArgs))
1920 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001921 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001922 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1923 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001924 move_arg(ConstructorArgs),
1925 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001926 CXXConstructExpr::CK_Complete,
1927 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001928 if (FromResult.isInvalid())
1929 return true;
1930 From = FromResult.takeAs<Expr>();
1931 return false;
1932 }
John McCall60d7b3a2010-08-24 06:29:42 +00001933 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001934 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1935 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001936 MultiExprArg(*this, &From, 1),
1937 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001938 CXXConstructExpr::CK_Complete,
1939 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001941 if (FromResult.isInvalid())
1942 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001944 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001945 return false;
1946 }
1947
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001948 // Resolve overloaded function references.
1949 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1950 DeclAccessPair Found;
1951 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1952 true, Found);
1953 if (!Fn)
1954 return true;
1955
1956 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1957 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001958
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001959 From = FixOverloadedFunctionReference(From, Found, Fn);
1960 FromType = From->getType();
1961 }
1962
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001963 // Perform the first implicit conversion.
1964 switch (SCS.First) {
1965 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001966 // Nothing to do.
1967 break;
1968
John McCallf6a16482010-12-04 03:47:34 +00001969 case ICK_Lvalue_To_Rvalue:
1970 // Should this get its own ICK?
1971 if (From->getObjectKind() == OK_ObjCProperty) {
1972 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00001973 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00001974 }
1975
1976 FromType = FromType.getUnqualifiedType();
1977 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
1978 From, 0, VK_RValue);
1979 break;
1980
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001981 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001982 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001983 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001984 break;
1985
1986 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001987 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001988 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001989 break;
1990
1991 default:
1992 assert(false && "Improper first standard conversion");
1993 break;
1994 }
1995
1996 // Perform the second implicit conversion
1997 switch (SCS.Second) {
1998 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001999 // If both sides are functions (or pointers/references to them), there could
2000 // be incompatible exception declarations.
2001 if (CheckExceptionSpecCompatibility(From, ToType))
2002 return true;
2003 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002004 break;
2005
Douglas Gregor43c79c22009-12-09 00:47:37 +00002006 case ICK_NoReturn_Adjustment:
2007 // If both sides are functions (or pointers/references to them), there could
2008 // be incompatible exception declarations.
2009 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002010 return true;
2011
John McCalle6a365d2010-12-19 02:44:49 +00002012 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002013 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002014
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002015 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002016 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002017 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002018 break;
2019
2020 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002021 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002022 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002023 break;
2024
2025 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002026 case ICK_Complex_Conversion: {
2027 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2028 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2029 CastKind CK;
2030 if (FromEl->isRealFloatingType()) {
2031 if (ToEl->isRealFloatingType())
2032 CK = CK_FloatingComplexCast;
2033 else
2034 CK = CK_FloatingComplexToIntegralComplex;
2035 } else if (ToEl->isRealFloatingType()) {
2036 CK = CK_IntegralComplexToFloatingComplex;
2037 } else {
2038 CK = CK_IntegralComplexCast;
2039 }
2040 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002041 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002042 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002043
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002044 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002045 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002046 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002047 else
John McCall2de56d12010-08-25 11:45:40 +00002048 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002049 break;
2050
Douglas Gregorf9201e02009-02-11 23:02:49 +00002051 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002052 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002053 break;
2054
Anders Carlsson61faec12009-09-12 04:46:44 +00002055 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002056 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002057 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002058 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002059 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002060 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002061 << From->getSourceRange();
2062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002063
John McCalldaa8e4e2010-11-15 09:13:47 +00002064 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002065 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002066 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002067 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002068 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002069 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002070 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002071
Anders Carlsson61faec12009-09-12 04:46:44 +00002072 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002073 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002074 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002075 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002076 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002077 if (CheckExceptionSpecCompatibility(From, ToType))
2078 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002079 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002080 break;
2081 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002082 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002083 CastKind Kind = CK_Invalid;
2084 switch (FromType->getScalarTypeKind()) {
2085 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2086 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2087 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2088 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2089 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2090 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2091 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2092 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002093
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002094 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002095 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002096 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002097
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002098 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002099 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002100 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002101 ToType.getNonReferenceType(),
2102 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002103 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002104 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002105 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002106 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002107
Sebastian Redl906082e2010-07-20 04:20:21 +00002108 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002109 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002110 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002111 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002112 }
2113
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002114 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002115 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002116 break;
2117
2118 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002119 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002120 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002121
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002122 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002123 // Case 1. x -> _Complex y
2124 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2125 QualType ElType = ToComplex->getElementType();
2126 bool isFloatingComplex = ElType->isRealFloatingType();
2127
2128 // x -> y
2129 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2130 // do nothing
2131 } else if (From->getType()->isRealFloatingType()) {
2132 ImpCastExprToType(From, ElType,
2133 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2134 } else {
2135 assert(From->getType()->isIntegerType());
2136 ImpCastExprToType(From, ElType,
2137 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2138 }
2139 // y -> _Complex y
2140 ImpCastExprToType(From, ToType,
2141 isFloatingComplex ? CK_FloatingRealToComplex
2142 : CK_IntegralRealToComplex);
2143
2144 // Case 2. _Complex x -> y
2145 } else {
2146 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2147 assert(FromComplex);
2148
2149 QualType ElType = FromComplex->getElementType();
2150 bool isFloatingComplex = ElType->isRealFloatingType();
2151
2152 // _Complex x -> x
2153 ImpCastExprToType(From, ElType,
2154 isFloatingComplex ? CK_FloatingComplexToReal
2155 : CK_IntegralComplexToReal);
2156
2157 // x -> y
2158 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2159 // do nothing
2160 } else if (ToType->isRealFloatingType()) {
2161 ImpCastExprToType(From, ToType,
2162 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2163 } else {
2164 assert(ToType->isIntegerType());
2165 ImpCastExprToType(From, ToType,
2166 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2167 }
2168 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002169 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002170
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002171 case ICK_Lvalue_To_Rvalue:
2172 case ICK_Array_To_Pointer:
2173 case ICK_Function_To_Pointer:
2174 case ICK_Qualification:
2175 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002176 assert(false && "Improper second standard conversion");
2177 break;
2178 }
2179
2180 switch (SCS.Third) {
2181 case ICK_Identity:
2182 // Nothing to do.
2183 break;
2184
Sebastian Redl906082e2010-07-20 04:20:21 +00002185 case ICK_Qualification: {
2186 // The qualification keeps the category of the inner expression, unless the
2187 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002188 ExprValueKind VK = ToType->isReferenceType() ?
2189 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002190 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002191 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002192
2193 if (SCS.DeprecatedStringLiteralToCharPtr)
2194 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2195 << ToType.getNonReferenceType();
2196
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002197 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002198 }
2199
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002200 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002201 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002202 break;
2203 }
2204
2205 return false;
2206}
2207
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002208ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002209 SourceLocation KWLoc,
2210 ParsedType Ty,
2211 SourceLocation RParen) {
2212 TypeSourceInfo *TSInfo;
2213 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002215 if (!TSInfo)
2216 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002217 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002218}
2219
Sebastian Redlf8aca862010-09-14 23:40:14 +00002220static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2221 SourceLocation KeyLoc) {
Douglas Gregora0506182011-01-27 20:35:44 +00002222 // FIXME: For many of these traits, we need a complete type before we can
2223 // check these properties.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002224 assert(!T->isDependentType() &&
2225 "Cannot evaluate traits for dependent types.");
2226 ASTContext &C = Self.Context;
2227 switch(UTT) {
2228 default: assert(false && "Unknown type trait or not implemented");
2229 case UTT_IsPOD: return T->isPODType();
2230 case UTT_IsLiteral: return T->isLiteralType();
2231 case UTT_IsClass: // Fallthrough
2232 case UTT_IsUnion:
2233 if (const RecordType *Record = T->getAs<RecordType>()) {
2234 bool Union = Record->getDecl()->isUnion();
2235 return UTT == UTT_IsUnion ? Union : !Union;
2236 }
2237 return false;
2238 case UTT_IsEnum: return T->isEnumeralType();
2239 case UTT_IsPolymorphic:
2240 if (const RecordType *Record = T->getAs<RecordType>()) {
2241 // Type traits are only parsed in C++, so we've got CXXRecords.
2242 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2243 }
2244 return false;
2245 case UTT_IsAbstract:
2246 if (const RecordType *RT = T->getAs<RecordType>())
2247 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2248 return false;
2249 case UTT_IsEmpty:
2250 if (const RecordType *Record = T->getAs<RecordType>()) {
2251 return !Record->getDecl()->isUnion()
2252 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2253 }
2254 return false;
2255 case UTT_HasTrivialConstructor:
2256 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2257 // If __is_pod (type) is true then the trait is true, else if type is
2258 // a cv class or union type (or array thereof) with a trivial default
2259 // constructor ([class.ctor]) then the trait is true, else it is false.
2260 if (T->isPODType())
2261 return true;
2262 if (const RecordType *RT =
2263 C.getBaseElementType(T)->getAs<RecordType>())
2264 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2265 return false;
2266 case UTT_HasTrivialCopy:
2267 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2268 // If __is_pod (type) is true or type is a reference type then
2269 // the trait is true, else if type is a cv class or union type
2270 // with a trivial copy constructor ([class.copy]) then the trait
2271 // is true, else it is false.
2272 if (T->isPODType() || T->isReferenceType())
2273 return true;
2274 if (const RecordType *RT = T->getAs<RecordType>())
2275 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2276 return false;
2277 case UTT_HasTrivialAssign:
2278 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2279 // If type is const qualified or is a reference type then the
2280 // trait is false. Otherwise if __is_pod (type) is true then the
2281 // trait is true, else if type is a cv class or union type with
2282 // a trivial copy assignment ([class.copy]) then the trait is
2283 // true, else it is false.
2284 // Note: the const and reference restrictions are interesting,
2285 // given that const and reference members don't prevent a class
2286 // from having a trivial copy assignment operator (but do cause
2287 // errors if the copy assignment operator is actually used, q.v.
2288 // [class.copy]p12).
2289
2290 if (C.getBaseElementType(T).isConstQualified())
2291 return false;
2292 if (T->isPODType())
2293 return true;
2294 if (const RecordType *RT = T->getAs<RecordType>())
2295 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2296 return false;
2297 case UTT_HasTrivialDestructor:
2298 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2299 // If __is_pod (type) is true or type is a reference type
2300 // then the trait is true, else if type is a cv class or union
2301 // type (or array thereof) with a trivial destructor
2302 // ([class.dtor]) then the trait is true, else it is
2303 // false.
2304 if (T->isPODType() || T->isReferenceType())
2305 return true;
2306 if (const RecordType *RT =
2307 C.getBaseElementType(T)->getAs<RecordType>())
2308 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2309 return false;
2310 // TODO: Propagate nothrowness for implicitly declared special members.
2311 case UTT_HasNothrowAssign:
2312 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2313 // If type is const qualified or is a reference type then the
2314 // trait is false. Otherwise if __has_trivial_assign (type)
2315 // is true then the trait is true, else if type is a cv class
2316 // or union type with copy assignment operators that are known
2317 // not to throw an exception then the trait is true, else it is
2318 // false.
2319 if (C.getBaseElementType(T).isConstQualified())
2320 return false;
2321 if (T->isReferenceType())
2322 return false;
2323 if (T->isPODType())
2324 return true;
2325 if (const RecordType *RT = T->getAs<RecordType>()) {
2326 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2327 if (RD->hasTrivialCopyAssignment())
2328 return true;
2329
2330 bool FoundAssign = false;
2331 bool AllNoThrow = true;
2332 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002333 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2334 Sema::LookupOrdinaryName);
2335 if (Self.LookupQualifiedName(Res, RD)) {
2336 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2337 Op != OpEnd; ++Op) {
2338 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2339 if (Operator->isCopyAssignmentOperator()) {
2340 FoundAssign = true;
2341 const FunctionProtoType *CPT
2342 = Operator->getType()->getAs<FunctionProtoType>();
2343 if (!CPT->hasEmptyExceptionSpec()) {
2344 AllNoThrow = false;
2345 break;
2346 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002347 }
2348 }
2349 }
2350
2351 return FoundAssign && AllNoThrow;
2352 }
2353 return false;
2354 case UTT_HasNothrowCopy:
2355 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2356 // If __has_trivial_copy (type) is true then the trait is true, else
2357 // if type is a cv class or union type with copy constructors that are
2358 // known not to throw an exception then the trait is true, else it is
2359 // false.
2360 if (T->isPODType() || T->isReferenceType())
2361 return true;
2362 if (const RecordType *RT = T->getAs<RecordType>()) {
2363 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2364 if (RD->hasTrivialCopyConstructor())
2365 return true;
2366
2367 bool FoundConstructor = false;
2368 bool AllNoThrow = true;
2369 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002370 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002371 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002372 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002373 // A template constructor is never a copy constructor.
2374 // FIXME: However, it may actually be selected at the actual overload
2375 // resolution point.
2376 if (isa<FunctionTemplateDecl>(*Con))
2377 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002378 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2379 if (Constructor->isCopyConstructor(FoundTQs)) {
2380 FoundConstructor = true;
2381 const FunctionProtoType *CPT
2382 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002383 // TODO: check whether evaluating default arguments can throw.
2384 // For now, we'll be conservative and assume that they can throw.
2385 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002386 AllNoThrow = false;
2387 break;
2388 }
2389 }
2390 }
2391
2392 return FoundConstructor && AllNoThrow;
2393 }
2394 return false;
2395 case UTT_HasNothrowConstructor:
2396 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2397 // If __has_trivial_constructor (type) is true then the trait is
2398 // true, else if type is a cv class or union type (or array
2399 // thereof) with a default constructor that is known not to
2400 // throw an exception then the trait is true, else it is false.
2401 if (T->isPODType())
2402 return true;
2403 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2404 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2405 if (RD->hasTrivialConstructor())
2406 return true;
2407
Sebastian Redl751025d2010-09-13 22:02:47 +00002408 DeclContext::lookup_const_iterator Con, ConEnd;
2409 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2410 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002411 // FIXME: In C++0x, a constructor template can be a default constructor.
2412 if (isa<FunctionTemplateDecl>(*Con))
2413 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002414 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2415 if (Constructor->isDefaultConstructor()) {
2416 const FunctionProtoType *CPT
2417 = Constructor->getType()->getAs<FunctionProtoType>();
2418 // TODO: check whether evaluating default arguments can throw.
2419 // For now, we'll be conservative and assume that they can throw.
2420 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2421 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002422 }
2423 }
2424 return false;
2425 case UTT_HasVirtualDestructor:
2426 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2427 // If type is a class type with a virtual destructor ([class.dtor])
2428 // then the trait is true, else it is false.
2429 if (const RecordType *Record = T->getAs<RecordType>()) {
2430 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002431 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002432 return Destructor->isVirtual();
2433 }
2434 return false;
2435 }
2436}
2437
2438ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002439 SourceLocation KWLoc,
2440 TypeSourceInfo *TSInfo,
2441 SourceLocation RParen) {
2442 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002443
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002444 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2445 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002446 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002447 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002448 QualType E = T;
2449 if (T->isIncompleteArrayType())
2450 E = Context.getAsArrayType(T)->getElementType();
2451 if (!T->isVoidType() &&
2452 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002453 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002454 return ExprError();
2455 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002456
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002457 bool Value = false;
2458 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002459 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002460
2461 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002462 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002463}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002464
Francois Pichet6ad6f282010-12-07 00:08:36 +00002465ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2466 SourceLocation KWLoc,
2467 ParsedType LhsTy,
2468 ParsedType RhsTy,
2469 SourceLocation RParen) {
2470 TypeSourceInfo *LhsTSInfo;
2471 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2472 if (!LhsTSInfo)
2473 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2474
2475 TypeSourceInfo *RhsTSInfo;
2476 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2477 if (!RhsTSInfo)
2478 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2479
2480 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2481}
2482
2483static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2484 QualType LhsT, QualType RhsT,
2485 SourceLocation KeyLoc) {
2486 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2487 "Cannot evaluate traits for dependent types.");
2488
2489 switch(BTT) {
2490 case BTT_IsBaseOf:
2491 // C++0x [meta.rel]p2
2492 // Base is a base class of Derived without regard to cv-qualifiers or
2493 // Base and Derived are not unions and name the same class type without
2494 // regard to cv-qualifiers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002495 if (Self.IsDerivedFrom(RhsT, LhsT) ||
Francois Pichet6ad6f282010-12-07 00:08:36 +00002496 (!LhsT->isUnionType() && !RhsT->isUnionType()
2497 && LhsT->getAsCXXRecordDecl() == RhsT->getAsCXXRecordDecl()))
2498 return true;
2499
2500 return false;
Francois Pichetf1872372010-12-08 22:35:30 +00002501 case BTT_TypeCompatible:
2502 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2503 RhsT.getUnqualifiedType());
Douglas Gregor9f361132011-01-27 20:28:01 +00002504
2505 case BTT_IsConvertibleTo: {
2506 // C++0x [meta.rel]p4:
2507 // Given the following function prototype:
2508 //
2509 // template <class T>
2510 // typename add_rvalue_reference<T>::type create();
2511 //
2512 // the predicate condition for a template specialization
2513 // is_convertible<From, To> shall be satisfied if and only if
2514 // the return expression in the following code would be
2515 // well-formed, including any implicit conversions to the return
2516 // type of the function:
2517 //
2518 // To test() {
2519 // return create<From>();
2520 // }
2521 //
2522 // Access checking is performed as if in a context unrelated to To and
2523 // From. Only the validity of the immediate context of the expression
2524 // of the return-statement (including conversions to the return type)
2525 // is considered.
2526 //
2527 // We model the initialization as a copy-initialization of a temporary
2528 // of the appropriate type, which for this expression is identical to the
2529 // return statement (since NRVO doesn't apply).
2530 if (LhsT->isObjectType() || LhsT->isFunctionType())
2531 LhsT = Self.Context.getRValueReferenceType(LhsT);
2532
2533 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
2534 OpaqueValueExpr From(LhsT.getNonLValueExprType(Self.Context),
2535 Expr::getValueKindForType(LhsT));
2536 Expr *FromPtr = &From;
2537 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2538 SourceLocation()));
2539
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002540 // Perform the initialization within a SFINAE trap at translation unit
2541 // scope.
2542 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2543 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002544 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2545 if (Init.getKind() == InitializationSequence::FailedSequence)
2546 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002547
Douglas Gregor9f361132011-01-27 20:28:01 +00002548 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2549 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2550 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002551 }
2552 llvm_unreachable("Unknown type trait or not implemented");
2553}
2554
2555ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2556 SourceLocation KWLoc,
2557 TypeSourceInfo *LhsTSInfo,
2558 TypeSourceInfo *RhsTSInfo,
2559 SourceLocation RParen) {
2560 QualType LhsT = LhsTSInfo->getType();
2561 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002562
Francois Pichet6ad6f282010-12-07 00:08:36 +00002563 if (BTT == BTT_IsBaseOf) {
2564 // C++0x [meta.rel]p2
2565 // If Base and Derived are class types and are different types
2566 // (ignoring possible cv-qualifiers) then Derived shall be a complete
2567 // type. []
2568 CXXRecordDecl *LhsDecl = LhsT->getAsCXXRecordDecl();
2569 CXXRecordDecl *RhsDecl = RhsT->getAsCXXRecordDecl();
2570 if (!LhsT->isDependentType() && !RhsT->isDependentType() &&
2571 LhsDecl && RhsDecl && LhsT != RhsT &&
2572 RequireCompleteType(KWLoc, RhsT,
2573 diag::err_incomplete_type_used_in_type_trait_expr))
2574 return ExprError();
Francois Pichetf1872372010-12-08 22:35:30 +00002575 } else if (BTT == BTT_TypeCompatible) {
2576 if (getLangOptions().CPlusPlus) {
2577 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2578 << SourceRange(KWLoc, RParen);
2579 return ExprError();
2580 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002581 }
2582
2583 bool Value = false;
2584 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2585 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2586
Francois Pichetf1872372010-12-08 22:35:30 +00002587 // Select trait result type.
2588 QualType ResultType;
2589 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002590 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2591 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002592 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002593 }
2594
Francois Pichet6ad6f282010-12-07 00:08:36 +00002595 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2596 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002597 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002598}
2599
John McCallf89e55a2010-11-18 06:31:45 +00002600QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2601 ExprValueKind &VK,
2602 SourceLocation Loc,
2603 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002604 const char *OpSpelling = isIndirect ? "->*" : ".*";
2605 // C++ 5.5p2
2606 // The binary operator .* [p3: ->*] binds its second operand, which shall
2607 // be of type "pointer to member of T" (where T is a completely-defined
2608 // class type) [...]
2609 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002610 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002611 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002612 Diag(Loc, diag::err_bad_memptr_rhs)
2613 << OpSpelling << RType << rex->getSourceRange();
2614 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002615 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002616
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002617 QualType Class(MemPtr->getClass(), 0);
2618
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002619 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2620 // member pointer points must be completely-defined. However, there is no
2621 // reason for this semantic distinction, and the rule is not enforced by
2622 // other compilers. Therefore, we do not check this property, as it is
2623 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002624
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002625 // C++ 5.5p2
2626 // [...] to its first operand, which shall be of class T or of a class of
2627 // which T is an unambiguous and accessible base class. [p3: a pointer to
2628 // such a class]
2629 QualType LType = lex->getType();
2630 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002631 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002632 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002633 else {
2634 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002635 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002636 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002637 return QualType();
2638 }
2639 }
2640
Douglas Gregora4923eb2009-11-16 21:35:15 +00002641 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002642 // If we want to check the hierarchy, we need a complete type.
2643 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2644 << OpSpelling << (int)isIndirect)) {
2645 return QualType();
2646 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002647 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002648 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002649 // FIXME: Would it be useful to print full ambiguity paths, or is that
2650 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002651 if (!IsDerivedFrom(LType, Class, Paths) ||
2652 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2653 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002654 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002655 return QualType();
2656 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002657 // Cast LHS to type of use.
2658 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002659 ExprValueKind VK =
2660 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002661
John McCallf871d0c2010-08-07 06:22:56 +00002662 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002663 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002664 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002665 }
2666
Douglas Gregored8abf12010-07-08 06:14:04 +00002667 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002668 // Diagnose use of pointer-to-member type which when used as
2669 // the functional cast in a pointer-to-member expression.
2670 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2671 return QualType();
2672 }
John McCallf89e55a2010-11-18 06:31:45 +00002673
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002674 // C++ 5.5p2
2675 // The result is an object or a function of the type specified by the
2676 // second operand.
2677 // The cv qualifiers are the union of those in the pointer and the left side,
2678 // in accordance with 5.5p5 and 5.2.5.
2679 // FIXME: This returns a dereferenced member function pointer as a normal
2680 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002681 // calling them. There's also a GCC extension to get a function pointer to the
2682 // thing, which is another complication, because this type - unlike the type
2683 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002684 // argument.
2685 // We probably need a "MemberFunctionClosureType" or something like that.
2686 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002687 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002688
Douglas Gregor6b4df912011-01-26 16:40:18 +00002689 // C++0x [expr.mptr.oper]p6:
2690 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002691 // ill-formed if the second operand is a pointer to member function with
2692 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2693 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002694 // is a pointer to member function with ref-qualifier &&.
2695 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2696 switch (Proto->getRefQualifier()) {
2697 case RQ_None:
2698 // Do nothing
2699 break;
2700
2701 case RQ_LValue:
2702 if (!isIndirect && !lex->Classify(Context).isLValue())
2703 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2704 << RType << 1 << lex->getSourceRange();
2705 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002706
Douglas Gregor6b4df912011-01-26 16:40:18 +00002707 case RQ_RValue:
2708 if (isIndirect || !lex->Classify(Context).isRValue())
2709 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2710 << RType << 0 << lex->getSourceRange();
2711 break;
2712 }
2713 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002714
John McCallf89e55a2010-11-18 06:31:45 +00002715 // C++ [expr.mptr.oper]p6:
2716 // The result of a .* expression whose second operand is a pointer
2717 // to a data member is of the same value category as its
2718 // first operand. The result of a .* expression whose second
2719 // operand is a pointer to a member function is a prvalue. The
2720 // result of an ->* expression is an lvalue if its second operand
2721 // is a pointer to data member and a prvalue otherwise.
2722 if (Result->isFunctionType())
2723 VK = VK_RValue;
2724 else if (isIndirect)
2725 VK = VK_LValue;
2726 else
2727 VK = lex->getValueKind();
2728
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002729 return Result;
2730}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002731
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002732/// \brief Try to convert a type to another according to C++0x 5.16p3.
2733///
2734/// This is part of the parameter validation for the ? operator. If either
2735/// value operand is a class type, the two operands are attempted to be
2736/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002737/// It returns true if the program is ill-formed and has already been diagnosed
2738/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002739static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2740 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002741 bool &HaveConversion,
2742 QualType &ToType) {
2743 HaveConversion = false;
2744 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002745
2746 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002747 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002748 // C++0x 5.16p3
2749 // The process for determining whether an operand expression E1 of type T1
2750 // can be converted to match an operand expression E2 of type T2 is defined
2751 // as follows:
2752 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002753 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002754 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002755 // E1 can be converted to match E2 if E1 can be implicitly converted to
2756 // type "lvalue reference to T2", subject to the constraint that in the
2757 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002758 QualType T = Self.Context.getLValueReferenceType(ToType);
2759 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002760
Douglas Gregorb70cf442010-03-26 20:14:36 +00002761 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2762 if (InitSeq.isDirectReferenceBinding()) {
2763 ToType = T;
2764 HaveConversion = true;
2765 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002766 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002767
Douglas Gregorb70cf442010-03-26 20:14:36 +00002768 if (InitSeq.isAmbiguous())
2769 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002770 }
John McCallb1bdc622010-02-25 01:37:24 +00002771
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002772 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2773 // -- if E1 and E2 have class type, and the underlying class types are
2774 // the same or one is a base class of the other:
2775 QualType FTy = From->getType();
2776 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002777 const RecordType *FRec = FTy->getAs<RecordType>();
2778 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002779 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002780 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002781 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002782 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002783 // E1 can be converted to match E2 if the class of T2 is the
2784 // same type as, or a base class of, the class of T1, and
2785 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002786 if (FRec == TRec || FDerivedFromT) {
2787 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002788 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2789 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2790 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2791 HaveConversion = true;
2792 return false;
2793 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002794
Douglas Gregorb70cf442010-03-26 20:14:36 +00002795 if (InitSeq.isAmbiguous())
2796 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002797 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002798 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002799
Douglas Gregorb70cf442010-03-26 20:14:36 +00002800 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002801 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002802
Douglas Gregorb70cf442010-03-26 20:14:36 +00002803 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2804 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002806 // an rvalue).
2807 //
2808 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2809 // to the array-to-pointer or function-to-pointer conversions.
2810 if (!TTy->getAs<TagType>())
2811 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002812
Douglas Gregorb70cf442010-03-26 20:14:36 +00002813 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2814 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002815 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002816 ToType = TTy;
2817 if (InitSeq.isAmbiguous())
2818 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2819
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002820 return false;
2821}
2822
2823/// \brief Try to find a common type for two according to C++0x 5.16p5.
2824///
2825/// This is part of the parameter validation for the ? operator. If either
2826/// value operand is a class type, overload resolution is used to find a
2827/// conversion to a common type.
2828static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2829 SourceLocation Loc) {
2830 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002831 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002832 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002833
2834 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002835 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002836 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002837 // We found a match. Perform the conversions on the arguments and move on.
2838 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002839 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002840 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002841 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002842 break;
2843 return false;
2844
Douglas Gregor20093b42009-12-09 23:02:17 +00002845 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002846 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2847 << LHS->getType() << RHS->getType()
2848 << LHS->getSourceRange() << RHS->getSourceRange();
2849 return true;
2850
Douglas Gregor20093b42009-12-09 23:02:17 +00002851 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002852 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2853 << LHS->getType() << RHS->getType()
2854 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002855 // FIXME: Print the possible common types by printing the return types of
2856 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002857 break;
2858
Douglas Gregor20093b42009-12-09 23:02:17 +00002859 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002860 assert(false && "Conditional operator has only built-in overloads");
2861 break;
2862 }
2863 return true;
2864}
2865
Sebastian Redl76458502009-04-17 16:30:52 +00002866/// \brief Perform an "extended" implicit conversion as returned by
2867/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002868static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2869 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2870 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2871 SourceLocation());
2872 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002873 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002874 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002875 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876
Douglas Gregorb70cf442010-03-26 20:14:36 +00002877 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002878 return false;
2879}
2880
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002881/// \brief Check the operands of ?: under C++ semantics.
2882///
2883/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2884/// extension. In this case, LHS == Cond. (But they're not aliases.)
2885QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallf89e55a2010-11-18 06:31:45 +00002886 Expr *&SAVE, ExprValueKind &VK,
John McCall09431682010-11-18 19:01:18 +00002887 ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002888 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002889 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2890 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002891
2892 // C++0x 5.16p1
2893 // The first expression is contextually converted to bool.
2894 if (!Cond->isTypeDependent()) {
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00002895 if (SAVE && Cond->getType()->isArrayType()) {
2896 QualType CondTy = Cond->getType();
2897 CondTy = Context.getArrayDecayedType(CondTy);
2898 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2899 SAVE = LHS = Cond;
2900 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002901 if (CheckCXXBooleanCondition(Cond))
2902 return QualType();
2903 }
2904
John McCallf89e55a2010-11-18 06:31:45 +00002905 // Assume r-value.
2906 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002907 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002908
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002909 // Either of the arguments dependent?
2910 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2911 return Context.DependentTy;
2912
2913 // C++0x 5.16p2
2914 // If either the second or the third operand has type (cv) void, ...
2915 QualType LTy = LHS->getType();
2916 QualType RTy = RHS->getType();
2917 bool LVoid = LTy->isVoidType();
2918 bool RVoid = RTy->isVoidType();
2919 if (LVoid || RVoid) {
2920 // ... then the [l2r] conversions are performed on the second and third
2921 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002922 DefaultFunctionArrayLvalueConversion(LHS);
2923 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002924 LTy = LHS->getType();
2925 RTy = RHS->getType();
2926
2927 // ... and one of the following shall hold:
2928 // -- The second or the third operand (but not both) is a throw-
2929 // expression; the result is of the type of the other and is an rvalue.
2930 bool LThrow = isa<CXXThrowExpr>(LHS);
2931 bool RThrow = isa<CXXThrowExpr>(RHS);
2932 if (LThrow && !RThrow)
2933 return RTy;
2934 if (RThrow && !LThrow)
2935 return LTy;
2936
2937 // -- Both the second and third operands have type void; the result is of
2938 // type void and is an rvalue.
2939 if (LVoid && RVoid)
2940 return Context.VoidTy;
2941
2942 // Neither holds, error.
2943 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2944 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2945 << LHS->getSourceRange() << RHS->getSourceRange();
2946 return QualType();
2947 }
2948
2949 // Neither is void.
2950
2951 // C++0x 5.16p3
2952 // Otherwise, if the second and third operand have different types, and
2953 // either has (cv) class type, and attempt is made to convert each of those
2954 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002955 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002956 (LTy->isRecordType() || RTy->isRecordType())) {
2957 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2958 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002959 QualType L2RType, R2LType;
2960 bool HaveL2R, HaveR2L;
2961 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002962 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002963 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002964 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002965
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002966 // If both can be converted, [...] the program is ill-formed.
2967 if (HaveL2R && HaveR2L) {
2968 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2969 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2970 return QualType();
2971 }
2972
2973 // If exactly one conversion is possible, that conversion is applied to
2974 // the chosen operand and the converted operands are used in place of the
2975 // original operands for the remainder of this section.
2976 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002977 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002978 return QualType();
2979 LTy = LHS->getType();
2980 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002981 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002982 return QualType();
2983 RTy = RHS->getType();
2984 }
2985 }
2986
2987 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00002988 // If the second and third operands are glvalues of the same value
2989 // category and have the same type, the result is of that type and
2990 // value category and it is a bit-field if the second or the third
2991 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00002992 // We only extend this to bitfields, not to the crazy other kinds of
2993 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002994 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00002995 if (Same &&
2996 LHS->getValueKind() != VK_RValue &&
2997 LHS->getValueKind() == RHS->getValueKind() &&
John McCall09431682010-11-18 19:01:18 +00002998 (LHS->getObjectKind() == OK_Ordinary ||
2999 LHS->getObjectKind() == OK_BitField) &&
3000 (RHS->getObjectKind() == OK_Ordinary ||
3001 RHS->getObjectKind() == OK_BitField)) {
John McCallf89e55a2010-11-18 06:31:45 +00003002 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00003003 if (LHS->getObjectKind() == OK_BitField ||
3004 RHS->getObjectKind() == OK_BitField)
3005 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003006 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003007 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003008
3009 // C++0x 5.16p5
3010 // Otherwise, the result is an rvalue. If the second and third operands
3011 // do not have the same type, and either has (cv) class type, ...
3012 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3013 // ... overload resolution is used to determine the conversions (if any)
3014 // to be applied to the operands. If the overload resolution fails, the
3015 // program is ill-formed.
3016 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3017 return QualType();
3018 }
3019
3020 // C++0x 5.16p6
3021 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3022 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00003023 DefaultFunctionArrayLvalueConversion(LHS);
3024 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003025 LTy = LHS->getType();
3026 RTy = RHS->getType();
3027
3028 // After those conversions, one of the following shall hold:
3029 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003030 // is of that type. If the operands have class type, the result
3031 // is a prvalue temporary of the result type, which is
3032 // copy-initialized from either the second operand or the third
3033 // operand depending on the value of the first operand.
3034 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3035 if (LTy->isRecordType()) {
3036 // The operands have class type. Make a temporary copy.
3037 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003038 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3039 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003040 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003041 if (LHSCopy.isInvalid())
3042 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003043
3044 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3045 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003046 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003047 if (RHSCopy.isInvalid())
3048 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003049
Douglas Gregorb65a4582010-05-19 23:40:50 +00003050 LHS = LHSCopy.takeAs<Expr>();
3051 RHS = RHSCopy.takeAs<Expr>();
3052 }
3053
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003054 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003055 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003056
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003057 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003058 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003059 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3060
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003061 // -- The second and third operands have arithmetic or enumeration type;
3062 // the usual arithmetic conversions are performed to bring them to a
3063 // common type, and the result is of that type.
3064 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3065 UsualArithmeticConversions(LHS, RHS);
3066 return LHS->getType();
3067 }
3068
3069 // -- The second and third operands have pointer type, or one has pointer
3070 // type and the other is a null pointer constant; pointer conversions
3071 // and qualification conversions are performed to bring them to their
3072 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003073 // -- The second and third operands have pointer to member type, or one has
3074 // pointer to member type and the other is a null pointer constant;
3075 // pointer to member conversions and qualification conversions are
3076 // performed to bring them to a common type, whose cv-qualification
3077 // shall match the cv-qualification of either the second or the third
3078 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003079 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003080 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003081 isSFINAEContext()? 0 : &NonStandardCompositeType);
3082 if (!Composite.isNull()) {
3083 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003084 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003085 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3086 << LTy << RTy << Composite
3087 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003088
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003089 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003090 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003091
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003092 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003093 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3094 if (!Composite.isNull())
3095 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003096
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003097 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3098 << LHS->getType() << RHS->getType()
3099 << LHS->getSourceRange() << RHS->getSourceRange();
3100 return QualType();
3101}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003102
3103/// \brief Find a merged pointer type and convert the two expressions to it.
3104///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003105/// This finds the composite pointer type (or member pointer type) for @p E1
3106/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3107/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003108/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003109///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003110/// \param Loc The location of the operator requiring these two expressions to
3111/// be converted to the composite pointer type.
3112///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003113/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3114/// a non-standard (but still sane) composite type to which both expressions
3115/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3116/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003118 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003119 bool *NonStandardCompositeType) {
3120 if (NonStandardCompositeType)
3121 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003123 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3124 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003125
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003126 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3127 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003128 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003129
3130 // C++0x 5.9p2
3131 // Pointer conversions and qualification conversions are performed on
3132 // pointer operands to bring them to their composite pointer type. If
3133 // one operand is a null pointer constant, the composite pointer type is
3134 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003135 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003136 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003137 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003138 else
John McCall404cd162010-11-13 01:35:44 +00003139 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003140 return T2;
3141 }
Douglas Gregorce940492009-09-25 04:25:58 +00003142 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003143 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003144 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003145 else
John McCall404cd162010-11-13 01:35:44 +00003146 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003147 return T1;
3148 }
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Douglas Gregor20b3e992009-08-24 17:42:35 +00003150 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003151 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3152 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003153 return QualType();
3154
3155 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3156 // the other has type "pointer to cv2 T" and the composite pointer type is
3157 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3158 // Otherwise, the composite pointer type is a pointer type similar to the
3159 // type of one of the operands, with a cv-qualification signature that is
3160 // the union of the cv-qualification signatures of the operand types.
3161 // In practice, the first part here is redundant; it's subsumed by the second.
3162 // What we do here is, we build the two possible composite types, and try the
3163 // conversions in both directions. If only one works, or if the two composite
3164 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003165 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003166 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3167 QualifierVector QualifierUnion;
3168 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3169 ContainingClassVector;
3170 ContainingClassVector MemberOfClass;
3171 QualType Composite1 = Context.getCanonicalType(T1),
3172 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003173 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003174 do {
3175 const PointerType *Ptr1, *Ptr2;
3176 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3177 (Ptr2 = Composite2->getAs<PointerType>())) {
3178 Composite1 = Ptr1->getPointeeType();
3179 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003181 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003182 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003183 if (NonStandardCompositeType &&
3184 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3185 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003186
Douglas Gregor20b3e992009-08-24 17:42:35 +00003187 QualifierUnion.push_back(
3188 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3189 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3190 continue;
3191 }
Mike Stump1eb44332009-09-09 15:08:12 +00003192
Douglas Gregor20b3e992009-08-24 17:42:35 +00003193 const MemberPointerType *MemPtr1, *MemPtr2;
3194 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3195 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3196 Composite1 = MemPtr1->getPointeeType();
3197 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003198
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003199 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003200 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003201 if (NonStandardCompositeType &&
3202 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3203 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003204
Douglas Gregor20b3e992009-08-24 17:42:35 +00003205 QualifierUnion.push_back(
3206 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3207 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3208 MemPtr2->getClass()));
3209 continue;
3210 }
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Douglas Gregor20b3e992009-08-24 17:42:35 +00003212 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003213
Douglas Gregor20b3e992009-08-24 17:42:35 +00003214 // Cannot unwrap any more types.
3215 break;
3216 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003217
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003218 if (NeedConstBefore && NonStandardCompositeType) {
3219 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003221 // requirements of C++ [conv.qual]p4 bullet 3.
3222 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3223 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3224 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3225 *NonStandardCompositeType = true;
3226 }
3227 }
3228 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229
Douglas Gregor20b3e992009-08-24 17:42:35 +00003230 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003231 ContainingClassVector::reverse_iterator MOC
3232 = MemberOfClass.rbegin();
3233 for (QualifierVector::reverse_iterator
3234 I = QualifierUnion.rbegin(),
3235 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003236 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003237 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003238 if (MOC->first && MOC->second) {
3239 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003240 Composite1 = Context.getMemberPointerType(
3241 Context.getQualifiedType(Composite1, Quals),
3242 MOC->first);
3243 Composite2 = Context.getMemberPointerType(
3244 Context.getQualifiedType(Composite2, Quals),
3245 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003246 } else {
3247 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003248 Composite1
3249 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3250 Composite2
3251 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003252 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003253 }
3254
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003255 // Try to convert to the first composite pointer type.
3256 InitializedEntity Entity1
3257 = InitializedEntity::InitializeTemporary(Composite1);
3258 InitializationKind Kind
3259 = InitializationKind::CreateCopy(Loc, SourceLocation());
3260 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3261 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003263 if (E1ToC1 && E2ToC1) {
3264 // Conversion to Composite1 is viable.
3265 if (!Context.hasSameType(Composite1, Composite2)) {
3266 // Composite2 is a different type from Composite1. Check whether
3267 // Composite2 is also viable.
3268 InitializedEntity Entity2
3269 = InitializedEntity::InitializeTemporary(Composite2);
3270 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3271 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3272 if (E1ToC2 && E2ToC2) {
3273 // Both Composite1 and Composite2 are viable and are different;
3274 // this is an ambiguity.
3275 return QualType();
3276 }
3277 }
3278
3279 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003280 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003281 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003282 if (E1Result.isInvalid())
3283 return QualType();
3284 E1 = E1Result.takeAs<Expr>();
3285
3286 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003287 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003288 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003289 if (E2Result.isInvalid())
3290 return QualType();
3291 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003292
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003293 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003294 }
3295
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003296 // Check whether Composite2 is viable.
3297 InitializedEntity Entity2
3298 = InitializedEntity::InitializeTemporary(Composite2);
3299 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3300 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3301 if (!E1ToC2 || !E2ToC2)
3302 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003304 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003305 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003306 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003307 if (E1Result.isInvalid())
3308 return QualType();
3309 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003310
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003311 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003312 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003313 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003314 if (E2Result.isInvalid())
3315 return QualType();
3316 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003317
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003318 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003319}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003320
John McCall60d7b3a2010-08-24 06:29:42 +00003321ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003322 if (!E)
3323 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003324
Anders Carlsson089c2602009-08-15 23:41:35 +00003325 if (!Context.getLangOptions().CPlusPlus)
3326 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003327
Douglas Gregor51326552009-12-24 18:51:59 +00003328 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3329
Ted Kremenek6217b802009-07-29 21:53:49 +00003330 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003331 if (!RT)
3332 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003334 // If this is the result of a call or an Objective-C message send expression,
3335 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00003336 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003337 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00003338 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003339 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3340 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
3341 if (MD->getResultType()->isReferenceType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003342 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003343 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00003344 }
John McCall86ff3082010-02-04 22:26:26 +00003345
3346 // That should be enough to guarantee that this type is complete.
3347 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003348 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003349 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003350 return Owned(E);
3351
Douglas Gregordb89f282010-07-01 22:47:18 +00003352 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003353 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003354 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003355 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003356 CheckDestructorAccess(E->getExprLoc(), Destructor,
3357 PDiag(diag::err_access_dtor_temp)
3358 << E->getType());
3359 }
Anders Carlssondef11992009-05-30 20:36:53 +00003360 // FIXME: Add the temporary to the temporaries vector.
3361 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3362}
3363
John McCall4765fa02010-12-06 08:20:24 +00003364Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003365 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003366
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003367 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3368 assert(ExprTemporaries.size() >= FirstTemporary);
3369 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003370 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003371
John McCall4765fa02010-12-06 08:20:24 +00003372 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3373 &ExprTemporaries[FirstTemporary],
3374 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003375 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3376 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003378 return E;
3379}
3380
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003381ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003382Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003383 if (SubExpr.isInvalid())
3384 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385
John McCall4765fa02010-12-06 08:20:24 +00003386 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003387}
3388
John McCall4765fa02010-12-06 08:20:24 +00003389Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003390 assert(SubStmt && "sub statement can't be null!");
3391
3392 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3393 assert(ExprTemporaries.size() >= FirstTemporary);
3394 if (ExprTemporaries.size() == FirstTemporary)
3395 return SubStmt;
3396
3397 // FIXME: In order to attach the temporaries, wrap the statement into
3398 // a StmtExpr; currently this is only used for asm statements.
3399 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3400 // a new AsmStmtWithTemporaries.
3401 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3402 SourceLocation(),
3403 SourceLocation());
3404 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3405 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003406 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003407}
3408
John McCall60d7b3a2010-08-24 06:29:42 +00003409ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003410Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003411 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003412 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003413 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003414 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003415 if (Result.isInvalid()) return ExprError();
3416 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003417
John McCall9ae2f072010-08-23 23:25:46 +00003418 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003419 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003420 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003421 // If we have a pointer to a dependent type and are using the -> operator,
3422 // the object type is the type that the pointer points to. We might still
3423 // have enough information about that type to do something useful.
3424 if (OpKind == tok::arrow)
3425 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3426 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427
John McCallb3d87482010-08-24 05:47:05 +00003428 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003429 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003430 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003431 }
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003433 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003434 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003435 // returned, with the original second operand.
3436 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003437 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003438 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003439 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003440 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003441
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003442 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003443 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3444 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003445 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003446 Base = Result.get();
3447 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003448 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003449 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003450 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003451 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003452 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003453 for (unsigned i = 0; i < Locations.size(); i++)
3454 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003455 return ExprError();
3456 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003457 }
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Douglas Gregor31658df2009-11-20 19:58:21 +00003459 if (BaseType->isPointerType())
3460 BaseType = BaseType->getPointeeType();
3461 }
Mike Stump1eb44332009-09-09 15:08:12 +00003462
3463 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003464 // vector types or Objective-C interfaces. Just return early and let
3465 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003466 if (!BaseType->isRecordType()) {
3467 // C++ [basic.lookup.classref]p2:
3468 // [...] If the type of the object expression is of pointer to scalar
3469 // type, the unqualified-id is looked up in the context of the complete
3470 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003471 //
3472 // This also indicates that we should be parsing a
3473 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003474 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003475 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003476 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003477 }
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Douglas Gregor03c57052009-11-17 05:17:33 +00003479 // The object type must be complete (or dependent).
3480 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003481 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003482 PDiag(diag::err_incomplete_member_access)))
3483 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484
Douglas Gregorc68afe22009-09-03 21:38:09 +00003485 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003486 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003487 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003488 // type C (or of pointer to a class type C), the unqualified-id is looked
3489 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003490 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003491 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003492}
3493
John McCall60d7b3a2010-08-24 06:29:42 +00003494ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003495 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003496 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003497 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3498 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003499 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500
Douglas Gregor77549082010-02-24 21:29:12 +00003501 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003502 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003503 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003504 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003505 /*RPLoc*/ ExpectedLParenLoc);
3506}
Douglas Gregord4dca082010-02-24 18:44:31 +00003507
John McCall60d7b3a2010-08-24 06:29:42 +00003508ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003509 SourceLocation OpLoc,
3510 tok::TokenKind OpKind,
3511 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003512 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003513 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003514 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003515 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003516 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003517 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003518
Douglas Gregorb57fb492010-02-24 22:38:50 +00003519 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003520 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003521 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003522 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003523 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003524 if (OpKind == tok::arrow) {
3525 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3526 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003527 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003528 // The user wrote "p->" when she probably meant "p."; fix it.
3529 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3530 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003531 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003532 if (isSFINAEContext())
3533 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534
Douglas Gregorb57fb492010-02-24 22:38:50 +00003535 OpKind = tok::period;
3536 }
3537 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003538
Douglas Gregorb57fb492010-02-24 22:38:50 +00003539 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3540 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003541 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003542 return ExprError();
3543 }
3544
3545 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003546 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003547 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003548 if (DestructedTypeInfo) {
3549 QualType DestructedType = DestructedTypeInfo->getType();
3550 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003551 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003552 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3553 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3554 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003555 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003556 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003557
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003558 // Recover by setting the destructed type to the object type.
3559 DestructedType = ObjectType;
3560 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3561 DestructedTypeStart);
3562 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3563 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003564 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003565
Douglas Gregorb57fb492010-02-24 22:38:50 +00003566 // C++ [expr.pseudo]p2:
3567 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3568 // form
3569 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003570 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003571 //
3572 // shall designate the same scalar type.
3573 if (ScopeTypeInfo) {
3574 QualType ScopeType = ScopeTypeInfo->getType();
3575 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003576 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003578 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003579 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003580 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003581 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003582
Douglas Gregorb57fb492010-02-24 22:38:50 +00003583 ScopeType = QualType();
3584 ScopeTypeInfo = 0;
3585 }
3586 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003587
John McCall9ae2f072010-08-23 23:25:46 +00003588 Expr *Result
3589 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3590 OpKind == tok::arrow, OpLoc,
3591 SS.getScopeRep(), SS.getRange(),
3592 ScopeTypeInfo,
3593 CCLoc,
3594 TildeLoc,
3595 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596
Douglas Gregorb57fb492010-02-24 22:38:50 +00003597 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003598 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003599
John McCall9ae2f072010-08-23 23:25:46 +00003600 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003601}
3602
John McCall60d7b3a2010-08-24 06:29:42 +00003603ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003604 SourceLocation OpLoc,
3605 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003606 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003607 UnqualifiedId &FirstTypeName,
3608 SourceLocation CCLoc,
3609 SourceLocation TildeLoc,
3610 UnqualifiedId &SecondTypeName,
3611 bool HasTrailingLParen) {
3612 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3613 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3614 "Invalid first type name in pseudo-destructor");
3615 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3616 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3617 "Invalid second type name in pseudo-destructor");
3618
Douglas Gregor77549082010-02-24 21:29:12 +00003619 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003620 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003621 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003622 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003623 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003624 if (OpKind == tok::arrow) {
3625 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3626 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003627 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003628 // The user wrote "p->" when she probably meant "p."; fix it.
3629 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003630 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003631 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003632 if (isSFINAEContext())
3633 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003634
Douglas Gregor77549082010-02-24 21:29:12 +00003635 OpKind = tok::period;
3636 }
3637 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003638
3639 // Compute the object type that we should use for name lookup purposes. Only
3640 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003641 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003642 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003643 if (const Type *T = ObjectType->getAs<RecordType>())
3644 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3645 else if (ObjectType->isDependentType())
3646 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003647 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003648
3649 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003650 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003651 QualType DestructedType;
3652 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003653 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003654 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003656 SecondTypeName.StartLocation,
3657 S, &SS, true, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003658 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003659 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3660 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003661 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003662 // couldn't find anything useful in scope. Just store the identifier and
3663 // it's location, and we'll perform (qualified) name lookup again at
3664 // template instantiation time.
3665 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3666 SecondTypeName.StartLocation);
3667 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003668 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003669 diag::err_pseudo_dtor_destructor_non_type)
3670 << SecondTypeName.Identifier << ObjectType;
3671 if (isSFINAEContext())
3672 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673
Douglas Gregor77549082010-02-24 21:29:12 +00003674 // Recover by assuming we had the right type all along.
3675 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003676 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003677 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003678 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003679 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003680 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003681 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3682 TemplateId->getTemplateArgs(),
3683 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003684 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003685 TemplateId->TemplateNameLoc,
3686 TemplateId->LAngleLoc,
3687 TemplateArgsPtr,
3688 TemplateId->RAngleLoc);
3689 if (T.isInvalid() || !T.get()) {
3690 // Recover by assuming we had the right type all along.
3691 DestructedType = ObjectType;
3692 } else
3693 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003695
3696 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003697 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003698 if (!DestructedType.isNull()) {
3699 if (!DestructedTypeInfo)
3700 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003701 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003702 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3703 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704
Douglas Gregorb57fb492010-02-24 22:38:50 +00003705 // Convert the name of the scope type (the type prior to '::') into a type.
3706 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003707 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003709 FirstTypeName.Identifier) {
3710 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003711 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003712 FirstTypeName.StartLocation,
3713 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003714 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003715 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003716 diag::err_pseudo_dtor_destructor_non_type)
3717 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003718
Douglas Gregorb57fb492010-02-24 22:38:50 +00003719 if (isSFINAEContext())
3720 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003721
Douglas Gregorb57fb492010-02-24 22:38:50 +00003722 // Just drop this type. It's unnecessary anyway.
3723 ScopeType = QualType();
3724 } else
3725 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003726 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003727 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003728 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003729 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3730 TemplateId->getTemplateArgs(),
3731 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003732 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003733 TemplateId->TemplateNameLoc,
3734 TemplateId->LAngleLoc,
3735 TemplateArgsPtr,
3736 TemplateId->RAngleLoc);
3737 if (T.isInvalid() || !T.get()) {
3738 // Recover by dropping this type.
3739 ScopeType = QualType();
3740 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003741 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003742 }
3743 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003744
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003745 if (!ScopeType.isNull() && !ScopeTypeInfo)
3746 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3747 FirstTypeName.StartLocation);
3748
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003749
John McCall9ae2f072010-08-23 23:25:46 +00003750 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003751 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003752 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003753}
3754
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003755ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3756 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003757 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3758 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003759 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003760
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003761 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003762 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003763 SourceLocation(), Method->getType(),
3764 VK_RValue, OK_Ordinary);
3765 QualType ResultType = Method->getResultType();
3766 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3767 ResultType = ResultType.getNonLValueExprType(Context);
3768
Douglas Gregor7edfb692009-11-23 12:27:39 +00003769 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3770 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003771 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003772 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003773 return CE;
3774}
3775
Sebastian Redl2e156222010-09-10 20:55:43 +00003776ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3777 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003778 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3779 Operand->CanThrow(Context),
3780 KeyLoc, RParen));
3781}
3782
3783ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3784 Expr *Operand, SourceLocation RParen) {
3785 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003786}
3787
John McCallf6a16482010-12-04 03:47:34 +00003788/// Perform the conversions required for an expression used in a
3789/// context that ignores the result.
3790void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003791 // C99 6.3.2.1:
3792 // [Except in specific positions,] an lvalue that does not have
3793 // array type is converted to the value stored in the
3794 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003795 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003796
John McCallf6a16482010-12-04 03:47:34 +00003797 // We always want to do this on ObjC property references.
3798 if (E->getObjectKind() == OK_ObjCProperty) {
3799 ConvertPropertyForRValue(E);
3800 if (E->isRValue()) return;
3801 }
3802
3803 // Otherwise, this rule does not apply in C++, at least not for the moment.
3804 if (getLangOptions().CPlusPlus) return;
3805
3806 // GCC seems to also exclude expressions of incomplete enum type.
3807 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3808 if (!T->getDecl()->isComplete()) {
3809 // FIXME: stupid workaround for a codegen bug!
3810 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3811 return;
3812 }
3813 }
3814
3815 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003816 if (!E->getType()->isVoidType())
3817 RequireCompleteType(E->getExprLoc(), E->getType(),
3818 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003819}
3820
3821ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003823 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003824
Douglas Gregord0937222010-12-13 22:49:22 +00003825 if (DiagnoseUnexpandedParameterPack(FullExpr))
3826 return ExprError();
3827
John McCallf6a16482010-12-04 03:47:34 +00003828 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003829 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003830 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003831}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003832
3833StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3834 if (!FullStmt) return StmtError();
3835
John McCall4765fa02010-12-06 08:20:24 +00003836 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003837}