blob: 1e5735d6f83522c3010afe312bec0eaa5f953df6 [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
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000026#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000027#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
Douglas Gregor124b8782010-02-16 19:09:40 +000030Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
31 IdentifierInfo &II,
32 SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000033 Scope *S, CXXScopeSpec &SS,
Douglas Gregor124b8782010-02-16 19:09:40 +000034 TypeTy *ObjectTypePtr,
35 bool EnteringContext) {
36 // Determine where to perform name lookup.
37
38 // FIXME: This area of the standard is very messy, and the current
39 // wording is rather unclear about which scopes we search for the
40 // destructor name; see core issues 399 and 555. Issue 399 in
41 // particular shows where the current description of destructor name
42 // lookup is completely out of line with existing practice, e.g.,
43 // this appears to be ill-formed:
44 //
45 // namespace N {
46 // template <typename T> struct S {
47 // ~S();
48 // };
49 // }
50 //
51 // void f(N::S<int>* s) {
52 // s->N::S<int>::~S();
53 // }
54 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000055 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000056 // For this reason, we're currently only doing the C++03 version of this
57 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000058 QualType SearchType;
59 DeclContext *LookupCtx = 0;
60 bool isDependent = false;
61 bool LookInScope = false;
62
63 // If we have an object type, it's because we are in a
64 // pseudo-destructor-expression or a member access expression, and
65 // we know what type we're looking for.
66 if (ObjectTypePtr)
67 SearchType = GetTypeFromParser(ObjectTypePtr);
68
69 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000070 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
71
72 bool AlreadySearched = false;
73 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000074 // C++ [basic.lookup.qual]p6:
75 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
76 // the type-names are looked up as types in the scope designated by the
77 // nested-name-specifier. In a qualified-id of the form:
78 //
79 // ::[opt] nested-name-specifier ̃ class-name
80 //
81 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000082 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000083 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000085 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000086 // the class-names are looked up as types in the scope designated by
87 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000089 // Here, we check the first case (completely) and determine whether the
90 // code below is permitted to look at the prefix of the
91 // nested-name-specifier.
92 DeclContext *DC = computeDeclContext(SS, EnteringContext);
93 if (DC && DC->isFileContext()) {
94 AlreadySearched = true;
95 LookupCtx = DC;
96 isDependent = false;
97 } else if (DC && isa<CXXRecordDecl>(DC))
98 LookAtPrefix = false;
99
100 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000101 NestedNameSpecifier *Prefix = 0;
102 if (AlreadySearched) {
103 // Nothing left to do.
104 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
105 CXXScopeSpec PrefixSS;
106 PrefixSS.setScopeRep(Prefix);
107 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
108 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000110 LookupCtx = computeDeclContext(SearchType);
111 isDependent = SearchType->isDependentType();
112 } else {
113 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000114 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000115 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000116
Douglas Gregoredc90502010-02-25 04:46:04 +0000117 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 } else if (ObjectTypePtr) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T
122 // of the object expression is of a class type C, the type-name is
123 // also looked up in the scope of class C. At least one of the
124 // lookups shall find a name that refers to (possibly
125 // cv-qualified) T.
126 LookupCtx = computeDeclContext(SearchType);
127 isDependent = SearchType->isDependentType();
128 assert((isDependent || !SearchType->isIncompleteType()) &&
129 "Caller should have completed object type");
130
131 LookInScope = true;
132 } else {
133 // Perform lookup into the current scope (only).
134 LookInScope = true;
135 }
136
137 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
138 for (unsigned Step = 0; Step != 2; ++Step) {
139 // Look for the name first in the computed lookup context (if we
140 // have one) and, if that fails to find a match, in the sope (if
141 // we're allowed to look there).
142 Found.clear();
143 if (Step == 0 && LookupCtx)
144 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000145 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000146 LookupName(Found, S);
147 else
148 continue;
149
150 // FIXME: Should we be suppressing ambiguities here?
151 if (Found.isAmbiguous())
152 return 0;
153
154 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
155 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000156
157 if (SearchType.isNull() || SearchType->isDependentType() ||
158 Context.hasSameUnqualifiedType(T, SearchType)) {
159 // We found our type!
160
161 return T.getAsOpaquePtr();
162 }
163 }
164
165 // If the name that we found is a class template name, and it is
166 // the same name as the template name in the last part of the
167 // nested-name-specifier (if present) or the object type, then
168 // this is the destructor for that class.
169 // FIXME: This is a workaround until we get real drafting for core
170 // issue 399, for which there isn't even an obvious direction.
171 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
172 QualType MemberOfType;
173 if (SS.isSet()) {
174 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
175 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000176 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
177 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000178 }
179 }
180 if (MemberOfType.isNull())
181 MemberOfType = SearchType;
182
183 if (MemberOfType.isNull())
184 continue;
185
186 // We're referring into a class template specialization. If the
187 // class template we found is the same as the template being
188 // specialized, we found what we are looking for.
189 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
190 if (ClassTemplateSpecializationDecl *Spec
191 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
192 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
193 Template->getCanonicalDecl())
194 return MemberOfType.getAsOpaquePtr();
195 }
196
197 continue;
198 }
199
200 // We're referring to an unresolved class template
201 // specialization. Determine whether we class template we found
202 // is the same as the template being specialized or, if we don't
203 // know which template is being specialized, that it at least
204 // has the same name.
205 if (const TemplateSpecializationType *SpecType
206 = MemberOfType->getAs<TemplateSpecializationType>()) {
207 TemplateName SpecName = SpecType->getTemplateName();
208
209 // The class template we found is the same template being
210 // specialized.
211 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
212 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214
215 continue;
216 }
217
218 // The class template we found has the same name as the
219 // (dependent) template name being specialized.
220 if (DependentTemplateName *DepTemplate
221 = SpecName.getAsDependentTemplateName()) {
222 if (DepTemplate->isIdentifier() &&
223 DepTemplate->getIdentifier() == Template->getIdentifier())
224 return MemberOfType.getAsOpaquePtr();
225
226 continue;
227 }
228 }
229 }
230 }
231
232 if (isDependent) {
233 // We didn't find our type, but that's okay: it's dependent
234 // anyway.
235 NestedNameSpecifier *NNS = 0;
236 SourceRange Range;
237 if (SS.isSet()) {
238 NNS = (NestedNameSpecifier *)SS.getScopeRep();
239 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
240 } else {
241 NNS = NestedNameSpecifier::Create(Context, &II);
242 Range = SourceRange(NameLoc);
243 }
244
Abramo Bagnarae4da7a02010-05-19 21:37:53 +0000245 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
246 Range, NameLoc).getAsOpaquePtr();
Douglas Gregor124b8782010-02-16 19:09:40 +0000247 }
248
249 if (ObjectTypePtr)
250 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
251 << &II;
252 else
253 Diag(NameLoc, diag::err_destructor_class_name);
254
255 return 0;
256}
257
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000258/// \brief Build a C++ typeid expression with a type operand.
259Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
260 SourceLocation TypeidLoc,
261 TypeSourceInfo *Operand,
262 SourceLocation RParenLoc) {
263 // C++ [expr.typeid]p4:
264 // The top-level cv-qualifiers of the lvalue expression or the type-id
265 // that is the operand of typeid are always ignored.
266 // If the type of the type-id is a class type or a reference to a class
267 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000268 Qualifiers Quals;
269 QualType T
270 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
271 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000272 if (T->getAs<RecordType>() &&
273 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
274 return ExprError();
Daniel Dunbar380c2132010-05-11 21:32:35 +0000275
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000276 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
277 Operand,
278 SourceRange(TypeidLoc, RParenLoc)));
279}
280
281/// \brief Build a C++ typeid expression with an expression operand.
282Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
283 SourceLocation TypeidLoc,
284 ExprArg Operand,
285 SourceLocation RParenLoc) {
286 bool isUnevaluatedOperand = true;
287 Expr *E = static_cast<Expr *>(Operand.get());
288 if (E && !E->isTypeDependent()) {
289 QualType T = E->getType();
290 if (const RecordType *RecordT = T->getAs<RecordType>()) {
291 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
292 // C++ [expr.typeid]p3:
293 // [...] If the type of the expression is a class type, the class
294 // shall be completely-defined.
295 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
296 return ExprError();
297
298 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000299 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000300 // polymorphic class type [...] [the] expression is an unevaluated
301 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000302 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000303 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000304
305 // We require a vtable to query the type at run time.
306 MarkVTableUsed(TypeidLoc, RecordD);
307 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000308 }
309
310 // C++ [expr.typeid]p4:
311 // [...] If the type of the type-id is a reference to a possibly
312 // cv-qualified type, the result of the typeid expression refers to a
313 // std::type_info object representing the cv-unqualified referenced
314 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000315 Qualifiers Quals;
316 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
317 if (!Context.hasSameType(T, UnqualT)) {
318 T = UnqualT;
Sebastian Redl906082e2010-07-20 04:20:21 +0000319 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000320 Operand.release();
321 Operand = Owned(E);
322 }
323 }
324
325 // If this is an unevaluated operand, clear out the set of
326 // declaration references we have been computing and eliminate any
327 // temporaries introduced in its computation.
328 if (isUnevaluatedOperand)
329 ExprEvalContexts.back().Context = Unevaluated;
330
331 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
332 Operand.takeAs<Expr>(),
333 SourceRange(TypeidLoc, RParenLoc)));
334}
335
336/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000337Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000338Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
339 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000340 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000341 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000342 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000343
Chris Lattner572af492008-11-20 05:51:55 +0000344 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000345 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +0000346 LookupQualifiedName(R, getStdNamespace());
John McCall1bcee0a2009-12-02 08:25:40 +0000347 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000348 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000350
Sebastian Redlc42e1182008-11-11 11:37:55 +0000351 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000352
353 if (isType) {
354 // The operand is a type; handle it as such.
355 TypeSourceInfo *TInfo = 0;
356 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
357 if (T.isNull())
358 return ExprError();
359
360 if (!TInfo)
361 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000362
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000364 }
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 // The operand is an expression.
367 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368}
369
Steve Naroff1b273c42007-09-16 14:56:35 +0000370/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000372Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000373 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000375 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
376 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000377}
Chris Lattner50dd2892008-02-26 00:51:44 +0000378
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000379/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
380Action::OwningExprResult
381Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
382 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
383}
384
Chris Lattner50dd2892008-02-26 00:51:44 +0000385/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000386Action::OwningExprResult
387Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000388 Expr *Ex = E.takeAs<Expr>();
389 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
390 return ExprError();
391 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
392}
393
394/// CheckCXXThrowOperand - Validate the operand of a throw.
395bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
396 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000397 // A throw-expression initializes a temporary object, called the exception
398 // object, the type of which is determined by removing any top-level
399 // cv-qualifiers from the static type of the operand of throw and adjusting
400 // the type from "array of T" or "function returning T" to "pointer to T"
401 // or "pointer to function returning T", [...]
402 if (E->getType().hasQualifiers())
403 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000404 CastCategory(E));
Douglas Gregor154fe982009-12-23 22:04:40 +0000405
Sebastian Redl972041f2009-04-27 20:27:31 +0000406 DefaultFunctionArrayConversion(E);
407
408 // If the type of the exception would be an incomplete type or a pointer
409 // to an incomplete type other than (cv) void the program is ill-formed.
410 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000411 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000412 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000413 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000414 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000415 }
416 if (!isPointer || !Ty->isVoidType()) {
417 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000418 PDiag(isPointer ? diag::err_throw_incomplete_ptr
419 : diag::err_throw_incomplete)
420 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000421 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000422
Douglas Gregorbf422f92010-04-15 18:05:39 +0000423 if (RequireNonAbstractType(ThrowLoc, E->getType(),
424 PDiag(diag::err_throw_abstract_type)
425 << E->getSourceRange()))
426 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000427 }
428
John McCallac418162010-04-22 01:10:34 +0000429 // Initialize the exception result. This implicitly weeds out
430 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000431 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000432 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000433 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
434 /*NRVO=*/false);
John McCallac418162010-04-22 01:10:34 +0000435 OwningExprResult Res = PerformCopyInitialization(Entity,
436 SourceLocation(),
437 Owned(E));
438 if (Res.isInvalid())
439 return true;
440 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000441
Eli Friedman5ed9b932010-06-03 20:39:03 +0000442 // If the exception has class type, we need additional handling.
443 const RecordType *RecordTy = Ty->getAs<RecordType>();
444 if (!RecordTy)
445 return false;
446 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
447
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000448 // If we are throwing a polymorphic class type or pointer thereof,
449 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000450 MarkVTableUsed(ThrowLoc, RD);
451
452 // If the class has a non-trivial destructor, we must be able to call it.
453 if (RD->hasTrivialDestructor())
454 return false;
455
Douglas Gregor1d110e02010-07-01 14:13:13 +0000456 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000457 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000458 if (!Destructor)
459 return false;
460
461 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
462 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000463 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000464 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000465}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000466
Sebastian Redlf53597f2009-03-15 17:47:39 +0000467Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000468 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
469 /// is a non-lvalue expression whose value is the address of the object for
470 /// which the function is called.
471
John McCallea1471e2010-05-20 01:18:31 +0000472 DeclContext *DC = getFunctionLevelDeclContext();
473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000474 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000476 MD->getThisType(Context),
477 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000478
Sebastian Redlf53597f2009-03-15 17:47:39 +0000479 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000480}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000481
482/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
483/// Can be interpreted either as function-style casting ("int(x)")
484/// or class type construction ("ClassType(x,y,z)")
485/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000486Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000487Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
488 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000489 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000490 SourceLocation *CommaLocs,
491 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000492 if (!TypeRep)
493 return ExprError();
494
John McCall9d125032010-01-15 18:39:57 +0000495 TypeSourceInfo *TInfo;
496 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
497 if (!TInfo)
498 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000499 unsigned NumExprs = exprs.size();
500 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000501 SourceLocation TyBeginLoc = TypeRange.getBegin();
502 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
503
Sebastian Redlf53597f2009-03-15 17:47:39 +0000504 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000505 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000506 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000507
508 return Owned(CXXUnresolvedConstructExpr::Create(Context,
509 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000510 LParenLoc,
511 Exprs, NumExprs,
512 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000513 }
514
Anders Carlssonbb60a502009-08-27 03:53:50 +0000515 if (Ty->isArrayType())
516 return ExprError(Diag(TyBeginLoc,
517 diag::err_value_init_for_array_type) << FullRange);
518 if (!Ty->isVoidType() &&
519 RequireCompleteType(TyBeginLoc, Ty,
520 PDiag(diag::err_invalid_incomplete_type_use)
521 << FullRange))
522 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000523
Anders Carlssonbb60a502009-08-27 03:53:50 +0000524 if (RequireNonAbstractType(TyBeginLoc, Ty,
525 diag::err_allocation_of_abstract_type))
526 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000527
528
Douglas Gregor506ae412009-01-16 18:33:17 +0000529 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000530 // If the expression list is a single expression, the type conversion
531 // expression is equivalent (in definedness, and if defined in meaning) to the
532 // corresponding cast expression.
533 //
534 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000535 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000536 CXXBaseSpecifierArray BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000537 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
538 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000539 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000540
541 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000542
Douglas Gregor63982352010-07-13 18:40:04 +0000543 return Owned(new (Context) CXXFunctionalCastExpr(
544 Ty.getNonLValueExprType(Context),
John McCall9d125032010-01-15 18:39:57 +0000545 TInfo, TyBeginLoc, Kind,
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000546 Exprs[0], BasePath,
547 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000548 }
549
Douglas Gregored8abf12010-07-08 06:14:04 +0000550 if (Ty->isRecordType()) {
551 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
552 InitializationKind Kind
553 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
554 LParenLoc, RParenLoc)
555 : InitializationKind::CreateValue(TypeRange.getBegin(),
556 LParenLoc, RParenLoc);
557 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
558 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
559 move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000560
Douglas Gregored8abf12010-07-08 06:14:04 +0000561 // FIXME: Improve AST representation?
562 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000563 }
564
565 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000566 // If the expression list specifies more than a single value, the type shall
567 // be a class with a suitably declared constructor.
568 //
569 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000570 return ExprError(Diag(CommaLocs[0],
571 diag::err_builtin_func_cast_more_than_one_arg)
572 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000573
574 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000575 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000576 // The expression T(), where T is a simple-type-specifier for a non-array
577 // complete object type or the (possibly cv-qualified) void type, creates an
578 // rvalue of the specified type, which is value-initialized.
579 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000580 exprs.release();
Douglas Gregored8abf12010-07-08 06:14:04 +0000581 return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000582}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000583
584
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000585/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
586/// @code new (memory) int[size][4] @endcode
587/// or
588/// @code ::new Foo(23, "hello") @endcode
589/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000590Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000591Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000592 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000593 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000594 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000595 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000596 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000597 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000598 // If the specified type is an array, unwrap it and save the expression.
599 if (D.getNumTypeObjects() > 0 &&
600 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
601 DeclaratorChunk &Chunk = D.getTypeObject(0);
602 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000603 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
604 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000605 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000606 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
607 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000608
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000609 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000610 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000611 }
612
Douglas Gregor043cad22009-09-11 00:18:58 +0000613 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000614 if (ArraySize) {
615 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000616 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
617 break;
618
619 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
620 if (Expr *NumElts = (Expr *)Array.NumElts) {
621 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
622 !NumElts->isIntegerConstantExpr(Context)) {
623 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
624 << NumElts->getSourceRange();
625 return ExprError();
626 }
627 }
628 }
629 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000630
John McCalla93c9342009-12-07 02:54:59 +0000631 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCallbf1a0282010-06-04 23:28:52 +0000632 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
633 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000634 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000635 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000636
637 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000638 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000639 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000640 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000641 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000642 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000643 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000644 D.getSourceRange().getBegin(),
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000645 R,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000646 Owned(ArraySize),
647 ConstructorLParen,
648 move(ConstructorArgs),
649 ConstructorRParen);
650}
651
Mike Stump1eb44332009-09-09 15:08:12 +0000652Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000653Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
654 SourceLocation PlacementLParen,
655 MultiExprArg PlacementArgs,
656 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000657 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000658 QualType AllocType,
659 SourceLocation TypeLoc,
660 SourceRange TypeRange,
661 ExprArg ArraySizeE,
662 SourceLocation ConstructorLParen,
663 MultiExprArg ConstructorArgs,
664 SourceLocation ConstructorRParen) {
665 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000666 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000667
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000668 // Per C++0x [expr.new]p5, the type being constructed may be a
669 // typedef of an array type.
670 if (!ArraySizeE.get()) {
671 if (const ConstantArrayType *Array
672 = Context.getAsConstantArrayType(AllocType)) {
673 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
674 Context.getSizeType(),
675 TypeRange.getEnd()));
676 AllocType = Array->getElementType();
677 }
678 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000679
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000680 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000681
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000682 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
683 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000684 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000685 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000686
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000687 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000688
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000689 OwningExprResult ConvertedSize
690 = ConvertToIntegralOrEnumerationType(StartLoc, move(ArraySizeE),
691 PDiag(diag::err_array_size_not_integral),
692 PDiag(diag::err_array_size_incomplete_type)
693 << ArraySize->getSourceRange(),
694 PDiag(diag::err_array_size_explicit_conversion),
695 PDiag(diag::note_array_size_conversion),
696 PDiag(diag::err_array_size_ambiguous_conversion),
697 PDiag(diag::note_array_size_conversion),
698 PDiag(getLangOptions().CPlusPlus0x? 0
699 : diag::ext_array_size_conversion));
700 if (ConvertedSize.isInvalid())
701 return ExprError();
702
703 ArraySize = ConvertedSize.takeAs<Expr>();
704 ArraySizeE = Owned(ArraySize);
705 SizeType = ArraySize->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000706 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000707 return ExprError();
708
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000709 // Let's see if this is a constant < 0. If so, we reject it out of hand.
710 // We don't care about special rules, so we tell the machinery it's not
711 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000712 if (!ArraySize->isValueDependent()) {
713 llvm::APSInt Value;
714 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
715 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000716 llvm::APInt::getNullValue(Value.getBitWidth()),
717 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000718 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
719 diag::err_typecheck_negative_array_size)
720 << ArraySize->getSourceRange());
Douglas Gregor4bd40312010-07-13 15:54:32 +0000721 } else if (TypeIdParens.isValid()) {
722 // Can't have dynamic array size when the type-id is in parentheses.
723 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
724 << ArraySize->getSourceRange()
725 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
726 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
727
728 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000729 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000730 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000731
Eli Friedman73c39ab2009-10-20 08:27:19 +0000732 ImpCastExprToType(ArraySize, Context.getSizeType(),
733 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000734 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000735
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000736 FunctionDecl *OperatorNew = 0;
737 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000738 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
739 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000740
Sebastian Redl28507842009-02-26 14:39:58 +0000741 if (!AllocType->isDependentType() &&
742 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
743 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000744 SourceRange(PlacementLParen, PlacementRParen),
745 UseGlobal, AllocType, ArraySize, PlaceArgs,
746 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000747 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000748 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000749 if (OperatorNew) {
750 // Add default arguments, if any.
751 const FunctionProtoType *Proto =
752 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000753 VariadicCallType CallType =
754 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000755
756 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
757 Proto, 1, PlaceArgs, NumPlaceArgs,
758 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000759 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000760
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000761 NumPlaceArgs = AllPlaceArgs.size();
762 if (NumPlaceArgs > 0)
763 PlaceArgs = &AllPlaceArgs[0];
764 }
765
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000766 bool Init = ConstructorLParen.isValid();
767 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000768 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000769 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
770 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000771 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
772
Anders Carlsson48c95012010-05-03 15:45:23 +0000773 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000774 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000775 SourceRange InitRange(ConsArgs[0]->getLocStart(),
776 ConsArgs[NumConsArgs - 1]->getLocEnd());
777
778 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
779 return ExprError();
780 }
781
Douglas Gregor99a2e602009-12-16 01:38:02 +0000782 if (!AllocType->isDependentType() &&
783 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
784 // C++0x [expr.new]p15:
785 // A new-expression that creates an object of type T initializes that
786 // object as follows:
787 InitializationKind Kind
788 // - If the new-initializer is omitted, the object is default-
789 // initialized (8.5); if no initialization is performed,
790 // the object has indeterminate value
791 = !Init? InitializationKind::CreateDefault(TypeLoc)
792 // - Otherwise, the new-initializer is interpreted according to the
793 // initialization rules of 8.5 for direct-initialization.
794 : InitializationKind::CreateDirect(TypeLoc,
795 ConstructorLParen,
796 ConstructorRParen);
797
Douglas Gregor99a2e602009-12-16 01:38:02 +0000798 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000799 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000800 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000801 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
802 move(ConstructorArgs));
803 if (FullInit.isInvalid())
804 return ExprError();
805
806 // FullInit is our initializer; walk through it to determine if it's a
807 // constructor call, which CXXNewExpr handles directly.
808 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
809 if (CXXBindTemporaryExpr *Binder
810 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
811 FullInitExpr = Binder->getSubExpr();
812 if (CXXConstructExpr *Construct
813 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
814 Constructor = Construct->getConstructor();
815 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
816 AEnd = Construct->arg_end();
817 A != AEnd; ++A)
818 ConvertedConstructorArgs.push_back(A->Retain());
819 } else {
820 // Take the converted initializer.
821 ConvertedConstructorArgs.push_back(FullInit.release());
822 }
823 } else {
824 // No initialization required.
825 }
826
827 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000828 NumConsArgs = ConvertedConstructorArgs.size();
829 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000830 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000831
Douglas Gregor6d908702010-02-26 05:06:18 +0000832 // Mark the new and delete operators as referenced.
833 if (OperatorNew)
834 MarkDeclarationReferenced(StartLoc, OperatorNew);
835 if (OperatorDelete)
836 MarkDeclarationReferenced(StartLoc, OperatorDelete);
837
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000838 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000839
Sebastian Redlf53597f2009-03-15 17:47:39 +0000840 PlacementArgs.release();
841 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000842 ArraySizeE.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000843
844 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenekad7fe862010-02-11 22:51:03 +0000845 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000846 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000847 ArraySize, Constructor, Init,
848 ConsArgs, NumConsArgs, OperatorDelete,
849 ResultType, StartLoc,
850 Init ? ConstructorRParen :
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000851 TypeRange.getEnd()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000852}
853
854/// CheckAllocatedType - Checks that a type is suitable as the allocated type
855/// in a new-expression.
856/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000857bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000858 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000859 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
860 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000861 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000862 return Diag(Loc, diag::err_bad_new_type)
863 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000864 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000865 return Diag(Loc, diag::err_bad_new_type)
866 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000867 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000868 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000869 PDiag(diag::err_new_incomplete_type)
870 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000871 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000872 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000873 diag::err_allocation_of_abstract_type))
874 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000875
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000876 return false;
877}
878
Douglas Gregor6d908702010-02-26 05:06:18 +0000879/// \brief Determine whether the given function is a non-placement
880/// deallocation function.
881static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
882 if (FD->isInvalidDecl())
883 return false;
884
885 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
886 return Method->isUsualDeallocationFunction();
887
888 return ((FD->getOverloadedOperator() == OO_Delete ||
889 FD->getOverloadedOperator() == OO_Array_Delete) &&
890 FD->getNumParams() == 1);
891}
892
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000893/// FindAllocationFunctions - Finds the overloads of operator new and delete
894/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000895bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
896 bool UseGlobal, QualType AllocType,
897 bool IsArray, Expr **PlaceArgs,
898 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000899 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000900 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000901 // --- Choosing an allocation function ---
902 // C++ 5.3.4p8 - 14 & 18
903 // 1) If UseGlobal is true, only look in the global scope. Else, also look
904 // in the scope of the allocated class.
905 // 2) If an array size is given, look for operator new[], else look for
906 // operator new.
907 // 3) The first argument is always size_t. Append the arguments from the
908 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000909
910 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
911 // We don't care about the actual value of this argument.
912 // FIXME: Should the Sema create the expression and embed it in the syntax
913 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000914 IntegerLiteral Size(llvm::APInt::getNullValue(
915 Context.Target.getPointerWidth(0)),
916 Context.getSizeType(),
917 SourceLocation());
918 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000919 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
920
Douglas Gregor6d908702010-02-26 05:06:18 +0000921 // C++ [expr.new]p8:
922 // If the allocated type is a non-array type, the allocation
923 // function’s name is operator new and the deallocation function’s
924 // name is operator delete. If the allocated type is an array
925 // type, the allocation function’s name is operator new[] and the
926 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000927 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
928 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000929 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
930 IsArray ? OO_Array_Delete : OO_Delete);
931
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000932 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000933 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000934 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000935 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000936 AllocArgs.size(), Record, /*AllowMissing=*/true,
937 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000938 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000939 }
940 if (!OperatorNew) {
941 // Didn't find a member overload. Look for a global one.
942 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000943 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000944 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000945 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
946 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000947 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000948 }
949
John McCall9c82afc2010-04-20 02:18:25 +0000950 // We don't need an operator delete if we're running under
951 // -fno-exceptions.
952 if (!getLangOptions().Exceptions) {
953 OperatorDelete = 0;
954 return false;
955 }
956
Anders Carlssond9583892009-05-31 20:26:12 +0000957 // FindAllocationOverload can change the passed in arguments, so we need to
958 // copy them back.
959 if (NumPlaceArgs > 0)
960 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Douglas Gregor6d908702010-02-26 05:06:18 +0000962 // C++ [expr.new]p19:
963 //
964 // If the new-expression begins with a unary :: operator, the
965 // deallocation function’s name is looked up in the global
966 // scope. Otherwise, if the allocated type is a class type T or an
967 // array thereof, the deallocation function’s name is looked up in
968 // the scope of T. If this lookup fails to find the name, or if
969 // the allocated type is not a class type or array thereof, the
970 // deallocation function’s name is looked up in the global scope.
971 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
972 if (AllocType->isRecordType() && !UseGlobal) {
973 CXXRecordDecl *RD
974 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
975 LookupQualifiedName(FoundDelete, RD);
976 }
John McCall90c8c572010-03-18 08:19:33 +0000977 if (FoundDelete.isAmbiguous())
978 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000979
980 if (FoundDelete.empty()) {
981 DeclareGlobalNewDelete();
982 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
983 }
984
985 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000986
987 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
988
John McCall90c8c572010-03-18 08:19:33 +0000989 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000990 // C++ [expr.new]p20:
991 // A declaration of a placement deallocation function matches the
992 // declaration of a placement allocation function if it has the
993 // same number of parameters and, after parameter transformations
994 // (8.3.5), all parameter types except the first are
995 // identical. [...]
996 //
997 // To perform this comparison, we compute the function type that
998 // the deallocation function should have, and use that type both
999 // for template argument deduction and for comparison purposes.
1000 QualType ExpectedFunctionType;
1001 {
1002 const FunctionProtoType *Proto
1003 = OperatorNew->getType()->getAs<FunctionProtoType>();
1004 llvm::SmallVector<QualType, 4> ArgTypes;
1005 ArgTypes.push_back(Context.VoidPtrTy);
1006 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1007 ArgTypes.push_back(Proto->getArgType(I));
1008
1009 ExpectedFunctionType
1010 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1011 ArgTypes.size(),
1012 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001013 0, false, false, 0, 0,
1014 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001015 }
1016
1017 for (LookupResult::iterator D = FoundDelete.begin(),
1018 DEnd = FoundDelete.end();
1019 D != DEnd; ++D) {
1020 FunctionDecl *Fn = 0;
1021 if (FunctionTemplateDecl *FnTmpl
1022 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1023 // Perform template argument deduction to try to match the
1024 // expected function type.
1025 TemplateDeductionInfo Info(Context, StartLoc);
1026 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1027 continue;
1028 } else
1029 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1030
1031 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001032 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001033 }
1034 } else {
1035 // C++ [expr.new]p20:
1036 // [...] Any non-placement deallocation function matches a
1037 // non-placement allocation function. [...]
1038 for (LookupResult::iterator D = FoundDelete.begin(),
1039 DEnd = FoundDelete.end();
1040 D != DEnd; ++D) {
1041 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1042 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001043 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001044 }
1045 }
1046
1047 // C++ [expr.new]p20:
1048 // [...] If the lookup finds a single matching deallocation
1049 // function, that function will be called; otherwise, no
1050 // deallocation function will be called.
1051 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001052 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001053
1054 // C++0x [expr.new]p20:
1055 // If the lookup finds the two-parameter form of a usual
1056 // deallocation function (3.7.4.2) and that function, considered
1057 // as a placement deallocation function, would have been
1058 // selected as a match for the allocation function, the program
1059 // is ill-formed.
1060 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1061 isNonPlacementDeallocationFunction(OperatorDelete)) {
1062 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1063 << SourceRange(PlaceArgs[0]->getLocStart(),
1064 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1065 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1066 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001067 } else {
1068 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001069 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001070 }
1071 }
1072
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001073 return false;
1074}
1075
Sebastian Redl7f662392008-12-04 22:20:51 +00001076/// FindAllocationOverload - Find an fitting overload for the allocation
1077/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001078bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1079 DeclarationName Name, Expr** Args,
1080 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001081 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001082 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1083 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001084 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001085 if (AllowMissing)
1086 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001087 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001088 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001089 }
1090
John McCall90c8c572010-03-18 08:19:33 +00001091 if (R.isAmbiguous())
1092 return true;
1093
1094 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001095
John McCall5769d612010-02-08 23:07:23 +00001096 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001097 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1098 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001099 // Even member operator new/delete are implicitly treated as
1100 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001101 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001102
John McCall9aa472c2010-03-19 07:35:19 +00001103 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1104 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001105 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1106 Candidates,
1107 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001108 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001109 }
1110
John McCall9aa472c2010-03-19 07:35:19 +00001111 FunctionDecl *Fn = cast<FunctionDecl>(D);
1112 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001113 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001114 }
1115
1116 // Do the resolution.
1117 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001118 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001119 case OR_Success: {
1120 // Got one!
1121 FunctionDecl *FnDecl = Best->Function;
1122 // The first argument is size_t, and the first parameter must be size_t,
1123 // too. This is checked on declaration and can be assumed. (It can't be
1124 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001125 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001126 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1127 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001128 OwningExprResult Result
1129 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1130 FnDecl->getParamDecl(i)),
1131 SourceLocation(),
1132 Owned(Args[i]->Retain()));
1133 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001134 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001135
1136 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001137 }
1138 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001139 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001140 return false;
1141 }
1142
1143 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001144 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001145 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001146 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001147 return true;
1148
1149 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001150 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001151 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001152 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001153 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001154
1155 case OR_Deleted:
1156 Diag(StartLoc, diag::err_ovl_deleted_call)
1157 << Best->Function->isDeleted()
1158 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001159 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001160 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001161 }
1162 assert(false && "Unreachable, bad result from BestViableFunction");
1163 return true;
1164}
1165
1166
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001167/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1168/// delete. These are:
1169/// @code
1170/// void* operator new(std::size_t) throw(std::bad_alloc);
1171/// void* operator new[](std::size_t) throw(std::bad_alloc);
1172/// void operator delete(void *) throw();
1173/// void operator delete[](void *) throw();
1174/// @endcode
1175/// Note that the placement and nothrow forms of new are *not* implicitly
1176/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001177void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001178 if (GlobalNewDeleteDeclared)
1179 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001180
1181 // C++ [basic.std.dynamic]p2:
1182 // [...] The following allocation and deallocation functions (18.4) are
1183 // implicitly declared in global scope in each translation unit of a
1184 // program
1185 //
1186 // void* operator new(std::size_t) throw(std::bad_alloc);
1187 // void* operator new[](std::size_t) throw(std::bad_alloc);
1188 // void operator delete(void*) throw();
1189 // void operator delete[](void*) throw();
1190 //
1191 // These implicit declarations introduce only the function names operator
1192 // new, operator new[], operator delete, operator delete[].
1193 //
1194 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1195 // "std" or "bad_alloc" as necessary to form the exception specification.
1196 // However, we do not make these implicit declarations visible to name
1197 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001198 if (!StdBadAlloc) {
1199 // The "std::bad_alloc" class has not yet been declared, so build it
1200 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001201 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00001202 getOrCreateStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001203 SourceLocation(),
1204 &PP.getIdentifierTable().get("bad_alloc"),
1205 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001206 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001207 }
1208
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001209 GlobalNewDeleteDeclared = true;
1210
1211 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1212 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001213 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001214
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001215 DeclareGlobalAllocationFunction(
1216 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001217 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001218 DeclareGlobalAllocationFunction(
1219 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001220 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001221 DeclareGlobalAllocationFunction(
1222 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1223 Context.VoidTy, VoidPtr);
1224 DeclareGlobalAllocationFunction(
1225 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1226 Context.VoidTy, VoidPtr);
1227}
1228
1229/// DeclareGlobalAllocationFunction - Declares a single implicit global
1230/// allocation function if it doesn't already exist.
1231void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001232 QualType Return, QualType Argument,
1233 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001234 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1235
1236 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001237 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001238 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001239 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001240 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001241 // Only look at non-template functions, as it is the predefined,
1242 // non-templated allocation function we are trying to declare here.
1243 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1244 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001245 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001246 Func->getParamDecl(0)->getType().getUnqualifiedType());
1247 // FIXME: Do we need to check for default arguments here?
1248 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1249 return;
1250 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001251 }
1252 }
1253
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001254 QualType BadAllocType;
1255 bool HasBadAllocExceptionSpec
1256 = (Name.getCXXOverloadedOperator() == OO_New ||
1257 Name.getCXXOverloadedOperator() == OO_Array_New);
1258 if (HasBadAllocExceptionSpec) {
1259 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001260 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001261 }
1262
1263 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1264 true, false,
1265 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001266 &BadAllocType,
1267 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001268 FunctionDecl *Alloc =
1269 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001270 FnType, /*TInfo=*/0, FunctionDecl::None,
1271 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001272 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001273
1274 if (AddMallocAttr)
1275 Alloc->addAttr(::new (Context) MallocAttr());
1276
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001277 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001278 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001279 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001280 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001281 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001282
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001283 // FIXME: Also add this declaration to the IdentifierResolver, but
1284 // make sure it is at the end of the chain to coincide with the
1285 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001286 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001287}
1288
Anders Carlsson78f74552009-11-15 18:45:20 +00001289bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1290 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001291 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001292 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001293 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001294 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001295
John McCalla24dc2e2009-11-17 02:14:36 +00001296 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001297 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001298
Chandler Carruth23893242010-06-28 00:30:51 +00001299 Found.suppressDiagnostics();
1300
John McCall046a7462010-08-04 00:31:26 +00001301 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001302 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1303 F != FEnd; ++F) {
John McCall046a7462010-08-04 00:31:26 +00001304 CXXMethodDecl *Delete = cast<CXXMethodDecl>((*F)->getUnderlyingDecl());
1305 if (Delete->isUsualDeallocationFunction())
1306 Matches.push_back(F.getPair());
1307 }
1308
1309 // There's exactly one suitable operator; pick it.
1310 if (Matches.size() == 1) {
1311 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1312 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1313 Matches[0]);
1314 return false;
1315
1316 // We found multiple suitable operators; complain about the ambiguity.
1317 } else if (!Matches.empty()) {
1318 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1319 << Name << RD;
1320
1321 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1322 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1323 Diag((*F)->getUnderlyingDecl()->getLocation(),
1324 diag::note_member_declared_here) << Name;
1325 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001326 }
1327
1328 // We did find operator delete/operator delete[] declarations, but
1329 // none of them were suitable.
1330 if (!Found.empty()) {
1331 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1332 << Name << RD;
1333
1334 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001335 F != FEnd; ++F)
1336 Diag((*F)->getUnderlyingDecl()->getLocation(),
1337 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001338
1339 return true;
1340 }
1341
1342 // Look for a global declaration.
1343 DeclareGlobalNewDelete();
1344 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1345
1346 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1347 Expr* DeallocArgs[1];
1348 DeallocArgs[0] = &Null;
1349 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1350 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1351 Operator))
1352 return true;
1353
1354 assert(Operator && "Did not find a deallocation function!");
1355 return false;
1356}
1357
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001358/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1359/// @code ::delete ptr; @endcode
1360/// or
1361/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001362Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001363Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001364 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001365 // C++ [expr.delete]p1:
1366 // The operand shall have a pointer type, or a class type having a single
1367 // conversion function to a pointer type. The result has type void.
1368 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001369 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1370
Anders Carlssond67c4c32009-08-16 20:29:29 +00001371 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Sebastian Redlf53597f2009-03-15 17:47:39 +00001373 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001374 if (!Ex->isTypeDependent()) {
1375 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001376
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001377 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor254a9422010-07-29 14:44:35 +00001378 if (RequireCompleteType(StartLoc, Type,
1379 PDiag(diag::err_delete_incomplete_class_type)))
1380 return ExprError();
1381
John McCall32daa422010-03-31 01:36:47 +00001382 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1383
Fariborz Jahanian53462782009-09-11 21:44:33 +00001384 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001385 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001386 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001387 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001388 NamedDecl *D = I.getDecl();
1389 if (isa<UsingShadowDecl>(D))
1390 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1391
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001392 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001393 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001394 continue;
1395
John McCall32daa422010-03-31 01:36:47 +00001396 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001397
1398 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1399 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001400 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001401 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001402 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001403 if (ObjectPtrConversions.size() == 1) {
1404 // We have a single conversion to a pointer-to-object type. Perform
1405 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001406 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001407 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001408 if (!PerformImplicitConversion(Ex,
1409 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001410 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001411 Operand = Owned(Ex);
1412 Type = Ex->getType();
1413 }
1414 }
1415 else if (ObjectPtrConversions.size() > 1) {
1416 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1417 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001418 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1419 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001420 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001421 }
Sebastian Redl28507842009-02-26 14:39:58 +00001422 }
1423
Sebastian Redlf53597f2009-03-15 17:47:39 +00001424 if (!Type->isPointerType())
1425 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1426 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001427
Ted Kremenek6217b802009-07-29 21:53:49 +00001428 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001429 if (Pointee->isVoidType() && !isSFINAEContext()) {
1430 // The C++ standard bans deleting a pointer to a non-object type, which
1431 // effectively bans deletion of "void*". However, most compilers support
1432 // this, so we treat it as a warning unless we're in a SFINAE context.
1433 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1434 << Type << Ex->getSourceRange();
1435 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001436 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1437 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001438 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001439 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001440 PDiag(diag::warn_delete_incomplete)
1441 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001442 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001443
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001444 // C++ [expr.delete]p2:
1445 // [Note: a pointer to a const type can be the operand of a
1446 // delete-expression; it is not necessary to cast away the constness
1447 // (5.2.11) of the pointer expression before it is used as the operand
1448 // of the delete-expression. ]
1449 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1450 CastExpr::CK_NoOp);
1451
1452 // Update the operand.
1453 Operand.take();
1454 Operand = ExprArg(*this, Ex);
1455
Anders Carlssond67c4c32009-08-16 20:29:29 +00001456 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1457 ArrayForm ? OO_Array_Delete : OO_Delete);
1458
Anders Carlsson78f74552009-11-15 18:45:20 +00001459 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1460 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1461
1462 if (!UseGlobal &&
1463 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001464 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001465
Anders Carlsson78f74552009-11-15 18:45:20 +00001466 if (!RD->hasTrivialDestructor())
Douglas Gregordb89f282010-07-01 22:47:18 +00001467 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump1eb44332009-09-09 15:08:12 +00001468 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001469 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001470 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001471
Anders Carlssond67c4c32009-08-16 20:29:29 +00001472 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001473 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001474 DeclareGlobalNewDelete();
1475 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001476 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001477 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001478 OperatorDelete))
1479 return ExprError();
1480 }
Mike Stump1eb44332009-09-09 15:08:12 +00001481
John McCall9c82afc2010-04-20 02:18:25 +00001482 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1483
Sebastian Redl28507842009-02-26 14:39:58 +00001484 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001485 }
1486
Sebastian Redlf53597f2009-03-15 17:47:39 +00001487 Operand.release();
1488 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001489 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001490}
1491
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001492/// \brief Check the use of the given variable as a C++ condition in an if,
1493/// while, do-while, or switch statement.
Douglas Gregor586596f2010-05-06 17:25:47 +00001494Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1495 SourceLocation StmtLoc,
1496 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001497 QualType T = ConditionVar->getType();
1498
1499 // C++ [stmt.select]p2:
1500 // The declarator shall not specify a function or an array.
1501 if (T->isFunctionType())
1502 return ExprError(Diag(ConditionVar->getLocation(),
1503 diag::err_invalid_use_of_function_type)
1504 << ConditionVar->getSourceRange());
1505 else if (T->isArrayType())
1506 return ExprError(Diag(ConditionVar->getLocation(),
1507 diag::err_invalid_use_of_array_type)
1508 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001509
Douglas Gregor586596f2010-05-06 17:25:47 +00001510 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1511 ConditionVar->getLocation(),
1512 ConditionVar->getType().getNonReferenceType());
Douglas Gregorff331c12010-07-25 18:17:45 +00001513 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001514 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00001515
1516 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001517}
1518
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001519/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1520bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1521 // C++ 6.4p4:
1522 // The value of a condition that is an initialized declaration in a statement
1523 // other than a switch statement is the value of the declared variable
1524 // implicitly converted to type bool. If that conversion is ill-formed, the
1525 // program is ill-formed.
1526 // The value of a condition that is an expression is the value of the
1527 // expression, implicitly converted to bool.
1528 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001529 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001530}
Douglas Gregor77a52232008-09-12 00:47:35 +00001531
1532/// Helper function to determine whether this is the (deprecated) C++
1533/// conversion from a string literal to a pointer to non-const char or
1534/// non-const wchar_t (for narrow and wide string literals,
1535/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001536bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001537Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1538 // Look inside the implicit cast, if it exists.
1539 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1540 From = Cast->getSubExpr();
1541
1542 // A string literal (2.13.4) that is not a wide string literal can
1543 // be converted to an rvalue of type "pointer to char"; a wide
1544 // string literal can be converted to an rvalue of type "pointer
1545 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001546 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001547 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001548 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001549 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001550 // This conversion is considered only when there is an
1551 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001552 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001553 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1554 (!StrLit->isWide() &&
1555 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1556 ToPointeeType->getKind() == BuiltinType::Char_S))))
1557 return true;
1558 }
1559
1560 return false;
1561}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001562
Douglas Gregorba70ab62010-04-16 22:17:36 +00001563static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1564 SourceLocation CastLoc,
1565 QualType Ty,
1566 CastExpr::CastKind Kind,
1567 CXXMethodDecl *Method,
1568 Sema::ExprArg Arg) {
1569 Expr *From = Arg.takeAs<Expr>();
1570
1571 switch (Kind) {
1572 default: assert(0 && "Unhandled cast kind!");
1573 case CastExpr::CK_ConstructorConversion: {
1574 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1575
1576 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1577 Sema::MultiExprArg(S, (void **)&From, 1),
1578 CastLoc, ConstructorArgs))
1579 return S.ExprError();
1580
1581 Sema::OwningExprResult Result =
1582 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1583 move_arg(ConstructorArgs));
1584 if (Result.isInvalid())
1585 return S.ExprError();
1586
1587 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1588 }
1589
1590 case CastExpr::CK_UserDefinedConversion: {
1591 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1592
1593 // Create an implicit call expr that calls it.
1594 // FIXME: pass the FoundDecl for the user-defined conversion here
1595 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1596 return S.MaybeBindToTemporary(CE);
1597 }
1598 }
1599}
1600
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001601/// PerformImplicitConversion - Perform an implicit conversion of the
1602/// expression From to the type ToType using the pre-computed implicit
1603/// conversion sequence ICS. Returns true if there was an error, false
1604/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001605/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001606/// used in the error message.
1607bool
1608Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1609 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001610 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001611 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001612 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001613 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001614 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001615 return true;
1616 break;
1617
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001618 case ImplicitConversionSequence::UserDefinedConversion: {
1619
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001620 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1621 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001622 QualType BeforeToType;
1623 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001624 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001625
1626 // If the user-defined conversion is specified by a conversion function,
1627 // the initial standard conversion sequence converts the source type to
1628 // the implicit object parameter of the conversion function.
1629 BeforeToType = Context.getTagDeclType(Conv->getParent());
1630 } else if (const CXXConstructorDecl *Ctor =
1631 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001632 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001633 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001634 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001635 // If the user-defined conversion is specified by a constructor, the
1636 // initial standard conversion sequence converts the source type to the
1637 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001638 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1639 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001640 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001641 else
1642 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001643 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001644 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001645 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001646 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001647 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001648 return true;
1649 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001650
Anders Carlsson0aebc812009-09-09 21:33:21 +00001651 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001652 = BuildCXXCastArgument(*this,
1653 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001654 ToType.getNonReferenceType(),
1655 CastKind, cast<CXXMethodDecl>(FD),
1656 Owned(From));
1657
1658 if (CastArg.isInvalid())
1659 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001660
1661 From = CastArg.takeAs<Expr>();
1662
Eli Friedmand8889622009-11-27 04:41:50 +00001663 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001664 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001665 }
John McCall1d318332010-01-12 00:44:57 +00001666
1667 case ImplicitConversionSequence::AmbiguousConversion:
1668 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1669 PDiag(diag::err_typecheck_ambiguous_condition)
1670 << From->getSourceRange());
1671 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001672
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001673 case ImplicitConversionSequence::EllipsisConversion:
1674 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001675 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001676
1677 case ImplicitConversionSequence::BadConversion:
1678 return true;
1679 }
1680
1681 // Everything went well.
1682 return false;
1683}
1684
1685/// PerformImplicitConversion - Perform an implicit conversion of the
1686/// expression From to the type ToType by following the standard
1687/// conversion sequence SCS. Returns true if there was an error, false
1688/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001689/// expression. Flavor is the context in which we're performing this
1690/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001691bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001692Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001693 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001694 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001695 // Overall FIXME: we are recomputing too many types here and doing far too
1696 // much extra work. What this means is that we need to keep track of more
1697 // information that is computed when we try the implicit conversion initially,
1698 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001699 QualType FromType = From->getType();
1700
Douglas Gregor225c41e2008-11-03 19:09:14 +00001701 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001702 // FIXME: When can ToType be a reference type?
1703 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001704 if (SCS.Second == ICK_Derived_To_Base) {
1705 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1706 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1707 MultiExprArg(*this, (void **)&From, 1),
1708 /*FIXME:ConstructLoc*/SourceLocation(),
1709 ConstructorArgs))
1710 return true;
1711 OwningExprResult FromResult =
1712 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1713 ToType, SCS.CopyConstructor,
1714 move_arg(ConstructorArgs));
1715 if (FromResult.isInvalid())
1716 return true;
1717 From = FromResult.takeAs<Expr>();
1718 return false;
1719 }
Mike Stump1eb44332009-09-09 15:08:12 +00001720 OwningExprResult FromResult =
1721 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1722 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001723 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001725 if (FromResult.isInvalid())
1726 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001728 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001729 return false;
1730 }
1731
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001732 // Resolve overloaded function references.
1733 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1734 DeclAccessPair Found;
1735 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1736 true, Found);
1737 if (!Fn)
1738 return true;
1739
1740 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1741 return true;
1742
1743 From = FixOverloadedFunctionReference(From, Found, Fn);
1744 FromType = From->getType();
1745 }
1746
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001747 // Perform the first implicit conversion.
1748 switch (SCS.First) {
1749 case ICK_Identity:
1750 case ICK_Lvalue_To_Rvalue:
1751 // Nothing to do.
1752 break;
1753
1754 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001755 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001756 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001757 break;
1758
1759 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001760 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001761 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001762 break;
1763
1764 default:
1765 assert(false && "Improper first standard conversion");
1766 break;
1767 }
1768
1769 // Perform the second implicit conversion
1770 switch (SCS.Second) {
1771 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001772 // If both sides are functions (or pointers/references to them), there could
1773 // be incompatible exception declarations.
1774 if (CheckExceptionSpecCompatibility(From, ToType))
1775 return true;
1776 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001777 break;
1778
Douglas Gregor43c79c22009-12-09 00:47:37 +00001779 case ICK_NoReturn_Adjustment:
1780 // If both sides are functions (or pointers/references to them), there could
1781 // be incompatible exception declarations.
1782 if (CheckExceptionSpecCompatibility(From, ToType))
1783 return true;
1784
1785 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1786 CastExpr::CK_NoOp);
1787 break;
1788
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001789 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001790 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001791 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1792 break;
1793
1794 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001795 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001796 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1797 break;
1798
1799 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001800 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001801 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1802 break;
1803
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001804 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001805 if (ToType->isRealFloatingType())
Eli Friedman73c39ab2009-10-20 08:27:19 +00001806 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1807 else
1808 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1809 break;
1810
Douglas Gregorf9201e02009-02-11 23:02:49 +00001811 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001812 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001813 break;
1814
Anders Carlsson61faec12009-09-12 04:46:44 +00001815 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001816 if (SCS.IncompatibleObjC) {
1817 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001818 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001819 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001820 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001821 << From->getSourceRange();
1822 }
1823
Anders Carlsson61faec12009-09-12 04:46:44 +00001824
1825 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001826 CXXBaseSpecifierArray BasePath;
1827 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001828 return true;
Sebastian Redl906082e2010-07-20 04:20:21 +00001829 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001830 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001831 }
1832
1833 case ICK_Pointer_Member: {
1834 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001835 CXXBaseSpecifierArray BasePath;
1836 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1837 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001838 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001839 if (CheckExceptionSpecCompatibility(From, ToType))
1840 return true;
Sebastian Redl906082e2010-07-20 04:20:21 +00001841 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001842 break;
1843 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001844 case ICK_Boolean_Conversion: {
1845 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1846 if (FromType->isMemberPointerType())
1847 Kind = CastExpr::CK_MemberPointerToBoolean;
1848
1849 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001850 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001851 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001852
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001853 case ICK_Derived_To_Base: {
1854 CXXBaseSpecifierArray BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001855 if (CheckDerivedToBaseConversion(From->getType(),
1856 ToType.getNonReferenceType(),
1857 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001858 From->getSourceRange(),
1859 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001860 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001861 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001862
Sebastian Redl906082e2010-07-20 04:20:21 +00001863 ImpCastExprToType(From, ToType.getNonReferenceType(),
1864 CastExpr::CK_DerivedToBase, CastCategory(From), BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001865 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001866 }
1867
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001868 case ICK_Vector_Conversion:
1869 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1870 break;
1871
1872 case ICK_Vector_Splat:
1873 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1874 break;
1875
1876 case ICK_Complex_Real:
1877 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1878 break;
1879
1880 case ICK_Lvalue_To_Rvalue:
1881 case ICK_Array_To_Pointer:
1882 case ICK_Function_To_Pointer:
1883 case ICK_Qualification:
1884 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001885 assert(false && "Improper second standard conversion");
1886 break;
1887 }
1888
1889 switch (SCS.Third) {
1890 case ICK_Identity:
1891 // Nothing to do.
1892 break;
1893
Sebastian Redl906082e2010-07-20 04:20:21 +00001894 case ICK_Qualification: {
1895 // The qualification keeps the category of the inner expression, unless the
1896 // target type isn't a reference.
1897 ImplicitCastExpr::ResultCategory Category = ToType->isReferenceType() ?
1898 CastCategory(From) : ImplicitCastExpr::RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00001899 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Sebastian Redl906082e2010-07-20 04:20:21 +00001900 CastExpr::CK_NoOp, Category);
Douglas Gregora9bff302010-02-28 18:30:25 +00001901
1902 if (SCS.DeprecatedStringLiteralToCharPtr)
1903 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1904 << ToType.getNonReferenceType();
1905
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001906 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00001907 }
1908
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001909 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001910 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001911 break;
1912 }
1913
1914 return false;
1915}
1916
Sebastian Redl64b45f72009-01-05 20:52:13 +00001917Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1918 SourceLocation KWLoc,
1919 SourceLocation LParen,
1920 TypeTy *Ty,
1921 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001922 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001924 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1925 // all traits except __is_class, __is_enum and __is_union require a the type
1926 // to be complete.
1927 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001928 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001929 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001930 return ExprError();
1931 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001932
1933 // There is no point in eagerly computing the value. The traits are designed
1934 // to be used from type trait templates, so Ty will be a template parameter
1935 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001936 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1937 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001938}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001939
1940QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001941 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001942 const char *OpSpelling = isIndirect ? "->*" : ".*";
1943 // C++ 5.5p2
1944 // The binary operator .* [p3: ->*] binds its second operand, which shall
1945 // be of type "pointer to member of T" (where T is a completely-defined
1946 // class type) [...]
1947 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001948 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001949 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001950 Diag(Loc, diag::err_bad_memptr_rhs)
1951 << OpSpelling << RType << rex->getSourceRange();
1952 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001953 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001954
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001955 QualType Class(MemPtr->getClass(), 0);
1956
Sebastian Redl59fc2692010-04-10 10:14:54 +00001957 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1958 return QualType();
1959
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001960 // C++ 5.5p2
1961 // [...] to its first operand, which shall be of class T or of a class of
1962 // which T is an unambiguous and accessible base class. [p3: a pointer to
1963 // such a class]
1964 QualType LType = lex->getType();
1965 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001966 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001967 LType = Ptr->getPointeeType().getNonReferenceType();
1968 else {
1969 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001970 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001971 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001972 return QualType();
1973 }
1974 }
1975
Douglas Gregora4923eb2009-11-16 21:35:15 +00001976 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001977 // If we want to check the hierarchy, we need a complete type.
1978 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1979 << OpSpelling << (int)isIndirect)) {
1980 return QualType();
1981 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001982 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001983 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001984 // FIXME: Would it be useful to print full ambiguity paths, or is that
1985 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001986 if (!IsDerivedFrom(LType, Class, Paths) ||
1987 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1988 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001989 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001990 return QualType();
1991 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001992 // Cast LHS to type of use.
1993 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Sebastian Redl906082e2010-07-20 04:20:21 +00001994 ImplicitCastExpr::ResultCategory Category =
1995 isIndirect ? ImplicitCastExpr::RValue : CastCategory(lex);
1996
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001997 CXXBaseSpecifierArray BasePath;
1998 BuildBasePathArray(Paths, BasePath);
Sebastian Redl906082e2010-07-20 04:20:21 +00001999 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, Category,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002000 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002001 }
2002
Douglas Gregored8abf12010-07-08 06:14:04 +00002003 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002004 // Diagnose use of pointer-to-member type which when used as
2005 // the functional cast in a pointer-to-member expression.
2006 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2007 return QualType();
2008 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002009 // C++ 5.5p2
2010 // The result is an object or a function of the type specified by the
2011 // second operand.
2012 // The cv qualifiers are the union of those in the pointer and the left side,
2013 // in accordance with 5.5p5 and 5.2.5.
2014 // FIXME: This returns a dereferenced member function pointer as a normal
2015 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002016 // calling them. There's also a GCC extension to get a function pointer to the
2017 // thing, which is another complication, because this type - unlike the type
2018 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002019 // argument.
2020 // We probably need a "MemberFunctionClosureType" or something like that.
2021 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002022 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002023 return Result;
2024}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002025
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002026/// \brief Try to convert a type to another according to C++0x 5.16p3.
2027///
2028/// This is part of the parameter validation for the ? operator. If either
2029/// value operand is a class type, the two operands are attempted to be
2030/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002031/// It returns true if the program is ill-formed and has already been diagnosed
2032/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002033static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2034 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002035 bool &HaveConversion,
2036 QualType &ToType) {
2037 HaveConversion = false;
2038 ToType = To->getType();
2039
2040 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2041 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002042 // C++0x 5.16p3
2043 // The process for determining whether an operand expression E1 of type T1
2044 // can be converted to match an operand expression E2 of type T2 is defined
2045 // as follows:
2046 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002047 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2048 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002049 // E1 can be converted to match E2 if E1 can be implicitly converted to
2050 // type "lvalue reference to T2", subject to the constraint that in the
2051 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002052 QualType T = Self.Context.getLValueReferenceType(ToType);
2053 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2054
2055 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2056 if (InitSeq.isDirectReferenceBinding()) {
2057 ToType = T;
2058 HaveConversion = true;
2059 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002060 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002061
2062 if (InitSeq.isAmbiguous())
2063 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002064 }
John McCallb1bdc622010-02-25 01:37:24 +00002065
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002066 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2067 // -- if E1 and E2 have class type, and the underlying class types are
2068 // the same or one is a base class of the other:
2069 QualType FTy = From->getType();
2070 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002071 const RecordType *FRec = FTy->getAs<RecordType>();
2072 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002073 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2074 Self.IsDerivedFrom(FTy, TTy);
2075 if (FRec && TRec &&
2076 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002077 // E1 can be converted to match E2 if the class of T2 is the
2078 // same type as, or a base class of, the class of T1, and
2079 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002080 if (FRec == TRec || FDerivedFromT) {
2081 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002082 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2083 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2084 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2085 HaveConversion = true;
2086 return false;
2087 }
2088
2089 if (InitSeq.isAmbiguous())
2090 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2091 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002092 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002093
2094 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002095 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002096
2097 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2098 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002099 // if E2 were converted to an rvalue (or the type it has, if E2 is
2100 // an rvalue).
2101 //
2102 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2103 // to the array-to-pointer or function-to-pointer conversions.
2104 if (!TTy->getAs<TagType>())
2105 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002106
2107 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2108 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2109 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2110 ToType = TTy;
2111 if (InitSeq.isAmbiguous())
2112 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2113
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002114 return false;
2115}
2116
2117/// \brief Try to find a common type for two according to C++0x 5.16p5.
2118///
2119/// This is part of the parameter validation for the ? operator. If either
2120/// value operand is a class type, overload resolution is used to find a
2121/// conversion to a common type.
2122static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2123 SourceLocation Loc) {
2124 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002125 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002126 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002127
2128 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002129 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002130 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002131 // We found a match. Perform the conversions on the arguments and move on.
2132 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002133 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002134 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002135 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002136 break;
2137 return false;
2138
Douglas Gregor20093b42009-12-09 23:02:17 +00002139 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002140 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2141 << LHS->getType() << RHS->getType()
2142 << LHS->getSourceRange() << RHS->getSourceRange();
2143 return true;
2144
Douglas Gregor20093b42009-12-09 23:02:17 +00002145 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002146 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2147 << LHS->getType() << RHS->getType()
2148 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002149 // FIXME: Print the possible common types by printing the return types of
2150 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002151 break;
2152
Douglas Gregor20093b42009-12-09 23:02:17 +00002153 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002154 assert(false && "Conditional operator has only built-in overloads");
2155 break;
2156 }
2157 return true;
2158}
2159
Sebastian Redl76458502009-04-17 16:30:52 +00002160/// \brief Perform an "extended" implicit conversion as returned by
2161/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002162static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2163 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2164 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2165 SourceLocation());
2166 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2167 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2168 Sema::MultiExprArg(Self, (void **)&E, 1));
2169 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002170 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002171
2172 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002173 return false;
2174}
2175
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002176/// \brief Check the operands of ?: under C++ semantics.
2177///
2178/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2179/// extension. In this case, LHS == Cond. (But they're not aliases.)
2180QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2181 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002182 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2183 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002184
2185 // C++0x 5.16p1
2186 // The first expression is contextually converted to bool.
2187 if (!Cond->isTypeDependent()) {
2188 if (CheckCXXBooleanCondition(Cond))
2189 return QualType();
2190 }
2191
2192 // Either of the arguments dependent?
2193 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2194 return Context.DependentTy;
2195
2196 // C++0x 5.16p2
2197 // If either the second or the third operand has type (cv) void, ...
2198 QualType LTy = LHS->getType();
2199 QualType RTy = RHS->getType();
2200 bool LVoid = LTy->isVoidType();
2201 bool RVoid = RTy->isVoidType();
2202 if (LVoid || RVoid) {
2203 // ... then the [l2r] conversions are performed on the second and third
2204 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002205 DefaultFunctionArrayLvalueConversion(LHS);
2206 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002207 LTy = LHS->getType();
2208 RTy = RHS->getType();
2209
2210 // ... and one of the following shall hold:
2211 // -- The second or the third operand (but not both) is a throw-
2212 // expression; the result is of the type of the other and is an rvalue.
2213 bool LThrow = isa<CXXThrowExpr>(LHS);
2214 bool RThrow = isa<CXXThrowExpr>(RHS);
2215 if (LThrow && !RThrow)
2216 return RTy;
2217 if (RThrow && !LThrow)
2218 return LTy;
2219
2220 // -- Both the second and third operands have type void; the result is of
2221 // type void and is an rvalue.
2222 if (LVoid && RVoid)
2223 return Context.VoidTy;
2224
2225 // Neither holds, error.
2226 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2227 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2228 << LHS->getSourceRange() << RHS->getSourceRange();
2229 return QualType();
2230 }
2231
2232 // Neither is void.
2233
2234 // C++0x 5.16p3
2235 // Otherwise, if the second and third operand have different types, and
2236 // either has (cv) class type, and attempt is made to convert each of those
2237 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002238 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002239 (LTy->isRecordType() || RTy->isRecordType())) {
2240 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2241 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002242 QualType L2RType, R2LType;
2243 bool HaveL2R, HaveR2L;
2244 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002245 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002246 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002247 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002248
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002249 // If both can be converted, [...] the program is ill-formed.
2250 if (HaveL2R && HaveR2L) {
2251 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2252 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2253 return QualType();
2254 }
2255
2256 // If exactly one conversion is possible, that conversion is applied to
2257 // the chosen operand and the converted operands are used in place of the
2258 // original operands for the remainder of this section.
2259 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002260 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002261 return QualType();
2262 LTy = LHS->getType();
2263 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002264 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002265 return QualType();
2266 RTy = RHS->getType();
2267 }
2268 }
2269
2270 // C++0x 5.16p4
2271 // If the second and third operands are lvalues and have the same type,
2272 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002273 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002274 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2275 RHS->isLvalue(Context) == Expr::LV_Valid)
2276 return LTy;
2277
2278 // C++0x 5.16p5
2279 // Otherwise, the result is an rvalue. If the second and third operands
2280 // do not have the same type, and either has (cv) class type, ...
2281 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2282 // ... overload resolution is used to determine the conversions (if any)
2283 // to be applied to the operands. If the overload resolution fails, the
2284 // program is ill-formed.
2285 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2286 return QualType();
2287 }
2288
2289 // C++0x 5.16p6
2290 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2291 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002292 DefaultFunctionArrayLvalueConversion(LHS);
2293 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002294 LTy = LHS->getType();
2295 RTy = RHS->getType();
2296
2297 // After those conversions, one of the following shall hold:
2298 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002299 // is of that type. If the operands have class type, the result
2300 // is a prvalue temporary of the result type, which is
2301 // copy-initialized from either the second operand or the third
2302 // operand depending on the value of the first operand.
2303 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2304 if (LTy->isRecordType()) {
2305 // The operands have class type. Make a temporary copy.
2306 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2307 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2308 SourceLocation(),
2309 Owned(LHS));
2310 if (LHSCopy.isInvalid())
2311 return QualType();
2312
2313 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2314 SourceLocation(),
2315 Owned(RHS));
2316 if (RHSCopy.isInvalid())
2317 return QualType();
2318
2319 LHS = LHSCopy.takeAs<Expr>();
2320 RHS = RHSCopy.takeAs<Expr>();
2321 }
2322
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002323 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002324 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002325
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002326 // Extension: conditional operator involving vector types.
2327 if (LTy->isVectorType() || RTy->isVectorType())
2328 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2329
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002330 // -- The second and third operands have arithmetic or enumeration type;
2331 // the usual arithmetic conversions are performed to bring them to a
2332 // common type, and the result is of that type.
2333 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2334 UsualArithmeticConversions(LHS, RHS);
2335 return LHS->getType();
2336 }
2337
2338 // -- The second and third operands have pointer type, or one has pointer
2339 // type and the other is a null pointer constant; pointer conversions
2340 // and qualification conversions are performed to bring them to their
2341 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002342 // -- The second and third operands have pointer to member type, or one has
2343 // pointer to member type and the other is a null pointer constant;
2344 // pointer to member conversions and qualification conversions are
2345 // performed to bring them to a common type, whose cv-qualification
2346 // shall match the cv-qualification of either the second or the third
2347 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002348 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002349 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002350 isSFINAEContext()? 0 : &NonStandardCompositeType);
2351 if (!Composite.isNull()) {
2352 if (NonStandardCompositeType)
2353 Diag(QuestionLoc,
2354 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2355 << LTy << RTy << Composite
2356 << LHS->getSourceRange() << RHS->getSourceRange();
2357
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002358 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002359 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002360
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002361 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002362 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2363 if (!Composite.isNull())
2364 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002365
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002366 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2367 << LHS->getType() << RHS->getType()
2368 << LHS->getSourceRange() << RHS->getSourceRange();
2369 return QualType();
2370}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002371
2372/// \brief Find a merged pointer type and convert the two expressions to it.
2373///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002374/// This finds the composite pointer type (or member pointer type) for @p E1
2375/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2376/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002377/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002378///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002379/// \param Loc The location of the operator requiring these two expressions to
2380/// be converted to the composite pointer type.
2381///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002382/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2383/// a non-standard (but still sane) composite type to which both expressions
2384/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2385/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002386QualType Sema::FindCompositePointerType(SourceLocation Loc,
2387 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002388 bool *NonStandardCompositeType) {
2389 if (NonStandardCompositeType)
2390 *NonStandardCompositeType = false;
2391
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002392 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2393 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002395 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2396 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002397 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002398
2399 // C++0x 5.9p2
2400 // Pointer conversions and qualification conversions are performed on
2401 // pointer operands to bring them to their composite pointer type. If
2402 // one operand is a null pointer constant, the composite pointer type is
2403 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002404 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002405 if (T2->isMemberPointerType())
2406 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2407 else
2408 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002409 return T2;
2410 }
Douglas Gregorce940492009-09-25 04:25:58 +00002411 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002412 if (T1->isMemberPointerType())
2413 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2414 else
2415 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002416 return T1;
2417 }
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Douglas Gregor20b3e992009-08-24 17:42:35 +00002419 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002420 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2421 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002422 return QualType();
2423
2424 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2425 // the other has type "pointer to cv2 T" and the composite pointer type is
2426 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2427 // Otherwise, the composite pointer type is a pointer type similar to the
2428 // type of one of the operands, with a cv-qualification signature that is
2429 // the union of the cv-qualification signatures of the operand types.
2430 // In practice, the first part here is redundant; it's subsumed by the second.
2431 // What we do here is, we build the two possible composite types, and try the
2432 // conversions in both directions. If only one works, or if the two composite
2433 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002434 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002435 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2436 QualifierVector QualifierUnion;
2437 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2438 ContainingClassVector;
2439 ContainingClassVector MemberOfClass;
2440 QualType Composite1 = Context.getCanonicalType(T1),
2441 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002442 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002443 do {
2444 const PointerType *Ptr1, *Ptr2;
2445 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2446 (Ptr2 = Composite2->getAs<PointerType>())) {
2447 Composite1 = Ptr1->getPointeeType();
2448 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002449
2450 // If we're allowed to create a non-standard composite type, keep track
2451 // of where we need to fill in additional 'const' qualifiers.
2452 if (NonStandardCompositeType &&
2453 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2454 NeedConstBefore = QualifierUnion.size();
2455
Douglas Gregor20b3e992009-08-24 17:42:35 +00002456 QualifierUnion.push_back(
2457 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2458 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2459 continue;
2460 }
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Douglas Gregor20b3e992009-08-24 17:42:35 +00002462 const MemberPointerType *MemPtr1, *MemPtr2;
2463 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2464 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2465 Composite1 = MemPtr1->getPointeeType();
2466 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002467
2468 // If we're allowed to create a non-standard composite type, keep track
2469 // of where we need to fill in additional 'const' qualifiers.
2470 if (NonStandardCompositeType &&
2471 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2472 NeedConstBefore = QualifierUnion.size();
2473
Douglas Gregor20b3e992009-08-24 17:42:35 +00002474 QualifierUnion.push_back(
2475 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2476 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2477 MemPtr2->getClass()));
2478 continue;
2479 }
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Douglas Gregor20b3e992009-08-24 17:42:35 +00002481 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Douglas Gregor20b3e992009-08-24 17:42:35 +00002483 // Cannot unwrap any more types.
2484 break;
2485 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002487 if (NeedConstBefore && NonStandardCompositeType) {
2488 // Extension: Add 'const' to qualifiers that come before the first qualifier
2489 // mismatch, so that our (non-standard!) composite type meets the
2490 // requirements of C++ [conv.qual]p4 bullet 3.
2491 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2492 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2493 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2494 *NonStandardCompositeType = true;
2495 }
2496 }
2497 }
2498
Douglas Gregor20b3e992009-08-24 17:42:35 +00002499 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002500 ContainingClassVector::reverse_iterator MOC
2501 = MemberOfClass.rbegin();
2502 for (QualifierVector::reverse_iterator
2503 I = QualifierUnion.rbegin(),
2504 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002505 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002506 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002507 if (MOC->first && MOC->second) {
2508 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002509 Composite1 = Context.getMemberPointerType(
2510 Context.getQualifiedType(Composite1, Quals),
2511 MOC->first);
2512 Composite2 = Context.getMemberPointerType(
2513 Context.getQualifiedType(Composite2, Quals),
2514 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002515 } else {
2516 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002517 Composite1
2518 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2519 Composite2
2520 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002521 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002522 }
2523
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002524 // Try to convert to the first composite pointer type.
2525 InitializedEntity Entity1
2526 = InitializedEntity::InitializeTemporary(Composite1);
2527 InitializationKind Kind
2528 = InitializationKind::CreateCopy(Loc, SourceLocation());
2529 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2530 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002531
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002532 if (E1ToC1 && E2ToC1) {
2533 // Conversion to Composite1 is viable.
2534 if (!Context.hasSameType(Composite1, Composite2)) {
2535 // Composite2 is a different type from Composite1. Check whether
2536 // Composite2 is also viable.
2537 InitializedEntity Entity2
2538 = InitializedEntity::InitializeTemporary(Composite2);
2539 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2540 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2541 if (E1ToC2 && E2ToC2) {
2542 // Both Composite1 and Composite2 are viable and are different;
2543 // this is an ambiguity.
2544 return QualType();
2545 }
2546 }
2547
2548 // Convert E1 to Composite1
2549 OwningExprResult E1Result
2550 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2551 if (E1Result.isInvalid())
2552 return QualType();
2553 E1 = E1Result.takeAs<Expr>();
2554
2555 // Convert E2 to Composite1
2556 OwningExprResult E2Result
2557 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2558 if (E2Result.isInvalid())
2559 return QualType();
2560 E2 = E2Result.takeAs<Expr>();
2561
2562 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002563 }
2564
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002565 // Check whether Composite2 is viable.
2566 InitializedEntity Entity2
2567 = InitializedEntity::InitializeTemporary(Composite2);
2568 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2569 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2570 if (!E1ToC2 || !E2ToC2)
2571 return QualType();
2572
2573 // Convert E1 to Composite2
2574 OwningExprResult E1Result
2575 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2576 if (E1Result.isInvalid())
2577 return QualType();
2578 E1 = E1Result.takeAs<Expr>();
2579
2580 // Convert E2 to Composite2
2581 OwningExprResult E2Result
2582 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2583 if (E2Result.isInvalid())
2584 return QualType();
2585 E2 = E2Result.takeAs<Expr>();
2586
2587 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002588}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002589
Anders Carlssondef11992009-05-30 20:36:53 +00002590Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002591 if (!Context.getLangOptions().CPlusPlus)
2592 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Douglas Gregor51326552009-12-24 18:51:59 +00002594 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2595
Ted Kremenek6217b802009-07-29 21:53:49 +00002596 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002597 if (!RT)
2598 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002600 // If this is the result of a call or an Objective-C message send expression,
2601 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002602 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002603 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00002604 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002605 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2606 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2607 if (MD->getResultType()->isReferenceType())
2608 return Owned(E);
2609 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00002610 }
John McCall86ff3082010-02-04 22:26:26 +00002611
2612 // That should be enough to guarantee that this type is complete.
2613 // If it has a trivial destructor, we can avoid the extra copy.
2614 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2615 if (RD->hasTrivialDestructor())
2616 return Owned(E);
2617
Douglas Gregordb89f282010-07-01 22:47:18 +00002618 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00002619 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00002620 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002621 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002622 CheckDestructorAccess(E->getExprLoc(), Destructor,
2623 PDiag(diag::err_access_dtor_temp)
2624 << E->getType());
2625 }
Anders Carlssondef11992009-05-30 20:36:53 +00002626 // FIXME: Add the temporary to the temporaries vector.
2627 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2628}
2629
Anders Carlsson0ece4912009-12-15 20:51:39 +00002630Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002631 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002632
John McCall323ed742010-05-06 08:58:33 +00002633 // Check any implicit conversions within the expression.
2634 CheckImplicitConversions(SubExpr);
2635
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002636 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2637 assert(ExprTemporaries.size() >= FirstTemporary);
2638 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002639 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002641 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002642 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002643 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002644 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2645 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002647 return E;
2648}
2649
Douglas Gregor90f93822009-12-22 22:17:25 +00002650Sema::OwningExprResult
2651Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2652 if (SubExpr.isInvalid())
2653 return ExprError();
2654
2655 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2656}
2657
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002658FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2659 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2660 assert(ExprTemporaries.size() >= FirstTemporary);
2661
2662 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2663 CXXTemporary **Temporaries =
2664 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2665
2666 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2667
2668 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2669 ExprTemporaries.end());
2670
2671 return E;
2672}
2673
Mike Stump1eb44332009-09-09 15:08:12 +00002674Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002675Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002676 tok::TokenKind OpKind, TypeTy *&ObjectType,
2677 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002678 // Since this might be a postfix expression, get rid of ParenListExprs.
2679 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002681 Expr *BaseExpr = (Expr*)Base.get();
2682 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002684 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002685 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002686 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002687 // If we have a pointer to a dependent type and are using the -> operator,
2688 // the object type is the type that the pointer points to. We might still
2689 // have enough information about that type to do something useful.
2690 if (OpKind == tok::arrow)
2691 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2692 BaseType = Ptr->getPointeeType();
2693
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002694 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002695 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002696 return move(Base);
2697 }
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002699 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002700 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002701 // returned, with the original second operand.
2702 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002703 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002704 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002705 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002706 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002707
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002708 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002709 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002710 BaseExpr = (Expr*)Base.get();
2711 if (BaseExpr == NULL)
2712 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002713 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002714 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002715 BaseType = BaseExpr->getType();
2716 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002717 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002718 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002719 for (unsigned i = 0; i < Locations.size(); i++)
2720 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002721 return ExprError();
2722 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002723 }
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Douglas Gregor31658df2009-11-20 19:58:21 +00002725 if (BaseType->isPointerType())
2726 BaseType = BaseType->getPointeeType();
2727 }
Mike Stump1eb44332009-09-09 15:08:12 +00002728
2729 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002730 // vector types or Objective-C interfaces. Just return early and let
2731 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002732 if (!BaseType->isRecordType()) {
2733 // C++ [basic.lookup.classref]p2:
2734 // [...] If the type of the object expression is of pointer to scalar
2735 // type, the unqualified-id is looked up in the context of the complete
2736 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002737 //
2738 // This also indicates that we should be parsing a
2739 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002740 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002741 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002742 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002743 }
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Douglas Gregor03c57052009-11-17 05:17:33 +00002745 // The object type must be complete (or dependent).
2746 if (!BaseType->isDependentType() &&
2747 RequireCompleteType(OpLoc, BaseType,
2748 PDiag(diag::err_incomplete_member_access)))
2749 return ExprError();
2750
Douglas Gregorc68afe22009-09-03 21:38:09 +00002751 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002752 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002753 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002754 // type C (or of pointer to a class type C), the unqualified-id is looked
2755 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002756 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002757 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002758}
2759
Douglas Gregor77549082010-02-24 21:29:12 +00002760Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2761 ExprArg MemExpr) {
2762 Expr *E = (Expr *) MemExpr.get();
2763 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2764 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2765 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002766 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002767
2768 return ActOnCallExpr(/*Scope*/ 0,
2769 move(MemExpr),
2770 /*LPLoc*/ ExpectedLParenLoc,
2771 Sema::MultiExprArg(*this, 0, 0),
2772 /*CommaLocs*/ 0,
2773 /*RPLoc*/ ExpectedLParenLoc);
2774}
Douglas Gregord4dca082010-02-24 18:44:31 +00002775
Douglas Gregorb57fb492010-02-24 22:38:50 +00002776Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2777 SourceLocation OpLoc,
2778 tok::TokenKind OpKind,
2779 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002780 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002781 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002782 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002783 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002784 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002785 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002786
2787 // C++ [expr.pseudo]p2:
2788 // The left-hand side of the dot operator shall be of scalar type. The
2789 // left-hand side of the arrow operator shall be of pointer to scalar type.
2790 // This scalar type is the object type.
2791 Expr *BaseE = (Expr *)Base.get();
2792 QualType ObjectType = BaseE->getType();
2793 if (OpKind == tok::arrow) {
2794 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2795 ObjectType = Ptr->getPointeeType();
2796 } else if (!BaseE->isTypeDependent()) {
2797 // The user wrote "p->" when she probably meant "p."; fix it.
2798 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2799 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002800 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002801 if (isSFINAEContext())
2802 return ExprError();
2803
2804 OpKind = tok::period;
2805 }
2806 }
2807
2808 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2809 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2810 << ObjectType << BaseE->getSourceRange();
2811 return ExprError();
2812 }
2813
2814 // C++ [expr.pseudo]p2:
2815 // [...] The cv-unqualified versions of the object type and of the type
2816 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002817 if (DestructedTypeInfo) {
2818 QualType DestructedType = DestructedTypeInfo->getType();
2819 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002820 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002821 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2822 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2823 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2824 << ObjectType << DestructedType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002825 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002826
2827 // Recover by setting the destructed type to the object type.
2828 DestructedType = ObjectType;
2829 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2830 DestructedTypeStart);
2831 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2832 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002833 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002834
Douglas Gregorb57fb492010-02-24 22:38:50 +00002835 // C++ [expr.pseudo]p2:
2836 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2837 // form
2838 //
2839 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2840 //
2841 // shall designate the same scalar type.
2842 if (ScopeTypeInfo) {
2843 QualType ScopeType = ScopeTypeInfo->getType();
2844 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00002845 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002846
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002847 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00002848 diag::err_pseudo_dtor_type_mismatch)
2849 << ObjectType << ScopeType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002850 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002851
2852 ScopeType = QualType();
2853 ScopeTypeInfo = 0;
2854 }
2855 }
2856
2857 OwningExprResult Result
2858 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2859 Base.takeAs<Expr>(),
2860 OpKind == tok::arrow,
2861 OpLoc,
2862 (NestedNameSpecifier *) SS.getScopeRep(),
2863 SS.getRange(),
2864 ScopeTypeInfo,
2865 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002866 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002867 Destructed));
2868
Douglas Gregorb57fb492010-02-24 22:38:50 +00002869 if (HasTrailingLParen)
2870 return move(Result);
2871
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002872 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002873}
2874
2875Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2876 SourceLocation OpLoc,
2877 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002878 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002879 UnqualifiedId &FirstTypeName,
2880 SourceLocation CCLoc,
2881 SourceLocation TildeLoc,
2882 UnqualifiedId &SecondTypeName,
2883 bool HasTrailingLParen) {
2884 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2885 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2886 "Invalid first type name in pseudo-destructor");
2887 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2888 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2889 "Invalid second type name in pseudo-destructor");
2890
2891 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002892
2893 // C++ [expr.pseudo]p2:
2894 // The left-hand side of the dot operator shall be of scalar type. The
2895 // left-hand side of the arrow operator shall be of pointer to scalar type.
2896 // This scalar type is the object type.
2897 QualType ObjectType = BaseE->getType();
2898 if (OpKind == tok::arrow) {
2899 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2900 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002901 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002902 // The user wrote "p->" when she probably meant "p."; fix it.
2903 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002904 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002905 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002906 if (isSFINAEContext())
2907 return ExprError();
2908
2909 OpKind = tok::period;
2910 }
2911 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002912
2913 // Compute the object type that we should use for name lookup purposes. Only
2914 // record types and dependent types matter.
2915 void *ObjectTypePtrForLookup = 0;
2916 if (!SS.isSet()) {
Gabor Greif170e5082010-06-17 11:29:31 +00002917 ObjectTypePtrForLookup = const_cast<RecordType*>(
2918 ObjectType->getAs<RecordType>());
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002919 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2920 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2921 }
Douglas Gregor77549082010-02-24 21:29:12 +00002922
Douglas Gregorb57fb492010-02-24 22:38:50 +00002923 // Convert the name of the type being destructed (following the ~) into a
2924 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002925 QualType DestructedType;
2926 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002927 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002928 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2929 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2930 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002931 S, &SS, true, ObjectTypePtrForLookup);
2932 if (!T &&
2933 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2934 (!SS.isSet() && ObjectType->isDependentType()))) {
2935 // The name of the type being destroyed is a dependent name, and we
2936 // couldn't find anything useful in scope. Just store the identifier and
2937 // it's location, and we'll perform (qualified) name lookup again at
2938 // template instantiation time.
2939 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2940 SecondTypeName.StartLocation);
2941 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002942 Diag(SecondTypeName.StartLocation,
2943 diag::err_pseudo_dtor_destructor_non_type)
2944 << SecondTypeName.Identifier << ObjectType;
2945 if (isSFINAEContext())
2946 return ExprError();
2947
2948 // Recover by assuming we had the right type all along.
2949 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002950 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002951 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002952 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002953 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002954 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002955 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2956 TemplateId->getTemplateArgs(),
2957 TemplateId->NumArgs);
2958 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2959 TemplateId->TemplateNameLoc,
2960 TemplateId->LAngleLoc,
2961 TemplateArgsPtr,
2962 TemplateId->RAngleLoc);
2963 if (T.isInvalid() || !T.get()) {
2964 // Recover by assuming we had the right type all along.
2965 DestructedType = ObjectType;
2966 } else
2967 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002968 }
2969
Douglas Gregorb57fb492010-02-24 22:38:50 +00002970 // If we've performed some kind of recovery, (re-)build the type source
2971 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002972 if (!DestructedType.isNull()) {
2973 if (!DestructedTypeInfo)
2974 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002975 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002976 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2977 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002978
2979 // Convert the name of the scope type (the type prior to '::') into a type.
2980 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002981 QualType ScopeType;
2982 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2983 FirstTypeName.Identifier) {
2984 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2985 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2986 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002987 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002988 if (!T) {
2989 Diag(FirstTypeName.StartLocation,
2990 diag::err_pseudo_dtor_destructor_non_type)
2991 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002992
Douglas Gregorb57fb492010-02-24 22:38:50 +00002993 if (isSFINAEContext())
2994 return ExprError();
2995
2996 // Just drop this type. It's unnecessary anyway.
2997 ScopeType = QualType();
2998 } else
2999 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003000 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003001 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003002 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003003 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3004 TemplateId->getTemplateArgs(),
3005 TemplateId->NumArgs);
3006 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
3007 TemplateId->TemplateNameLoc,
3008 TemplateId->LAngleLoc,
3009 TemplateArgsPtr,
3010 TemplateId->RAngleLoc);
3011 if (T.isInvalid() || !T.get()) {
3012 // Recover by dropping this type.
3013 ScopeType = QualType();
3014 } else
3015 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003016 }
3017 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003018
3019 if (!ScopeType.isNull() && !ScopeTypeInfo)
3020 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3021 FirstTypeName.StartLocation);
3022
3023
Douglas Gregorb57fb492010-02-24 22:38:50 +00003024 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003025 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003026 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003027}
3028
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003029CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003030 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003031 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003032 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3033 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003034 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3035
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003036 MemberExpr *ME =
3037 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3038 SourceLocation(), Method->getType());
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003039 QualType ResultType = Method->getCallResultType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003040 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3041 CXXMemberCallExpr *CE =
3042 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3043 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003044 return CE;
3045}
3046
Anders Carlsson165a0a02009-05-17 18:41:29 +00003047Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3048 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003049 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00003050 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregoreecf38f2010-05-06 21:39:56 +00003051 else
3052 return ExprError();
3053
Anders Carlsson165a0a02009-05-17 18:41:29 +00003054 return Owned(FullExpr);
3055}