blob: c3e2c503122e9d1571a47d0470394044cf163574 [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,
34 IdentifierInfo &II,
35 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();
74
75 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000077 // C++ [basic.lookup.qual]p6:
78 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
79 // 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:
81 //
82 // ::[opt] nested-name-specifier ̃ class-name
83 //
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 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000087 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000089 // the class-names are looked up as types in the scope designated by
90 // 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
93 // code below is permitted to look at the prefix of the
94 // 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;
102
103 // 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 }
Douglas Gregor93649fd2010-02-23 00:15:22 +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();
131 assert((isDependent || !SearchType->isIncompleteType()) &&
132 "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
173 // issue 399, for which there isn't even an obvious direction.
174 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;
185
186 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 }
202
203 // 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.
223 if (DependentTemplateName *DepTemplate
224 = 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)
256 << &II;
257 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 Gregor57fdc8a2010-04-26 22:37:10 +0000265 SourceLocation TypeidLoc,
266 TypeSourceInfo *Operand,
267 SourceLocation RParenLoc) {
268 // C++ [expr.typeid]p4:
269 // The top-level cv-qualifiers of the lvalue expression or the type-id
270 // that is the operand of typeid are always ignored.
271 // If the type of the type-id is a class type or a reference to a class
272 // 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();
Daniel Dunbar380c2132010-05-11 21:32:35 +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 Gregor57fdc8a2010-04-26 22:37:10 +0000288 SourceLocation TypeidLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000289 Expr *E,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000290 SourceLocation RParenLoc) {
291 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();
301
302 // 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 }
313
314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
318 // 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 }
326
327 // 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;
332
333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000334 E,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000335 SourceRange(TypeidLoc, RParenLoc)));
336}
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
Chris Lattner572af492008-11-20 05:51:55 +0000346 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000347 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +0000348 LookupQualifiedName(R, getStdNamespace());
John McCall1bcee0a2009-12-02 08:25:40 +0000349 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000350 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000351 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000352
Sebastian Redlc42e1182008-11-11 11:37:55 +0000353 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000354
355 if (isType) {
356 // The operand is a type; handle it as such.
357 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000358 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
359 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000360 if (T.isNull())
361 return ExprError();
362
363 if (!TInfo)
364 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000365
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000367 }
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000370 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000371}
372
Francois Pichet01b7c302010-09-08 12:20:18 +0000373/// \brief Build a Microsoft __uuidof expression with a type operand.
374ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
375 SourceLocation TypeidLoc,
376 TypeSourceInfo *Operand,
377 SourceLocation RParenLoc) {
378 // FIXME: add __uuidof semantic analysis for type operand.
379 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
380 Operand,
381 SourceRange(TypeidLoc, RParenLoc)));
382}
383
384/// \brief Build a Microsoft __uuidof expression with an expression operand.
385ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
386 SourceLocation TypeidLoc,
387 Expr *E,
388 SourceLocation RParenLoc) {
389 // FIXME: add __uuidof semantic analysis for expr operand.
390 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
391 E,
392 SourceRange(TypeidLoc, RParenLoc)));
393}
394
395/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
396ExprResult
397Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
398 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
399 // If MSVCGuidDecl has not been cached, do the lookup.
400 if (!MSVCGuidDecl) {
401 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
402 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
403 LookupQualifiedName(R, Context.getTranslationUnitDecl());
404 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
405 if (!MSVCGuidDecl)
406 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
407 }
408
409 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
410
411 if (isType) {
412 // The operand is a type; handle it as such.
413 TypeSourceInfo *TInfo = 0;
414 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
415 &TInfo);
416 if (T.isNull())
417 return ExprError();
418
419 if (!TInfo)
420 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
421
422 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
423 }
424
425 // The operand is an expression.
426 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
427}
428
Steve Naroff1b273c42007-09-16 14:56:35 +0000429/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000430ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000431Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000432 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000434 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
435 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000436}
Chris Lattner50dd2892008-02-26 00:51:44 +0000437
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000438/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000439ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000440Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
441 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
442}
443
Chris Lattner50dd2892008-02-26 00:51:44 +0000444/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000445ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000446Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000447 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
448 return ExprError();
449 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
450}
451
452/// CheckCXXThrowOperand - Validate the operand of a throw.
453bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
454 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000455 // A throw-expression initializes a temporary object, called the exception
456 // object, the type of which is determined by removing any top-level
457 // cv-qualifiers from the static type of the operand of throw and adjusting
458 // the type from "array of T" or "function returning T" to "pointer to T"
459 // or "pointer to function returning T", [...]
460 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000461 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000462 CastCategory(E));
Douglas Gregor154fe982009-12-23 22:04:40 +0000463
Sebastian Redl972041f2009-04-27 20:27:31 +0000464 DefaultFunctionArrayConversion(E);
465
466 // If the type of the exception would be an incomplete type or a pointer
467 // to an incomplete type other than (cv) void the program is ill-formed.
468 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000469 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000470 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000471 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000472 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000473 }
474 if (!isPointer || !Ty->isVoidType()) {
475 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000476 PDiag(isPointer ? diag::err_throw_incomplete_ptr
477 : diag::err_throw_incomplete)
478 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000479 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000480
Douglas Gregorbf422f92010-04-15 18:05:39 +0000481 if (RequireNonAbstractType(ThrowLoc, E->getType(),
482 PDiag(diag::err_throw_abstract_type)
483 << E->getSourceRange()))
484 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000485 }
486
John McCallac418162010-04-22 01:10:34 +0000487 // Initialize the exception result. This implicitly weeds out
488 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000489 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000490 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000491 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
492 /*NRVO=*/false);
John McCall60d7b3a2010-08-24 06:29:42 +0000493 ExprResult Res = PerformCopyInitialization(Entity,
John McCallac418162010-04-22 01:10:34 +0000494 SourceLocation(),
495 Owned(E));
496 if (Res.isInvalid())
497 return true;
498 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000499
Eli Friedman5ed9b932010-06-03 20:39:03 +0000500 // If the exception has class type, we need additional handling.
501 const RecordType *RecordTy = Ty->getAs<RecordType>();
502 if (!RecordTy)
503 return false;
504 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
505
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000506 // If we are throwing a polymorphic class type or pointer thereof,
507 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000508 MarkVTableUsed(ThrowLoc, RD);
509
510 // If the class has a non-trivial destructor, we must be able to call it.
511 if (RD->hasTrivialDestructor())
512 return false;
513
Douglas Gregor1d110e02010-07-01 14:13:13 +0000514 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000515 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000516 if (!Destructor)
517 return false;
518
519 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
520 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000521 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000522 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000523}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000524
John McCall60d7b3a2010-08-24 06:29:42 +0000525ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000526 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
527 /// is a non-lvalue expression whose value is the address of the object for
528 /// which the function is called.
529
John McCallea1471e2010-05-20 01:18:31 +0000530 DeclContext *DC = getFunctionLevelDeclContext();
531 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000532 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000533 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000534 MD->getThisType(Context),
535 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000536
Sebastian Redlf53597f2009-03-15 17:47:39 +0000537 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000538}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000539
John McCall60d7b3a2010-08-24 06:29:42 +0000540ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000541Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000542 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000543 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000544 SourceLocation *CommaLocs,
545 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000546 if (!TypeRep)
547 return ExprError();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000548
John McCall9d125032010-01-15 18:39:57 +0000549 TypeSourceInfo *TInfo;
550 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
551 if (!TInfo)
552 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000553
554 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
555}
556
557/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
558/// Can be interpreted either as function-style casting ("int(x)")
559/// or class type construction ("ClassType(x,y,z)")
560/// or creation of a value-initialized type ("int()").
561ExprResult
562Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
563 SourceLocation LParenLoc,
564 MultiExprArg exprs,
565 SourceLocation RParenLoc) {
566 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000567 unsigned NumExprs = exprs.size();
568 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000569 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000570 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
571
Sebastian Redlf53597f2009-03-15 17:47:39 +0000572 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000573 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000574 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregorab6677e2010-09-08 00:15:04 +0000576 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000577 LParenLoc,
578 Exprs, NumExprs,
579 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000580 }
581
Anders Carlssonbb60a502009-08-27 03:53:50 +0000582 if (Ty->isArrayType())
583 return ExprError(Diag(TyBeginLoc,
584 diag::err_value_init_for_array_type) << FullRange);
585 if (!Ty->isVoidType() &&
586 RequireCompleteType(TyBeginLoc, Ty,
587 PDiag(diag::err_invalid_incomplete_type_use)
588 << FullRange))
589 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000590
Anders Carlssonbb60a502009-08-27 03:53:50 +0000591 if (RequireNonAbstractType(TyBeginLoc, Ty,
592 diag::err_allocation_of_abstract_type))
593 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000594
595
Douglas Gregor506ae412009-01-16 18:33:17 +0000596 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000597 // If the expression list is a single expression, the type conversion
598 // expression is equivalent (in definedness, and if defined in meaning) to the
599 // corresponding cast expression.
600 //
601 if (NumExprs == 1) {
John McCall2de56d12010-08-25 11:45:40 +0000602 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +0000603 CXXCastPath BasePath;
Douglas Gregorab6677e2010-09-08 00:15:04 +0000604 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
605 Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000606 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000607 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000608
609 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000610
John McCallf871d0c2010-08-07 06:22:56 +0000611 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000612 Ty.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000613 TInfo, TyBeginLoc, Kind,
614 Exprs[0], &BasePath,
615 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000616 }
617
Douglas Gregored8abf12010-07-08 06:14:04 +0000618 if (Ty->isRecordType()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +0000619 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Douglas Gregored8abf12010-07-08 06:14:04 +0000620 InitializationKind Kind
Douglas Gregorab6677e2010-09-08 00:15:04 +0000621 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
Douglas Gregored8abf12010-07-08 06:14:04 +0000622 LParenLoc, RParenLoc)
Douglas Gregorab6677e2010-09-08 00:15:04 +0000623 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregored8abf12010-07-08 06:14:04 +0000624 LParenLoc, RParenLoc);
625 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000626 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000627
Douglas Gregored8abf12010-07-08 06:14:04 +0000628 // FIXME: Improve AST representation?
629 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000630 }
631
632 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000633 // If the expression list specifies more than a single value, the type shall
634 // be a class with a suitably declared constructor.
635 //
636 if (NumExprs > 1)
Douglas Gregorab6677e2010-09-08 00:15:04 +0000637 return ExprError(Diag(PP.getLocForEndOfToken(Exprs[0]->getLocEnd()),
Sebastian Redlf53597f2009-03-15 17:47:39 +0000638 diag::err_builtin_func_cast_more_than_one_arg)
639 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000640
641 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregorab6677e2010-09-08 00:15:04 +0000642 // FIXME: Why doesn't this go through the new-initialization code?
643
Douglas Gregor506ae412009-01-16 18:33:17 +0000644 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000645 // The expression T(), where T is a simple-type-specifier for a non-array
646 // complete object type or the (possibly cv-qualified) void type, creates an
647 // rvalue of the specified type, which is value-initialized.
648 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000649 exprs.release();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000650 return Owned(new (Context) CXXScalarValueInitExpr(
651 TInfo->getType().getNonLValueExprType(Context),
652 TInfo, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000653}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000654
655
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000656/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
657/// @code new (memory) int[size][4] @endcode
658/// or
659/// @code ::new Foo(23, "hello") @endcode
660/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000661ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000662Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000663 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000664 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000665 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000666 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000667 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000668 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000669 // If the specified type is an array, unwrap it and save the expression.
670 if (D.getNumTypeObjects() > 0 &&
671 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
672 DeclaratorChunk &Chunk = D.getTypeObject(0);
673 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000674 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
675 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000676 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000677 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
678 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000679
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000680 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000681 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000682 }
683
Douglas Gregor043cad22009-09-11 00:18:58 +0000684 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000685 if (ArraySize) {
686 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000687 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
688 break;
689
690 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
691 if (Expr *NumElts = (Expr *)Array.NumElts) {
692 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
693 !NumElts->isIntegerConstantExpr(Context)) {
694 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
695 << NumElts->getSourceRange();
696 return ExprError();
697 }
698 }
699 }
700 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000701
John McCallbf1a0282010-06-04 23:28:52 +0000702 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
703 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000704 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000705 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000706
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000707 if (!TInfo)
708 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
709
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000710 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000711 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000712 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000713 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000714 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000715 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000716 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000717 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000718 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000719 ConstructorLParen,
720 move(ConstructorArgs),
721 ConstructorRParen);
722}
723
John McCall60d7b3a2010-08-24 06:29:42 +0000724ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000725Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
726 SourceLocation PlacementLParen,
727 MultiExprArg PlacementArgs,
728 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000729 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000730 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000731 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000732 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000733 SourceLocation ConstructorLParen,
734 MultiExprArg ConstructorArgs,
735 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000736 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
737 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000738 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000739
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000740 // Per C++0x [expr.new]p5, the type being constructed may be a
741 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000742 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000743 if (const ConstantArrayType *Array
744 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000745 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
746 Context.getSizeType(),
747 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000748 AllocType = Array->getElementType();
749 }
750 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000751
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000752 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000753
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000754 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
755 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000756 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000757
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000758 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000759
John McCall60d7b3a2010-08-24 06:29:42 +0000760 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000761 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000762 PDiag(diag::err_array_size_not_integral),
763 PDiag(diag::err_array_size_incomplete_type)
764 << ArraySize->getSourceRange(),
765 PDiag(diag::err_array_size_explicit_conversion),
766 PDiag(diag::note_array_size_conversion),
767 PDiag(diag::err_array_size_ambiguous_conversion),
768 PDiag(diag::note_array_size_conversion),
769 PDiag(getLangOptions().CPlusPlus0x? 0
770 : diag::ext_array_size_conversion));
771 if (ConvertedSize.isInvalid())
772 return ExprError();
773
John McCall9ae2f072010-08-23 23:25:46 +0000774 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000775 SizeType = ArraySize->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000776 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000777 return ExprError();
778
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000779 // Let's see if this is a constant < 0. If so, we reject it out of hand.
780 // We don't care about special rules, so we tell the machinery it's not
781 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000782 if (!ArraySize->isValueDependent()) {
783 llvm::APSInt Value;
784 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
785 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000786 llvm::APInt::getNullValue(Value.getBitWidth()),
787 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000788 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000789 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000790 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +0000791
792 if (!AllocType->isDependentType()) {
793 unsigned ActiveSizeBits
794 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
795 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
796 Diag(ArraySize->getSourceRange().getBegin(),
797 diag::err_array_too_large)
798 << Value.toString(10)
799 << ArraySize->getSourceRange();
800 return ExprError();
801 }
802 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000803 } else if (TypeIdParens.isValid()) {
804 // Can't have dynamic array size when the type-id is in parentheses.
805 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
806 << ArraySize->getSourceRange()
807 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
808 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
809
810 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000811 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000812 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000813
Eli Friedman73c39ab2009-10-20 08:27:19 +0000814 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000815 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000816 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000817
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000818 FunctionDecl *OperatorNew = 0;
819 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000820 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
821 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000822
Sebastian Redl28507842009-02-26 14:39:58 +0000823 if (!AllocType->isDependentType() &&
824 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
825 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000826 SourceRange(PlacementLParen, PlacementRParen),
827 UseGlobal, AllocType, ArraySize, PlaceArgs,
828 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000829 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000830 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000831 if (OperatorNew) {
832 // Add default arguments, if any.
833 const FunctionProtoType *Proto =
834 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000835 VariadicCallType CallType =
836 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000837
838 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
839 Proto, 1, PlaceArgs, NumPlaceArgs,
840 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000841 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000842
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000843 NumPlaceArgs = AllPlaceArgs.size();
844 if (NumPlaceArgs > 0)
845 PlaceArgs = &AllPlaceArgs[0];
846 }
847
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000848 bool Init = ConstructorLParen.isValid();
849 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000850 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000851 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
852 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000853 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000854
Anders Carlsson48c95012010-05-03 15:45:23 +0000855 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000856 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000857 SourceRange InitRange(ConsArgs[0]->getLocStart(),
858 ConsArgs[NumConsArgs - 1]->getLocEnd());
859
860 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
861 return ExprError();
862 }
863
Douglas Gregor99a2e602009-12-16 01:38:02 +0000864 if (!AllocType->isDependentType() &&
865 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
866 // C++0x [expr.new]p15:
867 // A new-expression that creates an object of type T initializes that
868 // object as follows:
869 InitializationKind Kind
870 // - If the new-initializer is omitted, the object is default-
871 // initialized (8.5); if no initialization is performed,
872 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000873 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
Douglas Gregor99a2e602009-12-16 01:38:02 +0000874 // - Otherwise, the new-initializer is interpreted according to the
875 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000876 : InitializationKind::CreateDirect(TypeRange.getBegin(),
Douglas Gregor99a2e602009-12-16 01:38:02 +0000877 ConstructorLParen,
878 ConstructorRParen);
879
Douglas Gregor99a2e602009-12-16 01:38:02 +0000880 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000881 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000882 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCall60d7b3a2010-08-24 06:29:42 +0000883 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000884 move(ConstructorArgs));
885 if (FullInit.isInvalid())
886 return ExprError();
887
888 // FullInit is our initializer; walk through it to determine if it's a
889 // constructor call, which CXXNewExpr handles directly.
890 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
891 if (CXXBindTemporaryExpr *Binder
892 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
893 FullInitExpr = Binder->getSubExpr();
894 if (CXXConstructExpr *Construct
895 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
896 Constructor = Construct->getConstructor();
897 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
898 AEnd = Construct->arg_end();
899 A != AEnd; ++A)
900 ConvertedConstructorArgs.push_back(A->Retain());
901 } else {
902 // Take the converted initializer.
903 ConvertedConstructorArgs.push_back(FullInit.release());
904 }
905 } else {
906 // No initialization required.
907 }
908
909 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000910 NumConsArgs = ConvertedConstructorArgs.size();
911 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000912 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000913
Douglas Gregor6d908702010-02-26 05:06:18 +0000914 // Mark the new and delete operators as referenced.
915 if (OperatorNew)
916 MarkDeclarationReferenced(StartLoc, OperatorNew);
917 if (OperatorDelete)
918 MarkDeclarationReferenced(StartLoc, OperatorDelete);
919
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000920 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000921
Sebastian Redlf53597f2009-03-15 17:47:39 +0000922 PlacementArgs.release();
923 ConstructorArgs.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000924
Ted Kremenekad7fe862010-02-11 22:51:03 +0000925 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000926 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000927 ArraySize, Constructor, Init,
928 ConsArgs, NumConsArgs, OperatorDelete,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000929 ResultType, AllocTypeInfo,
930 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000931 Init ? ConstructorRParen :
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000932 TypeRange.getEnd()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000933}
934
935/// CheckAllocatedType - Checks that a type is suitable as the allocated type
936/// in a new-expression.
937/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000938bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000939 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000940 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
941 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000942 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000943 return Diag(Loc, diag::err_bad_new_type)
944 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000945 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000946 return Diag(Loc, diag::err_bad_new_type)
947 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000948 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000949 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000950 PDiag(diag::err_new_incomplete_type)
951 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000952 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000953 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000954 diag::err_allocation_of_abstract_type))
955 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000956
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000957 return false;
958}
959
Douglas Gregor6d908702010-02-26 05:06:18 +0000960/// \brief Determine whether the given function is a non-placement
961/// deallocation function.
962static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
963 if (FD->isInvalidDecl())
964 return false;
965
966 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
967 return Method->isUsualDeallocationFunction();
968
969 return ((FD->getOverloadedOperator() == OO_Delete ||
970 FD->getOverloadedOperator() == OO_Array_Delete) &&
971 FD->getNumParams() == 1);
972}
973
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000974/// FindAllocationFunctions - Finds the overloads of operator new and delete
975/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000976bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
977 bool UseGlobal, QualType AllocType,
978 bool IsArray, Expr **PlaceArgs,
979 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000980 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000981 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000982 // --- Choosing an allocation function ---
983 // C++ 5.3.4p8 - 14 & 18
984 // 1) If UseGlobal is true, only look in the global scope. Else, also look
985 // in the scope of the allocated class.
986 // 2) If an array size is given, look for operator new[], else look for
987 // operator new.
988 // 3) The first argument is always size_t. Append the arguments from the
989 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000990
991 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
992 // We don't care about the actual value of this argument.
993 // FIXME: Should the Sema create the expression and embed it in the syntax
994 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000995 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +0000996 Context.Target.getPointerWidth(0)),
997 Context.getSizeType(),
998 SourceLocation());
999 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001000 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1001
Douglas Gregor6d908702010-02-26 05:06:18 +00001002 // C++ [expr.new]p8:
1003 // If the allocated type is a non-array type, the allocation
1004 // function’s name is operator new and the deallocation function’s
1005 // name is operator delete. If the allocated type is an array
1006 // type, the allocation function’s name is operator new[] and the
1007 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001008 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1009 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001010 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1011 IsArray ? OO_Array_Delete : OO_Delete);
1012
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001013 QualType AllocElemType = Context.getBaseElementType(AllocType);
1014
1015 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001016 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001017 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001018 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001019 AllocArgs.size(), Record, /*AllowMissing=*/true,
1020 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001021 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001022 }
1023 if (!OperatorNew) {
1024 // Didn't find a member overload. Look for a global one.
1025 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001026 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001027 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001028 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1029 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001030 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001031 }
1032
John McCall9c82afc2010-04-20 02:18:25 +00001033 // We don't need an operator delete if we're running under
1034 // -fno-exceptions.
1035 if (!getLangOptions().Exceptions) {
1036 OperatorDelete = 0;
1037 return false;
1038 }
1039
Anders Carlssond9583892009-05-31 20:26:12 +00001040 // FindAllocationOverload can change the passed in arguments, so we need to
1041 // copy them back.
1042 if (NumPlaceArgs > 0)
1043 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Douglas Gregor6d908702010-02-26 05:06:18 +00001045 // C++ [expr.new]p19:
1046 //
1047 // If the new-expression begins with a unary :: operator, the
1048 // deallocation function’s name is looked up in the global
1049 // scope. Otherwise, if the allocated type is a class type T or an
1050 // array thereof, the deallocation function’s name is looked up in
1051 // the scope of T. If this lookup fails to find the name, or if
1052 // the allocated type is not a class type or array thereof, the
1053 // deallocation function’s name is looked up in the global scope.
1054 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001055 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001056 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001057 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001058 LookupQualifiedName(FoundDelete, RD);
1059 }
John McCall90c8c572010-03-18 08:19:33 +00001060 if (FoundDelete.isAmbiguous())
1061 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001062
1063 if (FoundDelete.empty()) {
1064 DeclareGlobalNewDelete();
1065 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1066 }
1067
1068 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001069
1070 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1071
John McCall90c8c572010-03-18 08:19:33 +00001072 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001073 // C++ [expr.new]p20:
1074 // A declaration of a placement deallocation function matches the
1075 // declaration of a placement allocation function if it has the
1076 // same number of parameters and, after parameter transformations
1077 // (8.3.5), all parameter types except the first are
1078 // identical. [...]
1079 //
1080 // To perform this comparison, we compute the function type that
1081 // the deallocation function should have, and use that type both
1082 // for template argument deduction and for comparison purposes.
1083 QualType ExpectedFunctionType;
1084 {
1085 const FunctionProtoType *Proto
1086 = OperatorNew->getType()->getAs<FunctionProtoType>();
1087 llvm::SmallVector<QualType, 4> ArgTypes;
1088 ArgTypes.push_back(Context.VoidPtrTy);
1089 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1090 ArgTypes.push_back(Proto->getArgType(I));
1091
1092 ExpectedFunctionType
1093 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1094 ArgTypes.size(),
1095 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001096 0, false, false, 0, 0,
1097 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001098 }
1099
1100 for (LookupResult::iterator D = FoundDelete.begin(),
1101 DEnd = FoundDelete.end();
1102 D != DEnd; ++D) {
1103 FunctionDecl *Fn = 0;
1104 if (FunctionTemplateDecl *FnTmpl
1105 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1106 // Perform template argument deduction to try to match the
1107 // expected function type.
1108 TemplateDeductionInfo Info(Context, StartLoc);
1109 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1110 continue;
1111 } else
1112 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1113
1114 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001115 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001116 }
1117 } else {
1118 // C++ [expr.new]p20:
1119 // [...] Any non-placement deallocation function matches a
1120 // non-placement allocation function. [...]
1121 for (LookupResult::iterator D = FoundDelete.begin(),
1122 DEnd = FoundDelete.end();
1123 D != DEnd; ++D) {
1124 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1125 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001126 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001127 }
1128 }
1129
1130 // C++ [expr.new]p20:
1131 // [...] If the lookup finds a single matching deallocation
1132 // function, that function will be called; otherwise, no
1133 // deallocation function will be called.
1134 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001135 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001136
1137 // C++0x [expr.new]p20:
1138 // If the lookup finds the two-parameter form of a usual
1139 // deallocation function (3.7.4.2) and that function, considered
1140 // as a placement deallocation function, would have been
1141 // selected as a match for the allocation function, the program
1142 // is ill-formed.
1143 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1144 isNonPlacementDeallocationFunction(OperatorDelete)) {
1145 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1146 << SourceRange(PlaceArgs[0]->getLocStart(),
1147 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1148 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1149 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001150 } else {
1151 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001152 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001153 }
1154 }
1155
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001156 return false;
1157}
1158
Sebastian Redl7f662392008-12-04 22:20:51 +00001159/// FindAllocationOverload - Find an fitting overload for the allocation
1160/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001161bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1162 DeclarationName Name, Expr** Args,
1163 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001164 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001165 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1166 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001167 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001168 if (AllowMissing)
1169 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001170 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001171 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001172 }
1173
John McCall90c8c572010-03-18 08:19:33 +00001174 if (R.isAmbiguous())
1175 return true;
1176
1177 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001178
John McCall5769d612010-02-08 23:07:23 +00001179 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001180 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1181 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001182 // Even member operator new/delete are implicitly treated as
1183 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001184 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001185
John McCall9aa472c2010-03-19 07:35:19 +00001186 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1187 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001188 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1189 Candidates,
1190 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001191 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001192 }
1193
John McCall9aa472c2010-03-19 07:35:19 +00001194 FunctionDecl *Fn = cast<FunctionDecl>(D);
1195 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001196 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001197 }
1198
1199 // Do the resolution.
1200 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001201 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001202 case OR_Success: {
1203 // Got one!
1204 FunctionDecl *FnDecl = Best->Function;
1205 // The first argument is size_t, and the first parameter must be size_t,
1206 // too. This is checked on declaration and can be assumed. (It can't be
1207 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001208 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001209 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1210 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001211 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001212 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1213 FnDecl->getParamDecl(i)),
1214 SourceLocation(),
1215 Owned(Args[i]->Retain()));
1216 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001217 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001218
1219 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001220 }
1221 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001222 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001223 return false;
1224 }
1225
1226 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001227 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001228 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001229 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001230 return true;
1231
1232 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001233 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001234 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001235 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001236 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001237
1238 case OR_Deleted:
1239 Diag(StartLoc, diag::err_ovl_deleted_call)
1240 << Best->Function->isDeleted()
1241 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001242 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001243 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001244 }
1245 assert(false && "Unreachable, bad result from BestViableFunction");
1246 return true;
1247}
1248
1249
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001250/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1251/// delete. These are:
1252/// @code
1253/// void* operator new(std::size_t) throw(std::bad_alloc);
1254/// void* operator new[](std::size_t) throw(std::bad_alloc);
1255/// void operator delete(void *) throw();
1256/// void operator delete[](void *) throw();
1257/// @endcode
1258/// Note that the placement and nothrow forms of new are *not* implicitly
1259/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001260void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001261 if (GlobalNewDeleteDeclared)
1262 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001263
1264 // C++ [basic.std.dynamic]p2:
1265 // [...] The following allocation and deallocation functions (18.4) are
1266 // implicitly declared in global scope in each translation unit of a
1267 // program
1268 //
1269 // void* operator new(std::size_t) throw(std::bad_alloc);
1270 // void* operator new[](std::size_t) throw(std::bad_alloc);
1271 // void operator delete(void*) throw();
1272 // void operator delete[](void*) throw();
1273 //
1274 // These implicit declarations introduce only the function names operator
1275 // new, operator new[], operator delete, operator delete[].
1276 //
1277 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1278 // "std" or "bad_alloc" as necessary to form the exception specification.
1279 // However, we do not make these implicit declarations visible to name
1280 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001281 if (!StdBadAlloc) {
1282 // The "std::bad_alloc" class has not yet been declared, so build it
1283 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001284 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00001285 getOrCreateStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001286 SourceLocation(),
1287 &PP.getIdentifierTable().get("bad_alloc"),
1288 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001289 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001290 }
1291
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001292 GlobalNewDeleteDeclared = true;
1293
1294 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1295 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001296 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001297
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001298 DeclareGlobalAllocationFunction(
1299 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001300 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001301 DeclareGlobalAllocationFunction(
1302 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001303 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001304 DeclareGlobalAllocationFunction(
1305 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1306 Context.VoidTy, VoidPtr);
1307 DeclareGlobalAllocationFunction(
1308 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1309 Context.VoidTy, VoidPtr);
1310}
1311
1312/// DeclareGlobalAllocationFunction - Declares a single implicit global
1313/// allocation function if it doesn't already exist.
1314void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001315 QualType Return, QualType Argument,
1316 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001317 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1318
1319 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001320 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001321 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001322 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001323 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001324 // Only look at non-template functions, as it is the predefined,
1325 // non-templated allocation function we are trying to declare here.
1326 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1327 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001328 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001329 Func->getParamDecl(0)->getType().getUnqualifiedType());
1330 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001331 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1332 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001333 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001334 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001335 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001336 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001337 }
1338 }
1339
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001340 QualType BadAllocType;
1341 bool HasBadAllocExceptionSpec
1342 = (Name.getCXXOverloadedOperator() == OO_New ||
1343 Name.getCXXOverloadedOperator() == OO_Array_New);
1344 if (HasBadAllocExceptionSpec) {
1345 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001346 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001347 }
1348
1349 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1350 true, false,
1351 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001352 &BadAllocType,
1353 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001354 FunctionDecl *Alloc =
1355 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001356 FnType, /*TInfo=*/0, SC_None,
1357 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001358 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001359
1360 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001361 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopesfc284482009-12-16 16:59:22 +00001362
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001363 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001364 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001365 SC_None,
1366 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001367 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001368
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001369 // FIXME: Also add this declaration to the IdentifierResolver, but
1370 // make sure it is at the end of the chain to coincide with the
1371 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001372 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001373}
1374
Anders Carlsson78f74552009-11-15 18:45:20 +00001375bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1376 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001377 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001378 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001379 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001380 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001381
John McCalla24dc2e2009-11-17 02:14:36 +00001382 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001383 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001384
Chandler Carruth23893242010-06-28 00:30:51 +00001385 Found.suppressDiagnostics();
1386
John McCall046a7462010-08-04 00:31:26 +00001387 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001388 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1389 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001390 NamedDecl *ND = (*F)->getUnderlyingDecl();
1391
1392 // Ignore template operator delete members from the check for a usual
1393 // deallocation function.
1394 if (isa<FunctionTemplateDecl>(ND))
1395 continue;
1396
1397 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001398 Matches.push_back(F.getPair());
1399 }
1400
1401 // There's exactly one suitable operator; pick it.
1402 if (Matches.size() == 1) {
1403 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1404 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1405 Matches[0]);
1406 return false;
1407
1408 // We found multiple suitable operators; complain about the ambiguity.
1409 } else if (!Matches.empty()) {
1410 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1411 << Name << RD;
1412
1413 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1414 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1415 Diag((*F)->getUnderlyingDecl()->getLocation(),
1416 diag::note_member_declared_here) << Name;
1417 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001418 }
1419
1420 // We did find operator delete/operator delete[] declarations, but
1421 // none of them were suitable.
1422 if (!Found.empty()) {
1423 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1424 << Name << RD;
1425
1426 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001427 F != FEnd; ++F)
1428 Diag((*F)->getUnderlyingDecl()->getLocation(),
1429 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001430
1431 return true;
1432 }
1433
1434 // Look for a global declaration.
1435 DeclareGlobalNewDelete();
1436 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1437
1438 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1439 Expr* DeallocArgs[1];
1440 DeallocArgs[0] = &Null;
1441 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1442 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1443 Operator))
1444 return true;
1445
1446 assert(Operator && "Did not find a deallocation function!");
1447 return false;
1448}
1449
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001450/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1451/// @code ::delete ptr; @endcode
1452/// or
1453/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001454ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001455Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001456 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001457 // C++ [expr.delete]p1:
1458 // The operand shall have a pointer type, or a class type having a single
1459 // conversion function to a pointer type. The result has type void.
1460 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001461 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1462
Anders Carlssond67c4c32009-08-16 20:29:29 +00001463 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Sebastian Redl28507842009-02-26 14:39:58 +00001465 if (!Ex->isTypeDependent()) {
1466 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001467
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001468 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor254a9422010-07-29 14:44:35 +00001469 if (RequireCompleteType(StartLoc, Type,
1470 PDiag(diag::err_delete_incomplete_class_type)))
1471 return ExprError();
1472
John McCall32daa422010-03-31 01:36:47 +00001473 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1474
Fariborz Jahanian53462782009-09-11 21:44:33 +00001475 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001476 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001477 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001478 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001479 NamedDecl *D = I.getDecl();
1480 if (isa<UsingShadowDecl>(D))
1481 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1482
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001483 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001484 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001485 continue;
1486
John McCall32daa422010-03-31 01:36:47 +00001487 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001488
1489 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1490 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001491 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001492 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001493 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001494 if (ObjectPtrConversions.size() == 1) {
1495 // We have a single conversion to a pointer-to-object type. Perform
1496 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001497 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001498 if (!PerformImplicitConversion(Ex,
1499 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001500 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001501 Type = Ex->getType();
1502 }
1503 }
1504 else if (ObjectPtrConversions.size() > 1) {
1505 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1506 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001507 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1508 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001509 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001510 }
Sebastian Redl28507842009-02-26 14:39:58 +00001511 }
1512
Sebastian Redlf53597f2009-03-15 17:47:39 +00001513 if (!Type->isPointerType())
1514 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1515 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001516
Ted Kremenek6217b802009-07-29 21:53:49 +00001517 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001518 if (Pointee->isVoidType() && !isSFINAEContext()) {
1519 // The C++ standard bans deleting a pointer to a non-object type, which
1520 // effectively bans deletion of "void*". However, most compilers support
1521 // this, so we treat it as a warning unless we're in a SFINAE context.
1522 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1523 << Type << Ex->getSourceRange();
1524 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001525 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1526 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001527 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001528 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001529 PDiag(diag::warn_delete_incomplete)
1530 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001531 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001532
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001533 // C++ [expr.delete]p2:
1534 // [Note: a pointer to a const type can be the operand of a
1535 // delete-expression; it is not necessary to cast away the constness
1536 // (5.2.11) of the pointer expression before it is used as the operand
1537 // of the delete-expression. ]
1538 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001539 CK_NoOp);
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001540
Anders Carlssond67c4c32009-08-16 20:29:29 +00001541 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1542 ArrayForm ? OO_Array_Delete : OO_Delete);
1543
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001544 QualType PointeeElem = Context.getBaseElementType(Pointee);
1545 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001546 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1547
1548 if (!UseGlobal &&
1549 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001550 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001551
Anders Carlsson78f74552009-11-15 18:45:20 +00001552 if (!RD->hasTrivialDestructor())
Douglas Gregordb89f282010-07-01 22:47:18 +00001553 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump1eb44332009-09-09 15:08:12 +00001554 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001555 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001556 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001557
Anders Carlssond67c4c32009-08-16 20:29:29 +00001558 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001559 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001560 DeclareGlobalNewDelete();
1561 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001562 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001563 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001564 OperatorDelete))
1565 return ExprError();
1566 }
Mike Stump1eb44332009-09-09 15:08:12 +00001567
John McCall9c82afc2010-04-20 02:18:25 +00001568 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1569
Sebastian Redl28507842009-02-26 14:39:58 +00001570 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001571 }
1572
Sebastian Redlf53597f2009-03-15 17:47:39 +00001573 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001574 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001575}
1576
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001577/// \brief Check the use of the given variable as a C++ condition in an if,
1578/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001579ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
Douglas Gregor586596f2010-05-06 17:25:47 +00001580 SourceLocation StmtLoc,
1581 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001582 QualType T = ConditionVar->getType();
1583
1584 // C++ [stmt.select]p2:
1585 // The declarator shall not specify a function or an array.
1586 if (T->isFunctionType())
1587 return ExprError(Diag(ConditionVar->getLocation(),
1588 diag::err_invalid_use_of_function_type)
1589 << ConditionVar->getSourceRange());
1590 else if (T->isArrayType())
1591 return ExprError(Diag(ConditionVar->getLocation(),
1592 diag::err_invalid_use_of_array_type)
1593 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001594
Douglas Gregor586596f2010-05-06 17:25:47 +00001595 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1596 ConditionVar->getLocation(),
1597 ConditionVar->getType().getNonReferenceType());
Douglas Gregorff331c12010-07-25 18:17:45 +00001598 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001599 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00001600
1601 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001602}
1603
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001604/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1605bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1606 // C++ 6.4p4:
1607 // The value of a condition that is an initialized declaration in a statement
1608 // other than a switch statement is the value of the declared variable
1609 // implicitly converted to type bool. If that conversion is ill-formed, the
1610 // program is ill-formed.
1611 // The value of a condition that is an expression is the value of the
1612 // expression, implicitly converted to bool.
1613 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001614 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001615}
Douglas Gregor77a52232008-09-12 00:47:35 +00001616
1617/// Helper function to determine whether this is the (deprecated) C++
1618/// conversion from a string literal to a pointer to non-const char or
1619/// non-const wchar_t (for narrow and wide string literals,
1620/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001621bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001622Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1623 // Look inside the implicit cast, if it exists.
1624 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1625 From = Cast->getSubExpr();
1626
1627 // A string literal (2.13.4) that is not a wide string literal can
1628 // be converted to an rvalue of type "pointer to char"; a wide
1629 // string literal can be converted to an rvalue of type "pointer
1630 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001631 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001632 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001633 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001634 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001635 // This conversion is considered only when there is an
1636 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001637 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001638 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1639 (!StrLit->isWide() &&
1640 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1641 ToPointeeType->getKind() == BuiltinType::Char_S))))
1642 return true;
1643 }
1644
1645 return false;
1646}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001647
John McCall60d7b3a2010-08-24 06:29:42 +00001648static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001649 SourceLocation CastLoc,
1650 QualType Ty,
1651 CastKind Kind,
1652 CXXMethodDecl *Method,
1653 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001654 switch (Kind) {
1655 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001656 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001657 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001658
1659 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001660 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001661 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001662 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001663
John McCall60d7b3a2010-08-24 06:29:42 +00001664 ExprResult Result =
Douglas Gregorba70ab62010-04-16 22:17:36 +00001665 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001666 move_arg(ConstructorArgs),
1667 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001668 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001669 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001670
1671 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1672 }
1673
John McCall2de56d12010-08-25 11:45:40 +00001674 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001675 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1676
1677 // Create an implicit call expr that calls it.
1678 // FIXME: pass the FoundDecl for the user-defined conversion here
1679 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1680 return S.MaybeBindToTemporary(CE);
1681 }
1682 }
1683}
1684
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001685/// PerformImplicitConversion - Perform an implicit conversion of the
1686/// expression From to the type ToType using the pre-computed implicit
1687/// conversion sequence ICS. Returns true if there was an error, false
1688/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001689/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001690/// used in the error message.
1691bool
1692Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1693 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001694 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001695 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001696 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001697 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001698 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001699 return true;
1700 break;
1701
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001702 case ImplicitConversionSequence::UserDefinedConversion: {
1703
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001704 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall2de56d12010-08-25 11:45:40 +00001705 CastKind CastKind = CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001706 QualType BeforeToType;
1707 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001708 CastKind = CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001709
1710 // If the user-defined conversion is specified by a conversion function,
1711 // the initial standard conversion sequence converts the source type to
1712 // the implicit object parameter of the conversion function.
1713 BeforeToType = Context.getTagDeclType(Conv->getParent());
1714 } else if (const CXXConstructorDecl *Ctor =
1715 dyn_cast<CXXConstructorDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001716 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001717 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001718 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001719 // If the user-defined conversion is specified by a constructor, the
1720 // initial standard conversion sequence converts the source type to the
1721 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001722 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1723 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001724 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001725 else
1726 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001727 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001728 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001729 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001730 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001731 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001732 return true;
1733 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001734
John McCall60d7b3a2010-08-24 06:29:42 +00001735 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001736 = BuildCXXCastArgument(*this,
1737 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001738 ToType.getNonReferenceType(),
1739 CastKind, cast<CXXMethodDecl>(FD),
John McCall9ae2f072010-08-23 23:25:46 +00001740 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001741
1742 if (CastArg.isInvalid())
1743 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001744
1745 From = CastArg.takeAs<Expr>();
1746
Eli Friedmand8889622009-11-27 04:41:50 +00001747 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001748 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001749 }
John McCall1d318332010-01-12 00:44:57 +00001750
1751 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001752 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001753 PDiag(diag::err_typecheck_ambiguous_condition)
1754 << From->getSourceRange());
1755 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001756
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001757 case ImplicitConversionSequence::EllipsisConversion:
1758 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001759 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001760
1761 case ImplicitConversionSequence::BadConversion:
1762 return true;
1763 }
1764
1765 // Everything went well.
1766 return false;
1767}
1768
1769/// PerformImplicitConversion - Perform an implicit conversion of the
1770/// expression From to the type ToType by following the standard
1771/// conversion sequence SCS. Returns true if there was an error, false
1772/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001773/// expression. Flavor is the context in which we're performing this
1774/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001775bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001776Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001777 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001778 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001779 // Overall FIXME: we are recomputing too many types here and doing far too
1780 // much extra work. What this means is that we need to keep track of more
1781 // information that is computed when we try the implicit conversion initially,
1782 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001783 QualType FromType = From->getType();
1784
Douglas Gregor225c41e2008-11-03 19:09:14 +00001785 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001786 // FIXME: When can ToType be a reference type?
1787 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001788 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001789 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001790 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001791 MultiExprArg(*this, &From, 1),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001792 /*FIXME:ConstructLoc*/SourceLocation(),
1793 ConstructorArgs))
1794 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001795 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001796 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1797 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001798 move_arg(ConstructorArgs),
1799 /*ZeroInit*/ false,
1800 CXXConstructExpr::CK_Complete);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001801 if (FromResult.isInvalid())
1802 return true;
1803 From = FromResult.takeAs<Expr>();
1804 return false;
1805 }
John McCall60d7b3a2010-08-24 06:29:42 +00001806 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001807 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1808 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001809 MultiExprArg(*this, &From, 1),
1810 /*ZeroInit*/ false,
1811 CXXConstructExpr::CK_Complete);
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001813 if (FromResult.isInvalid())
1814 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001816 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001817 return false;
1818 }
1819
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001820 // Resolve overloaded function references.
1821 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1822 DeclAccessPair Found;
1823 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1824 true, Found);
1825 if (!Fn)
1826 return true;
1827
1828 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1829 return true;
1830
1831 From = FixOverloadedFunctionReference(From, Found, Fn);
1832 FromType = From->getType();
1833 }
1834
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001835 // Perform the first implicit conversion.
1836 switch (SCS.First) {
1837 case ICK_Identity:
1838 case ICK_Lvalue_To_Rvalue:
1839 // Nothing to do.
1840 break;
1841
1842 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001843 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001844 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001845 break;
1846
1847 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001848 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001849 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001850 break;
1851
1852 default:
1853 assert(false && "Improper first standard conversion");
1854 break;
1855 }
1856
1857 // Perform the second implicit conversion
1858 switch (SCS.Second) {
1859 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001860 // If both sides are functions (or pointers/references to them), there could
1861 // be incompatible exception declarations.
1862 if (CheckExceptionSpecCompatibility(From, ToType))
1863 return true;
1864 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001865 break;
1866
Douglas Gregor43c79c22009-12-09 00:47:37 +00001867 case ICK_NoReturn_Adjustment:
1868 // If both sides are functions (or pointers/references to them), there could
1869 // be incompatible exception declarations.
1870 if (CheckExceptionSpecCompatibility(From, ToType))
1871 return true;
1872
1873 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
John McCall2de56d12010-08-25 11:45:40 +00001874 CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001875 break;
1876
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001877 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001878 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001879 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001880 break;
1881
1882 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001883 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001884 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001885 break;
1886
1887 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001888 case ICK_Complex_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001889 ImpCastExprToType(From, ToType, CK_Unknown);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001890 break;
1891
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001892 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001893 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00001894 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001895 else
John McCall2de56d12010-08-25 11:45:40 +00001896 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001897 break;
1898
Douglas Gregorf9201e02009-02-11 23:02:49 +00001899 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001900 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001901 break;
1902
Anders Carlsson61faec12009-09-12 04:46:44 +00001903 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001904 if (SCS.IncompatibleObjC) {
1905 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001906 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001907 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001908 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001909 << From->getSourceRange();
1910 }
1911
Anders Carlsson61faec12009-09-12 04:46:44 +00001912
John McCall2de56d12010-08-25 11:45:40 +00001913 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00001914 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001915 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001916 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001917 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001918 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001919 }
1920
1921 case ICK_Pointer_Member: {
John McCall2de56d12010-08-25 11:45:40 +00001922 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00001923 CXXCastPath BasePath;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001924 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1925 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001926 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001927 if (CheckExceptionSpecCompatibility(From, ToType))
1928 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001929 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001930 break;
1931 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001932 case ICK_Boolean_Conversion: {
John McCall2de56d12010-08-25 11:45:40 +00001933 CastKind Kind = CK_Unknown;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001934 if (FromType->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00001935 Kind = CK_MemberPointerToBoolean;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001936
1937 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001938 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001939 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001940
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001941 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00001942 CXXCastPath BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001943 if (CheckDerivedToBaseConversion(From->getType(),
1944 ToType.getNonReferenceType(),
1945 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001946 From->getSourceRange(),
1947 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001948 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001949 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001950
Sebastian Redl906082e2010-07-20 04:20:21 +00001951 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00001952 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00001953 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001954 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001955 }
1956
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001957 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001958 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001959 break;
1960
1961 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00001962 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001963 break;
1964
1965 case ICK_Complex_Real:
John McCall2de56d12010-08-25 11:45:40 +00001966 ImpCastExprToType(From, ToType, CK_Unknown);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001967 break;
1968
1969 case ICK_Lvalue_To_Rvalue:
1970 case ICK_Array_To_Pointer:
1971 case ICK_Function_To_Pointer:
1972 case ICK_Qualification:
1973 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001974 assert(false && "Improper second standard conversion");
1975 break;
1976 }
1977
1978 switch (SCS.Third) {
1979 case ICK_Identity:
1980 // Nothing to do.
1981 break;
1982
Sebastian Redl906082e2010-07-20 04:20:21 +00001983 case ICK_Qualification: {
1984 // The qualification keeps the category of the inner expression, unless the
1985 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00001986 ExprValueKind VK = ToType->isReferenceType() ?
1987 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00001988 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00001989 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00001990
1991 if (SCS.DeprecatedStringLiteralToCharPtr)
1992 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1993 << ToType.getNonReferenceType();
1994
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001995 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00001996 }
1997
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001998 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001999 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002000 break;
2001 }
2002
2003 return false;
2004}
2005
John McCall60d7b3a2010-08-24 06:29:42 +00002006ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +00002007 SourceLocation KWLoc,
2008 SourceLocation LParen,
John McCallb3d87482010-08-24 05:47:05 +00002009 ParsedType Ty,
Sebastian Redl64b45f72009-01-05 20:52:13 +00002010 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002011 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002013 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2014 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002015 // to be complete, an array of unknown bound, or void.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002016 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002017 QualType E = T;
2018 if (T->isIncompleteArrayType())
2019 E = Context.getAsArrayType(T)->getElementType();
2020 if (!T->isVoidType() &&
2021 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002022 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002023 return ExprError();
2024 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002025
2026 // There is no point in eagerly computing the value. The traits are designed
2027 // to be used from type trait templates, so Ty will be a template parameter
2028 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002029 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
2030 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002031}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002032
2033QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00002034 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002035 const char *OpSpelling = isIndirect ? "->*" : ".*";
2036 // C++ 5.5p2
2037 // The binary operator .* [p3: ->*] binds its second operand, which shall
2038 // be of type "pointer to member of T" (where T is a completely-defined
2039 // class type) [...]
2040 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002041 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002042 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002043 Diag(Loc, diag::err_bad_memptr_rhs)
2044 << OpSpelling << RType << rex->getSourceRange();
2045 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002046 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002047
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002048 QualType Class(MemPtr->getClass(), 0);
2049
Sebastian Redl59fc2692010-04-10 10:14:54 +00002050 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
2051 return QualType();
2052
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002053 // C++ 5.5p2
2054 // [...] to its first operand, which shall be of class T or of a class of
2055 // which T is an unambiguous and accessible base class. [p3: a pointer to
2056 // such a class]
2057 QualType LType = lex->getType();
2058 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002059 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002060 LType = Ptr->getPointeeType().getNonReferenceType();
2061 else {
2062 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002063 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002064 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002065 return QualType();
2066 }
2067 }
2068
Douglas Gregora4923eb2009-11-16 21:35:15 +00002069 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002070 // If we want to check the hierarchy, we need a complete type.
2071 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2072 << OpSpelling << (int)isIndirect)) {
2073 return QualType();
2074 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002075 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002076 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002077 // FIXME: Would it be useful to print full ambiguity paths, or is that
2078 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002079 if (!IsDerivedFrom(LType, Class, Paths) ||
2080 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2081 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002082 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002083 return QualType();
2084 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002085 // Cast LHS to type of use.
2086 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002087 ExprValueKind VK =
2088 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002089
John McCallf871d0c2010-08-07 06:22:56 +00002090 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002091 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002092 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002093 }
2094
Douglas Gregored8abf12010-07-08 06:14:04 +00002095 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002096 // Diagnose use of pointer-to-member type which when used as
2097 // the functional cast in a pointer-to-member expression.
2098 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2099 return QualType();
2100 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002101 // C++ 5.5p2
2102 // The result is an object or a function of the type specified by the
2103 // second operand.
2104 // The cv qualifiers are the union of those in the pointer and the left side,
2105 // in accordance with 5.5p5 and 5.2.5.
2106 // FIXME: This returns a dereferenced member function pointer as a normal
2107 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002108 // calling them. There's also a GCC extension to get a function pointer to the
2109 // thing, which is another complication, because this type - unlike the type
2110 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002111 // argument.
2112 // We probably need a "MemberFunctionClosureType" or something like that.
2113 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002114 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002115 return Result;
2116}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002117
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002118/// \brief Try to convert a type to another according to C++0x 5.16p3.
2119///
2120/// This is part of the parameter validation for the ? operator. If either
2121/// value operand is a class type, the two operands are attempted to be
2122/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002123/// It returns true if the program is ill-formed and has already been diagnosed
2124/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002125static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2126 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002127 bool &HaveConversion,
2128 QualType &ToType) {
2129 HaveConversion = false;
2130 ToType = To->getType();
2131
2132 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2133 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002134 // C++0x 5.16p3
2135 // The process for determining whether an operand expression E1 of type T1
2136 // can be converted to match an operand expression E2 of type T2 is defined
2137 // as follows:
2138 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002139 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2140 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002141 // E1 can be converted to match E2 if E1 can be implicitly converted to
2142 // type "lvalue reference to T2", subject to the constraint that in the
2143 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002144 QualType T = Self.Context.getLValueReferenceType(ToType);
2145 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2146
2147 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2148 if (InitSeq.isDirectReferenceBinding()) {
2149 ToType = T;
2150 HaveConversion = true;
2151 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002152 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002153
2154 if (InitSeq.isAmbiguous())
2155 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002156 }
John McCallb1bdc622010-02-25 01:37:24 +00002157
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002158 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2159 // -- if E1 and E2 have class type, and the underlying class types are
2160 // the same or one is a base class of the other:
2161 QualType FTy = From->getType();
2162 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002163 const RecordType *FRec = FTy->getAs<RecordType>();
2164 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002165 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2166 Self.IsDerivedFrom(FTy, TTy);
2167 if (FRec && TRec &&
2168 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002169 // E1 can be converted to match E2 if the class of T2 is the
2170 // same type as, or a base class of, the class of T1, and
2171 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002172 if (FRec == TRec || FDerivedFromT) {
2173 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002174 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2175 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2176 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2177 HaveConversion = true;
2178 return false;
2179 }
2180
2181 if (InitSeq.isAmbiguous())
2182 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2183 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002184 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002185
2186 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002187 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002188
2189 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2190 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002191 // if E2 were converted to an rvalue (or the type it has, if E2 is
2192 // an rvalue).
2193 //
2194 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2195 // to the array-to-pointer or function-to-pointer conversions.
2196 if (!TTy->getAs<TagType>())
2197 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002198
2199 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2200 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2201 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2202 ToType = TTy;
2203 if (InitSeq.isAmbiguous())
2204 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2205
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002206 return false;
2207}
2208
2209/// \brief Try to find a common type for two according to C++0x 5.16p5.
2210///
2211/// This is part of the parameter validation for the ? operator. If either
2212/// value operand is a class type, overload resolution is used to find a
2213/// conversion to a common type.
2214static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2215 SourceLocation Loc) {
2216 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002217 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002218 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002219
2220 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002221 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002222 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002223 // We found a match. Perform the conversions on the arguments and move on.
2224 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002225 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002226 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002227 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002228 break;
2229 return false;
2230
Douglas Gregor20093b42009-12-09 23:02:17 +00002231 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002232 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2233 << LHS->getType() << RHS->getType()
2234 << LHS->getSourceRange() << RHS->getSourceRange();
2235 return true;
2236
Douglas Gregor20093b42009-12-09 23:02:17 +00002237 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002238 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2239 << LHS->getType() << RHS->getType()
2240 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002241 // FIXME: Print the possible common types by printing the return types of
2242 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002243 break;
2244
Douglas Gregor20093b42009-12-09 23:02:17 +00002245 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002246 assert(false && "Conditional operator has only built-in overloads");
2247 break;
2248 }
2249 return true;
2250}
2251
Sebastian Redl76458502009-04-17 16:30:52 +00002252/// \brief Perform an "extended" implicit conversion as returned by
2253/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002254static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2255 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2256 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2257 SourceLocation());
2258 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002259 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002260 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002261 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002262
2263 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002264 return false;
2265}
2266
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002267/// \brief Check the operands of ?: under C++ semantics.
2268///
2269/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2270/// extension. In this case, LHS == Cond. (But they're not aliases.)
2271QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2272 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002273 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2274 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002275
2276 // C++0x 5.16p1
2277 // The first expression is contextually converted to bool.
2278 if (!Cond->isTypeDependent()) {
2279 if (CheckCXXBooleanCondition(Cond))
2280 return QualType();
2281 }
2282
2283 // Either of the arguments dependent?
2284 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2285 return Context.DependentTy;
2286
2287 // C++0x 5.16p2
2288 // If either the second or the third operand has type (cv) void, ...
2289 QualType LTy = LHS->getType();
2290 QualType RTy = RHS->getType();
2291 bool LVoid = LTy->isVoidType();
2292 bool RVoid = RTy->isVoidType();
2293 if (LVoid || RVoid) {
2294 // ... then the [l2r] conversions are performed on the second and third
2295 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002296 DefaultFunctionArrayLvalueConversion(LHS);
2297 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002298 LTy = LHS->getType();
2299 RTy = RHS->getType();
2300
2301 // ... and one of the following shall hold:
2302 // -- The second or the third operand (but not both) is a throw-
2303 // expression; the result is of the type of the other and is an rvalue.
2304 bool LThrow = isa<CXXThrowExpr>(LHS);
2305 bool RThrow = isa<CXXThrowExpr>(RHS);
2306 if (LThrow && !RThrow)
2307 return RTy;
2308 if (RThrow && !LThrow)
2309 return LTy;
2310
2311 // -- Both the second and third operands have type void; the result is of
2312 // type void and is an rvalue.
2313 if (LVoid && RVoid)
2314 return Context.VoidTy;
2315
2316 // Neither holds, error.
2317 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2318 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2319 << LHS->getSourceRange() << RHS->getSourceRange();
2320 return QualType();
2321 }
2322
2323 // Neither is void.
2324
2325 // C++0x 5.16p3
2326 // Otherwise, if the second and third operand have different types, and
2327 // either has (cv) class type, and attempt is made to convert each of those
2328 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002329 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002330 (LTy->isRecordType() || RTy->isRecordType())) {
2331 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2332 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002333 QualType L2RType, R2LType;
2334 bool HaveL2R, HaveR2L;
2335 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002336 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002337 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002338 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002339
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002340 // If both can be converted, [...] the program is ill-formed.
2341 if (HaveL2R && HaveR2L) {
2342 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2343 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2344 return QualType();
2345 }
2346
2347 // If exactly one conversion is possible, that conversion is applied to
2348 // the chosen operand and the converted operands are used in place of the
2349 // original operands for the remainder of this section.
2350 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002351 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002352 return QualType();
2353 LTy = LHS->getType();
2354 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002355 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002356 return QualType();
2357 RTy = RHS->getType();
2358 }
2359 }
2360
2361 // C++0x 5.16p4
2362 // If the second and third operands are lvalues and have the same type,
2363 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002364 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002365 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2366 RHS->isLvalue(Context) == Expr::LV_Valid)
2367 return LTy;
2368
2369 // C++0x 5.16p5
2370 // Otherwise, the result is an rvalue. If the second and third operands
2371 // do not have the same type, and either has (cv) class type, ...
2372 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2373 // ... overload resolution is used to determine the conversions (if any)
2374 // to be applied to the operands. If the overload resolution fails, the
2375 // program is ill-formed.
2376 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2377 return QualType();
2378 }
2379
2380 // C++0x 5.16p6
2381 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2382 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002383 DefaultFunctionArrayLvalueConversion(LHS);
2384 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002385 LTy = LHS->getType();
2386 RTy = RHS->getType();
2387
2388 // After those conversions, one of the following shall hold:
2389 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002390 // is of that type. If the operands have class type, the result
2391 // is a prvalue temporary of the result type, which is
2392 // copy-initialized from either the second operand or the third
2393 // operand depending on the value of the first operand.
2394 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2395 if (LTy->isRecordType()) {
2396 // The operands have class type. Make a temporary copy.
2397 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCall60d7b3a2010-08-24 06:29:42 +00002398 ExprResult LHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorb65a4582010-05-19 23:40:50 +00002399 SourceLocation(),
2400 Owned(LHS));
2401 if (LHSCopy.isInvalid())
2402 return QualType();
2403
John McCall60d7b3a2010-08-24 06:29:42 +00002404 ExprResult RHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorb65a4582010-05-19 23:40:50 +00002405 SourceLocation(),
2406 Owned(RHS));
2407 if (RHSCopy.isInvalid())
2408 return QualType();
2409
2410 LHS = LHSCopy.takeAs<Expr>();
2411 RHS = RHSCopy.takeAs<Expr>();
2412 }
2413
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002414 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002415 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002416
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002417 // Extension: conditional operator involving vector types.
2418 if (LTy->isVectorType() || RTy->isVectorType())
2419 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2420
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002421 // -- The second and third operands have arithmetic or enumeration type;
2422 // the usual arithmetic conversions are performed to bring them to a
2423 // common type, and the result is of that type.
2424 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2425 UsualArithmeticConversions(LHS, RHS);
2426 return LHS->getType();
2427 }
2428
2429 // -- The second and third operands have pointer type, or one has pointer
2430 // type and the other is a null pointer constant; pointer conversions
2431 // and qualification conversions are performed to bring them to their
2432 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002433 // -- The second and third operands have pointer to member type, or one has
2434 // pointer to member type and the other is a null pointer constant;
2435 // pointer to member conversions and qualification conversions are
2436 // performed to bring them to a common type, whose cv-qualification
2437 // shall match the cv-qualification of either the second or the third
2438 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002439 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002440 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002441 isSFINAEContext()? 0 : &NonStandardCompositeType);
2442 if (!Composite.isNull()) {
2443 if (NonStandardCompositeType)
2444 Diag(QuestionLoc,
2445 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2446 << LTy << RTy << Composite
2447 << LHS->getSourceRange() << RHS->getSourceRange();
2448
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002449 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002450 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002451
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002452 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002453 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2454 if (!Composite.isNull())
2455 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002456
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002457 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2458 << LHS->getType() << RHS->getType()
2459 << LHS->getSourceRange() << RHS->getSourceRange();
2460 return QualType();
2461}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002462
2463/// \brief Find a merged pointer type and convert the two expressions to it.
2464///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002465/// This finds the composite pointer type (or member pointer type) for @p E1
2466/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2467/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002468/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002469///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002470/// \param Loc The location of the operator requiring these two expressions to
2471/// be converted to the composite pointer type.
2472///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002473/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2474/// a non-standard (but still sane) composite type to which both expressions
2475/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2476/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002477QualType Sema::FindCompositePointerType(SourceLocation Loc,
2478 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002479 bool *NonStandardCompositeType) {
2480 if (NonStandardCompositeType)
2481 *NonStandardCompositeType = false;
2482
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002483 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2484 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002486 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2487 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002488 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002489
2490 // C++0x 5.9p2
2491 // Pointer conversions and qualification conversions are performed on
2492 // pointer operands to bring them to their composite pointer type. If
2493 // one operand is a null pointer constant, the composite pointer type is
2494 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002495 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002496 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002497 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002498 else
John McCall2de56d12010-08-25 11:45:40 +00002499 ImpCastExprToType(E1, T2, CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002500 return T2;
2501 }
Douglas Gregorce940492009-09-25 04:25:58 +00002502 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002503 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002504 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002505 else
John McCall2de56d12010-08-25 11:45:40 +00002506 ImpCastExprToType(E2, T1, CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002507 return T1;
2508 }
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Douglas Gregor20b3e992009-08-24 17:42:35 +00002510 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002511 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2512 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002513 return QualType();
2514
2515 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2516 // the other has type "pointer to cv2 T" and the composite pointer type is
2517 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2518 // Otherwise, the composite pointer type is a pointer type similar to the
2519 // type of one of the operands, with a cv-qualification signature that is
2520 // the union of the cv-qualification signatures of the operand types.
2521 // In practice, the first part here is redundant; it's subsumed by the second.
2522 // What we do here is, we build the two possible composite types, and try the
2523 // conversions in both directions. If only one works, or if the two composite
2524 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002525 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002526 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2527 QualifierVector QualifierUnion;
2528 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2529 ContainingClassVector;
2530 ContainingClassVector MemberOfClass;
2531 QualType Composite1 = Context.getCanonicalType(T1),
2532 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002533 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002534 do {
2535 const PointerType *Ptr1, *Ptr2;
2536 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2537 (Ptr2 = Composite2->getAs<PointerType>())) {
2538 Composite1 = Ptr1->getPointeeType();
2539 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002540
2541 // If we're allowed to create a non-standard composite type, keep track
2542 // of where we need to fill in additional 'const' qualifiers.
2543 if (NonStandardCompositeType &&
2544 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2545 NeedConstBefore = QualifierUnion.size();
2546
Douglas Gregor20b3e992009-08-24 17:42:35 +00002547 QualifierUnion.push_back(
2548 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2549 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2550 continue;
2551 }
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Douglas Gregor20b3e992009-08-24 17:42:35 +00002553 const MemberPointerType *MemPtr1, *MemPtr2;
2554 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2555 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2556 Composite1 = MemPtr1->getPointeeType();
2557 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002558
2559 // If we're allowed to create a non-standard composite type, keep track
2560 // of where we need to fill in additional 'const' qualifiers.
2561 if (NonStandardCompositeType &&
2562 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2563 NeedConstBefore = QualifierUnion.size();
2564
Douglas Gregor20b3e992009-08-24 17:42:35 +00002565 QualifierUnion.push_back(
2566 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2567 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2568 MemPtr2->getClass()));
2569 continue;
2570 }
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Douglas Gregor20b3e992009-08-24 17:42:35 +00002572 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002573
Douglas Gregor20b3e992009-08-24 17:42:35 +00002574 // Cannot unwrap any more types.
2575 break;
2576 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002577
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002578 if (NeedConstBefore && NonStandardCompositeType) {
2579 // Extension: Add 'const' to qualifiers that come before the first qualifier
2580 // mismatch, so that our (non-standard!) composite type meets the
2581 // requirements of C++ [conv.qual]p4 bullet 3.
2582 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2583 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2584 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2585 *NonStandardCompositeType = true;
2586 }
2587 }
2588 }
2589
Douglas Gregor20b3e992009-08-24 17:42:35 +00002590 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002591 ContainingClassVector::reverse_iterator MOC
2592 = MemberOfClass.rbegin();
2593 for (QualifierVector::reverse_iterator
2594 I = QualifierUnion.rbegin(),
2595 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002596 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002597 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002598 if (MOC->first && MOC->second) {
2599 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002600 Composite1 = Context.getMemberPointerType(
2601 Context.getQualifiedType(Composite1, Quals),
2602 MOC->first);
2603 Composite2 = Context.getMemberPointerType(
2604 Context.getQualifiedType(Composite2, Quals),
2605 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002606 } else {
2607 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002608 Composite1
2609 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2610 Composite2
2611 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002612 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002613 }
2614
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002615 // Try to convert to the first composite pointer type.
2616 InitializedEntity Entity1
2617 = InitializedEntity::InitializeTemporary(Composite1);
2618 InitializationKind Kind
2619 = InitializationKind::CreateCopy(Loc, SourceLocation());
2620 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2621 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002623 if (E1ToC1 && E2ToC1) {
2624 // Conversion to Composite1 is viable.
2625 if (!Context.hasSameType(Composite1, Composite2)) {
2626 // Composite2 is a different type from Composite1. Check whether
2627 // Composite2 is also viable.
2628 InitializedEntity Entity2
2629 = InitializedEntity::InitializeTemporary(Composite2);
2630 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2631 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2632 if (E1ToC2 && E2ToC2) {
2633 // Both Composite1 and Composite2 are viable and are different;
2634 // this is an ambiguity.
2635 return QualType();
2636 }
2637 }
2638
2639 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002640 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002641 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002642 if (E1Result.isInvalid())
2643 return QualType();
2644 E1 = E1Result.takeAs<Expr>();
2645
2646 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002647 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002648 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002649 if (E2Result.isInvalid())
2650 return QualType();
2651 E2 = E2Result.takeAs<Expr>();
2652
2653 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002654 }
2655
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002656 // Check whether Composite2 is viable.
2657 InitializedEntity Entity2
2658 = InitializedEntity::InitializeTemporary(Composite2);
2659 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2660 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2661 if (!E1ToC2 || !E2ToC2)
2662 return QualType();
2663
2664 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00002665 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002666 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002667 if (E1Result.isInvalid())
2668 return QualType();
2669 E1 = E1Result.takeAs<Expr>();
2670
2671 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00002672 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002673 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002674 if (E2Result.isInvalid())
2675 return QualType();
2676 E2 = E2Result.takeAs<Expr>();
2677
2678 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002679}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002680
John McCall60d7b3a2010-08-24 06:29:42 +00002681ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002682 if (!Context.getLangOptions().CPlusPlus)
2683 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Douglas Gregor51326552009-12-24 18:51:59 +00002685 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2686
Ted Kremenek6217b802009-07-29 21:53:49 +00002687 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002688 if (!RT)
2689 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002691 // If this is the result of a call or an Objective-C message send expression,
2692 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002693 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002694 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00002695 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002696 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2697 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2698 if (MD->getResultType()->isReferenceType())
2699 return Owned(E);
2700 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00002701 }
John McCall86ff3082010-02-04 22:26:26 +00002702
2703 // That should be enough to guarantee that this type is complete.
2704 // If it has a trivial destructor, we can avoid the extra copy.
2705 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00002706 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00002707 return Owned(E);
2708
Douglas Gregordb89f282010-07-01 22:47:18 +00002709 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00002710 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00002711 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002712 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002713 CheckDestructorAccess(E->getExprLoc(), Destructor,
2714 PDiag(diag::err_access_dtor_temp)
2715 << E->getType());
2716 }
Anders Carlssondef11992009-05-30 20:36:53 +00002717 // FIXME: Add the temporary to the temporaries vector.
2718 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2719}
2720
Anders Carlsson0ece4912009-12-15 20:51:39 +00002721Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002722 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002723
John McCall323ed742010-05-06 08:58:33 +00002724 // Check any implicit conversions within the expression.
2725 CheckImplicitConversions(SubExpr);
2726
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002727 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2728 assert(ExprTemporaries.size() >= FirstTemporary);
2729 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002730 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002732 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002733 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002734 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002735 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2736 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002738 return E;
2739}
2740
John McCall60d7b3a2010-08-24 06:29:42 +00002741ExprResult
2742Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00002743 if (SubExpr.isInvalid())
2744 return ExprError();
2745
2746 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2747}
2748
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002749FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2750 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2751 assert(ExprTemporaries.size() >= FirstTemporary);
2752
2753 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2754 CXXTemporary **Temporaries =
2755 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2756
2757 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2758
2759 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2760 ExprTemporaries.end());
2761
2762 return E;
2763}
2764
John McCall60d7b3a2010-08-24 06:29:42 +00002765ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002766Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00002767 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00002768 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002769 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002770 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002771 if (Result.isInvalid()) return ExprError();
2772 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002773
John McCall9ae2f072010-08-23 23:25:46 +00002774 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002775 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002776 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002777 // If we have a pointer to a dependent type and are using the -> operator,
2778 // the object type is the type that the pointer points to. We might still
2779 // have enough information about that type to do something useful.
2780 if (OpKind == tok::arrow)
2781 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2782 BaseType = Ptr->getPointeeType();
2783
John McCallb3d87482010-08-24 05:47:05 +00002784 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00002785 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00002786 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002787 }
Mike Stump1eb44332009-09-09 15:08:12 +00002788
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002789 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002790 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002791 // returned, with the original second operand.
2792 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002793 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002794 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002795 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002796 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002797
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002798 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00002799 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
2800 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002801 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00002802 Base = Result.get();
2803 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00002804 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00002805 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00002806 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002807 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002808 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002809 for (unsigned i = 0; i < Locations.size(); i++)
2810 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002811 return ExprError();
2812 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002813 }
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Douglas Gregor31658df2009-11-20 19:58:21 +00002815 if (BaseType->isPointerType())
2816 BaseType = BaseType->getPointeeType();
2817 }
Mike Stump1eb44332009-09-09 15:08:12 +00002818
2819 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002820 // vector types or Objective-C interfaces. Just return early and let
2821 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002822 if (!BaseType->isRecordType()) {
2823 // C++ [basic.lookup.classref]p2:
2824 // [...] If the type of the object expression is of pointer to scalar
2825 // type, the unqualified-id is looked up in the context of the complete
2826 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002827 //
2828 // This also indicates that we should be parsing a
2829 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00002830 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002831 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00002832 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002833 }
Mike Stump1eb44332009-09-09 15:08:12 +00002834
Douglas Gregor03c57052009-11-17 05:17:33 +00002835 // The object type must be complete (or dependent).
2836 if (!BaseType->isDependentType() &&
2837 RequireCompleteType(OpLoc, BaseType,
2838 PDiag(diag::err_incomplete_member_access)))
2839 return ExprError();
2840
Douglas Gregorc68afe22009-09-03 21:38:09 +00002841 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002842 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002843 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002844 // type C (or of pointer to a class type C), the unqualified-id is looked
2845 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00002846 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00002847 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002848}
2849
John McCall60d7b3a2010-08-24 06:29:42 +00002850ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002851 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00002852 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00002853 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
2854 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00002855 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002856
2857 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00002858 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00002859 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00002860 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00002861 /*CommaLocs*/ 0,
2862 /*RPLoc*/ ExpectedLParenLoc);
2863}
Douglas Gregord4dca082010-02-24 18:44:31 +00002864
John McCall60d7b3a2010-08-24 06:29:42 +00002865ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002866 SourceLocation OpLoc,
2867 tok::TokenKind OpKind,
2868 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002869 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002870 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002871 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002872 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002873 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002874 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002875
2876 // C++ [expr.pseudo]p2:
2877 // The left-hand side of the dot operator shall be of scalar type. The
2878 // left-hand side of the arrow operator shall be of pointer to scalar type.
2879 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00002880 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002881 if (OpKind == tok::arrow) {
2882 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2883 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00002884 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002885 // The user wrote "p->" when she probably meant "p."; fix it.
2886 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2887 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002888 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002889 if (isSFINAEContext())
2890 return ExprError();
2891
2892 OpKind = tok::period;
2893 }
2894 }
2895
2896 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2897 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00002898 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002899 return ExprError();
2900 }
2901
2902 // C++ [expr.pseudo]p2:
2903 // [...] The cv-unqualified versions of the object type and of the type
2904 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002905 if (DestructedTypeInfo) {
2906 QualType DestructedType = DestructedTypeInfo->getType();
2907 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002908 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002909 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2910 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2911 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00002912 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002913 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002914
2915 // Recover by setting the destructed type to the object type.
2916 DestructedType = ObjectType;
2917 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2918 DestructedTypeStart);
2919 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2920 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002921 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002922
Douglas Gregorb57fb492010-02-24 22:38:50 +00002923 // C++ [expr.pseudo]p2:
2924 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2925 // form
2926 //
2927 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2928 //
2929 // shall designate the same scalar type.
2930 if (ScopeTypeInfo) {
2931 QualType ScopeType = ScopeTypeInfo->getType();
2932 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00002933 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002934
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002935 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00002936 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00002937 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002938 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002939
2940 ScopeType = QualType();
2941 ScopeTypeInfo = 0;
2942 }
2943 }
2944
John McCall9ae2f072010-08-23 23:25:46 +00002945 Expr *Result
2946 = new (Context) CXXPseudoDestructorExpr(Context, Base,
2947 OpKind == tok::arrow, OpLoc,
2948 SS.getScopeRep(), SS.getRange(),
2949 ScopeTypeInfo,
2950 CCLoc,
2951 TildeLoc,
2952 Destructed);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002953
Douglas Gregorb57fb492010-02-24 22:38:50 +00002954 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00002955 return Owned(Result);
Douglas Gregorb57fb492010-02-24 22:38:50 +00002956
John McCall9ae2f072010-08-23 23:25:46 +00002957 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00002958}
2959
John McCall60d7b3a2010-08-24 06:29:42 +00002960ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00002961 SourceLocation OpLoc,
2962 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002963 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002964 UnqualifiedId &FirstTypeName,
2965 SourceLocation CCLoc,
2966 SourceLocation TildeLoc,
2967 UnqualifiedId &SecondTypeName,
2968 bool HasTrailingLParen) {
2969 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2970 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2971 "Invalid first type name in pseudo-destructor");
2972 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2973 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2974 "Invalid second type name in pseudo-destructor");
2975
Douglas Gregor77549082010-02-24 21:29:12 +00002976 // C++ [expr.pseudo]p2:
2977 // The left-hand side of the dot operator shall be of scalar type. The
2978 // left-hand side of the arrow operator shall be of pointer to scalar type.
2979 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00002980 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00002981 if (OpKind == tok::arrow) {
2982 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2983 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002984 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002985 // The user wrote "p->" when she probably meant "p."; fix it.
2986 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002987 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002988 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002989 if (isSFINAEContext())
2990 return ExprError();
2991
2992 OpKind = tok::period;
2993 }
2994 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002995
2996 // Compute the object type that we should use for name lookup purposes. Only
2997 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00002998 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002999 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003000 if (const Type *T = ObjectType->getAs<RecordType>())
3001 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3002 else if (ObjectType->isDependentType())
3003 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003004 }
Douglas Gregor77549082010-02-24 21:29:12 +00003005
Douglas Gregorb57fb492010-02-24 22:38:50 +00003006 // Convert the name of the type being destructed (following the ~) into a
3007 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003008 QualType DestructedType;
3009 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003010 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003011 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003012 ParsedType T = getTypeName(*SecondTypeName.Identifier,
3013 SecondTypeName.StartLocation,
3014 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003015 if (!T &&
3016 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3017 (!SS.isSet() && ObjectType->isDependentType()))) {
3018 // The name of the type being destroyed is a dependent name, and we
3019 // couldn't find anything useful in scope. Just store the identifier and
3020 // it's location, and we'll perform (qualified) name lookup again at
3021 // template instantiation time.
3022 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3023 SecondTypeName.StartLocation);
3024 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00003025 Diag(SecondTypeName.StartLocation,
3026 diag::err_pseudo_dtor_destructor_non_type)
3027 << SecondTypeName.Identifier << ObjectType;
3028 if (isSFINAEContext())
3029 return ExprError();
3030
3031 // Recover by assuming we had the right type all along.
3032 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003033 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003034 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003035 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003036 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003037 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003038 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3039 TemplateId->getTemplateArgs(),
3040 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003041 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003042 TemplateId->TemplateNameLoc,
3043 TemplateId->LAngleLoc,
3044 TemplateArgsPtr,
3045 TemplateId->RAngleLoc);
3046 if (T.isInvalid() || !T.get()) {
3047 // Recover by assuming we had the right type all along.
3048 DestructedType = ObjectType;
3049 } else
3050 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003051 }
3052
Douglas Gregorb57fb492010-02-24 22:38:50 +00003053 // If we've performed some kind of recovery, (re-)build the type source
3054 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003055 if (!DestructedType.isNull()) {
3056 if (!DestructedTypeInfo)
3057 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003058 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003059 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3060 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003061
3062 // Convert the name of the scope type (the type prior to '::') into a type.
3063 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003064 QualType ScopeType;
3065 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3066 FirstTypeName.Identifier) {
3067 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003068 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3069 FirstTypeName.StartLocation,
3070 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003071 if (!T) {
3072 Diag(FirstTypeName.StartLocation,
3073 diag::err_pseudo_dtor_destructor_non_type)
3074 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00003075
Douglas Gregorb57fb492010-02-24 22:38:50 +00003076 if (isSFINAEContext())
3077 return ExprError();
3078
3079 // Just drop this type. It's unnecessary anyway.
3080 ScopeType = QualType();
3081 } else
3082 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003083 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003084 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003085 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003086 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3087 TemplateId->getTemplateArgs(),
3088 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003089 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003090 TemplateId->TemplateNameLoc,
3091 TemplateId->LAngleLoc,
3092 TemplateArgsPtr,
3093 TemplateId->RAngleLoc);
3094 if (T.isInvalid() || !T.get()) {
3095 // Recover by dropping this type.
3096 ScopeType = QualType();
3097 } else
3098 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003099 }
3100 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003101
3102 if (!ScopeType.isNull() && !ScopeTypeInfo)
3103 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3104 FirstTypeName.StartLocation);
3105
3106
John McCall9ae2f072010-08-23 23:25:46 +00003107 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003108 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003109 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003110}
3111
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003112CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003113 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003114 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003115 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3116 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003117 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3118
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003119 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003120 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003121 SourceLocation(), Method->getType());
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003122 QualType ResultType = Method->getCallResultType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003123 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3124 CXXMemberCallExpr *CE =
3125 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3126 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003127 return CE;
3128}
3129
John McCall60d7b3a2010-08-24 06:29:42 +00003130ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
John McCall9ae2f072010-08-23 23:25:46 +00003131 if (!FullExpr) return ExprError();
3132 return MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003133}