blob: 021b4afb25d14eb88a0d1898729e8159481af993 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000021#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Parse/DeclSpec.h"
Douglas Gregore610ada2010-02-24 18:44:31 +000026#include "clang/Parse/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000027#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000028using namespace clang;
29
Douglas Gregorfe17d252010-02-16 19:09:40 +000030Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
31 IdentifierInfo &II,
32 SourceLocation NameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000033 Scope *S, CXXScopeSpec &SS,
Douglas Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000055 // See also PR6358 and PR6359.
Sebastian Redla771d222010-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 Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000070 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
71
72 bool AlreadySearched = false;
73 bool LookAtPrefix = true;
Sebastian Redla771d222010-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 Carruth8f254812010-02-21 10:19:54 +000082 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000083 //
Sebastian Redla771d222010-07-07 23:17:38 +000084 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000085 //
Sebastian Redla771d222010-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 Gregorfe17d252010-02-16 19:09:40 +000088 //
Sebastian Redla771d222010-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 Gregor46841e12010-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 Gregor46841e12010-02-23 00:15:22 +0000109 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 LookupCtx = computeDeclContext(SearchType);
111 isDependent = SearchType->isDependentType();
112 } else {
113 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000114 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000115 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000116
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000117 LookInScope = false;
Douglas Gregorfe17d252010-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 Gregor678f90d2010-02-25 01:56:36 +0000145 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-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 Gregorfe17d252010-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 McCalle78aac42010-03-10 03:28:59 +0000176 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
177 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-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 Bagnarad7548482010-05-19 21:37:53 +0000245 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
246 Range, NameLoc).getAsOpaquePtr();
Douglas Gregorfe17d252010-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 Gregor9da64192010-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 Gregor876cec22010-06-02 06:16:02 +0000268 Qualifiers Quals;
269 QualType T
270 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
271 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000272 if (T->getAs<RecordType>() &&
273 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
274 return ExprError();
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000275
Douglas Gregor9da64192010-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:
299 // When typeid is applied to an expression other than an lvalue of a
300 // polymorphic class type [...] [the] expression is an unevaluated
301 // operand. [...]
Douglas Gregor88d292c2010-05-13 16:44:06 +0000302 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000303 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000304
305 // We require a vtable to query the type at run time.
306 MarkVTableUsed(TypeidLoc, RecordD);
307 }
Douglas Gregor9da64192010-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 Gregor876cec22010-06-02 06:16:02 +0000315 Qualifiers Quals;
316 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
317 if (!Context.hasSameType(T, UnqualT)) {
318 T = UnqualT;
319 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, E->isLvalue(Context));
Douglas Gregor9da64192010-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 Redl6d4256c2009-03-15 17:47:39 +0000337Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000338Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
339 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000340 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000341 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000342 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000343
Chris Lattnerec7f7732008-11-20 05:51:55 +0000344 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000345 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
346 LookupQualifiedName(R, StdNamespace);
John McCall67c00872009-12-02 08:25:40 +0000347 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000348 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor9da64192010-04-26 22:37:10 +0000350
Sebastian Redlc4704762008-11-11 11:37:55 +0000351 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor9da64192010-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 Redlc4704762008-11-11 11:37:55 +0000362
Douglas Gregor9da64192010-04-26 22:37:10 +0000363 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000364 }
Mike Stump11289f42009-09-09 15:08:12 +0000365
Douglas Gregor9da64192010-04-26 22:37:10 +0000366 // The operand is an expression.
367 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000368}
369
Steve Naroff66356bd2007-09-16 14:56:35 +0000370/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000371Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000372Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000373 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000374 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000375 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
376 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000377}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000378
Sebastian Redl576fd422009-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 Lattnerb7e656b2008-02-26 00:51:44 +0000385/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000386Action::OwningExprResult
387Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-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 Gregor247894b2009-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,
404 E->isLvalue(Context) == Expr::LV_Valid);
405
Sebastian Redl4de47b42009-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 McCall2e6567a2010-04-22 01:10:34 +0000411 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000412 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000413 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000414 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000415 }
416 if (!isPointer || !Ty->isVoidType()) {
417 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000418 PDiag(isPointer ? diag::err_throw_incomplete_ptr
419 : diag::err_throw_incomplete)
420 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000421 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000422
Douglas Gregore8154332010-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 Redl4de47b42009-04-27 20:27:31 +0000427 }
428
John McCall2e6567a2010-04-22 01:10:34 +0000429 // Initialize the exception result. This implicitly weeds out
430 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000431 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000432 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000433 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
434 /*NRVO=*/false);
John McCall2e6567a2010-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 Gregor88d292c2010-05-13 16:44:06 +0000441
Eli Friedman91a3d272010-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 Gregor88d292c2010-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 Friedman91a3d272010-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 Gregorbac74902010-07-01 14:13:13 +0000456 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000457 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000458 if (!Destructor)
459 return false;
460
461 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
462 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregore1823702010-07-07 23:37:33 +0000463 PDiag(diag::err_access_dtor_temp) << Ty);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000464 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000465}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000466
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000467Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-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 McCall87fe5d52010-05-20 01:18:31 +0000472 DeclContext *DC = getFunctionLevelDeclContext();
473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000474 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000475 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000476 MD->getThisType(Context),
477 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000478
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000479 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000480}
Argyrios Kyrtzidis857fcc22008-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 Redl6d4256c2009-03-15 17:47:39 +0000486Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000487Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
488 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000489 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000490 SourceLocation *CommaLocs,
491 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000492 if (!TypeRep)
493 return ExprError();
494
John McCall97513962010-01-15 18:39:57 +0000495 TypeSourceInfo *TInfo;
496 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
497 if (!TInfo)
498 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000499 unsigned NumExprs = exprs.size();
500 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000501 SourceLocation TyBeginLoc = TypeRange.getBegin();
502 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
503
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000504 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000505 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000506 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000507
508 return Owned(CXXUnresolvedConstructExpr::Create(Context,
509 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000510 LParenLoc,
511 Exprs, NumExprs,
512 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000513 }
514
Anders Carlsson55243162009-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 Jahanian9a14b842009-10-23 21:01:39 +0000523
Anders Carlsson55243162009-08-27 03:53:50 +0000524 if (RequireNonAbstractType(TyBeginLoc, Ty,
525 diag::err_allocation_of_abstract_type))
526 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000527
528
Douglas Gregordd04d332009-01-16 18:33:17 +0000529 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-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 Carlssonf10e4142009-08-07 22:21:05 +0000535 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000536 CXXBaseSpecifierArray BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +0000537 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
538 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000539 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000540
541 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000542
543 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000544 TInfo, TyBeginLoc, Kind,
Anders Carlsson5d270e82010-04-24 18:38:56 +0000545 Exprs[0], BasePath,
546 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000547 }
548
Douglas Gregore1823702010-07-07 23:37:33 +0000549 if (const RecordType *RT = Ty->getAs<RecordType>()) {
550 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000551
Douglas Gregore1823702010-07-07 23:37:33 +0000552 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
553 !Record->hasTrivialDestructor()) {
554 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
555 InitializationKind Kind
556 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
557 LParenLoc, RParenLoc)
558 : InitializationKind::CreateValue(TypeRange.getBegin(),
559 LParenLoc, RParenLoc);
560 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
561 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
562 move(exprs));
563
564 // FIXME: Improve AST representation?
565 return move(Result);
566 }
567
568 // Fall through to value-initialize an object of class type that
569 // doesn't have a user-declared default constructor.
Douglas Gregordd04d332009-01-16 18:33:17 +0000570 }
571
572 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000573 // If the expression list specifies more than a single value, the type shall
574 // be a class with a suitably declared constructor.
575 //
576 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000577 return ExprError(Diag(CommaLocs[0],
578 diag::err_builtin_func_cast_more_than_one_arg)
579 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000580
581 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000582 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000583 // The expression T(), where T is a simple-type-specifier for a non-array
584 // complete object type or the (possibly cv-qualified) void type, creates an
585 // rvalue of the specified type, which is value-initialized.
586 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000587 exprs.release();
Douglas Gregore1823702010-07-07 23:37:33 +0000588 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000589}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000590
591
Sebastian Redlbd150f42008-11-21 19:14:01 +0000592/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
593/// @code new (memory) int[size][4] @endcode
594/// or
595/// @code ::new Foo(23, "hello") @endcode
596/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000597Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000598Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000599 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000600 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000601 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000602 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000603 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000604 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000605 // If the specified type is an array, unwrap it and save the expression.
606 if (D.getNumTypeObjects() > 0 &&
607 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
608 DeclaratorChunk &Chunk = D.getTypeObject(0);
609 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000610 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
611 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000612 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000613 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
614 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000615
616 if (ParenTypeId) {
617 // Can't have dynamic array size when the type-id is in parentheses.
618 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
619 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
620 !NumElts->isIntegerConstantExpr(Context)) {
621 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
622 << NumElts->getSourceRange();
623 return ExprError();
624 }
625 }
626
Sebastian Redl351bb782008-12-02 14:43:59 +0000627 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000628 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000629 }
630
Douglas Gregor73341c42009-09-11 00:18:58 +0000631 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000632 if (ArraySize) {
633 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000634 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
635 break;
636
637 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
638 if (Expr *NumElts = (Expr *)Array.NumElts) {
639 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
640 !NumElts->isIntegerConstantExpr(Context)) {
641 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
642 << NumElts->getSourceRange();
643 return ExprError();
644 }
645 }
646 }
647 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000648
John McCallbcd03502009-12-07 02:54:59 +0000649 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCall8cb7bdf2010-06-04 23:28:52 +0000650 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
651 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000652 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000653 return ExprError();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000654
655 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000656 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000657 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000658 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000659 PlacementRParen,
660 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000661 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000662 D.getSourceRange().getBegin(),
Ted Kremenekabb1f912010-06-25 22:48:49 +0000663 R,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000664 Owned(ArraySize),
665 ConstructorLParen,
666 move(ConstructorArgs),
667 ConstructorRParen);
668}
669
Mike Stump11289f42009-09-09 15:08:12 +0000670Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000671Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
672 SourceLocation PlacementLParen,
673 MultiExprArg PlacementArgs,
674 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000675 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000676 QualType AllocType,
677 SourceLocation TypeLoc,
678 SourceRange TypeRange,
679 ExprArg ArraySizeE,
680 SourceLocation ConstructorLParen,
681 MultiExprArg ConstructorArgs,
682 SourceLocation ConstructorRParen) {
683 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000684 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000685
Douglas Gregorcda95f42010-05-16 16:01:03 +0000686 // Per C++0x [expr.new]p5, the type being constructed may be a
687 // typedef of an array type.
688 if (!ArraySizeE.get()) {
689 if (const ConstantArrayType *Array
690 = Context.getAsConstantArrayType(AllocType)) {
691 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
692 Context.getSizeType(),
693 TypeRange.getEnd()));
694 AllocType = Array->getElementType();
695 }
696 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000697
Douglas Gregorcda95f42010-05-16 16:01:03 +0000698 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000699
Sebastian Redlbd150f42008-11-21 19:14:01 +0000700 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
701 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000702 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000703 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor4799d032010-06-30 00:20:43 +0000704
Sebastian Redl351bb782008-12-02 14:43:59 +0000705 QualType SizeType = ArraySize->getType();
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000706
Douglas Gregor4799d032010-06-30 00:20:43 +0000707 OwningExprResult ConvertedSize
708 = ConvertToIntegralOrEnumerationType(StartLoc, move(ArraySizeE),
709 PDiag(diag::err_array_size_not_integral),
710 PDiag(diag::err_array_size_incomplete_type)
711 << ArraySize->getSourceRange(),
712 PDiag(diag::err_array_size_explicit_conversion),
713 PDiag(diag::note_array_size_conversion),
714 PDiag(diag::err_array_size_ambiguous_conversion),
715 PDiag(diag::note_array_size_conversion),
716 PDiag(getLangOptions().CPlusPlus0x? 0
717 : diag::ext_array_size_conversion));
718 if (ConvertedSize.isInvalid())
719 return ExprError();
720
721 ArraySize = ConvertedSize.takeAs<Expr>();
722 ArraySizeE = Owned(ArraySize);
723 SizeType = ArraySize->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000724 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000725 return ExprError();
726
Sebastian Redl351bb782008-12-02 14:43:59 +0000727 // Let's see if this is a constant < 0. If so, we reject it out of hand.
728 // We don't care about special rules, so we tell the machinery it's not
729 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000730 if (!ArraySize->isValueDependent()) {
731 llvm::APSInt Value;
732 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
733 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000734 llvm::APInt::getNullValue(Value.getBitWidth()),
735 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000736 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
737 diag::err_typecheck_negative_array_size)
738 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000739 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000740 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000741
Eli Friedman06ed2a52009-10-20 08:27:19 +0000742 ImpCastExprToType(ArraySize, Context.getSizeType(),
743 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000744 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000745
Sebastian Redlbd150f42008-11-21 19:14:01 +0000746 FunctionDecl *OperatorNew = 0;
747 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000748 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
749 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000750
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000751 if (!AllocType->isDependentType() &&
752 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
753 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000754 SourceRange(PlacementLParen, PlacementRParen),
755 UseGlobal, AllocType, ArraySize, PlaceArgs,
756 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000757 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000758 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000759 if (OperatorNew) {
760 // Add default arguments, if any.
761 const FunctionProtoType *Proto =
762 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000763 VariadicCallType CallType =
764 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000765
766 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
767 Proto, 1, PlaceArgs, NumPlaceArgs,
768 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000769 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000770
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000771 NumPlaceArgs = AllPlaceArgs.size();
772 if (NumPlaceArgs > 0)
773 PlaceArgs = &AllPlaceArgs[0];
774 }
775
Sebastian Redlbd150f42008-11-21 19:14:01 +0000776 bool Init = ConstructorLParen.isValid();
777 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000778 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000779 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
780 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000781 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
782
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000783 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000784 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000785 SourceRange InitRange(ConsArgs[0]->getLocStart(),
786 ConsArgs[NumConsArgs - 1]->getLocEnd());
787
788 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
789 return ExprError();
790 }
791
Douglas Gregor85dabae2009-12-16 01:38:02 +0000792 if (!AllocType->isDependentType() &&
793 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
794 // C++0x [expr.new]p15:
795 // A new-expression that creates an object of type T initializes that
796 // object as follows:
797 InitializationKind Kind
798 // - If the new-initializer is omitted, the object is default-
799 // initialized (8.5); if no initialization is performed,
800 // the object has indeterminate value
801 = !Init? InitializationKind::CreateDefault(TypeLoc)
802 // - Otherwise, the new-initializer is interpreted according to the
803 // initialization rules of 8.5 for direct-initialization.
804 : InitializationKind::CreateDirect(TypeLoc,
805 ConstructorLParen,
806 ConstructorRParen);
807
Douglas Gregor85dabae2009-12-16 01:38:02 +0000808 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000809 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000810 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000811 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
812 move(ConstructorArgs));
813 if (FullInit.isInvalid())
814 return ExprError();
815
816 // FullInit is our initializer; walk through it to determine if it's a
817 // constructor call, which CXXNewExpr handles directly.
818 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
819 if (CXXBindTemporaryExpr *Binder
820 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
821 FullInitExpr = Binder->getSubExpr();
822 if (CXXConstructExpr *Construct
823 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
824 Constructor = Construct->getConstructor();
825 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
826 AEnd = Construct->arg_end();
827 A != AEnd; ++A)
828 ConvertedConstructorArgs.push_back(A->Retain());
829 } else {
830 // Take the converted initializer.
831 ConvertedConstructorArgs.push_back(FullInit.release());
832 }
833 } else {
834 // No initialization required.
835 }
836
837 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000838 NumConsArgs = ConvertedConstructorArgs.size();
839 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000840 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000841
Douglas Gregor6642ca22010-02-26 05:06:18 +0000842 // Mark the new and delete operators as referenced.
843 if (OperatorNew)
844 MarkDeclarationReferenced(StartLoc, OperatorNew);
845 if (OperatorDelete)
846 MarkDeclarationReferenced(StartLoc, OperatorDelete);
847
Sebastian Redlbd150f42008-11-21 19:14:01 +0000848 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000849
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000850 PlacementArgs.release();
851 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000852 ArraySizeE.release();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000853
854 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000855 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
856 PlaceArgs, NumPlaceArgs, ParenTypeId,
857 ArraySize, Constructor, Init,
858 ConsArgs, NumConsArgs, OperatorDelete,
859 ResultType, StartLoc,
860 Init ? ConstructorRParen :
Ted Kremenekabb1f912010-06-25 22:48:49 +0000861 TypeRange.getEnd()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000862}
863
864/// CheckAllocatedType - Checks that a type is suitable as the allocated type
865/// in a new-expression.
866/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000867bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000868 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000869 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
870 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000871 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000872 return Diag(Loc, diag::err_bad_new_type)
873 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000874 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000875 return Diag(Loc, diag::err_bad_new_type)
876 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000877 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000878 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000879 PDiag(diag::err_new_incomplete_type)
880 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000881 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000882 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000883 diag::err_allocation_of_abstract_type))
884 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000885
Sebastian Redlbd150f42008-11-21 19:14:01 +0000886 return false;
887}
888
Douglas Gregor6642ca22010-02-26 05:06:18 +0000889/// \brief Determine whether the given function is a non-placement
890/// deallocation function.
891static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
892 if (FD->isInvalidDecl())
893 return false;
894
895 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
896 return Method->isUsualDeallocationFunction();
897
898 return ((FD->getOverloadedOperator() == OO_Delete ||
899 FD->getOverloadedOperator() == OO_Array_Delete) &&
900 FD->getNumParams() == 1);
901}
902
Sebastian Redlfaf68082008-12-03 20:26:15 +0000903/// FindAllocationFunctions - Finds the overloads of operator new and delete
904/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000905bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
906 bool UseGlobal, QualType AllocType,
907 bool IsArray, Expr **PlaceArgs,
908 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000909 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000910 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000911 // --- Choosing an allocation function ---
912 // C++ 5.3.4p8 - 14 & 18
913 // 1) If UseGlobal is true, only look in the global scope. Else, also look
914 // in the scope of the allocated class.
915 // 2) If an array size is given, look for operator new[], else look for
916 // operator new.
917 // 3) The first argument is always size_t. Append the arguments from the
918 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000919
920 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
921 // We don't care about the actual value of this argument.
922 // FIXME: Should the Sema create the expression and embed it in the syntax
923 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000924 IntegerLiteral Size(llvm::APInt::getNullValue(
925 Context.Target.getPointerWidth(0)),
926 Context.getSizeType(),
927 SourceLocation());
928 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000929 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
930
Douglas Gregor6642ca22010-02-26 05:06:18 +0000931 // C++ [expr.new]p8:
932 // If the allocated type is a non-array type, the allocation
933 // function’s name is operator new and the deallocation function’s
934 // name is operator delete. If the allocated type is an array
935 // type, the allocation function’s name is operator new[] and the
936 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000937 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
938 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000939 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
940 IsArray ? OO_Array_Delete : OO_Delete);
941
Sebastian Redlfaf68082008-12-03 20:26:15 +0000942 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000943 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000944 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000945 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000946 AllocArgs.size(), Record, /*AllowMissing=*/true,
947 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000948 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000949 }
950 if (!OperatorNew) {
951 // Didn't find a member overload. Look for a global one.
952 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000953 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000954 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000955 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
956 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000957 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000958 }
959
John McCall0f55a032010-04-20 02:18:25 +0000960 // We don't need an operator delete if we're running under
961 // -fno-exceptions.
962 if (!getLangOptions().Exceptions) {
963 OperatorDelete = 0;
964 return false;
965 }
966
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000967 // FindAllocationOverload can change the passed in arguments, so we need to
968 // copy them back.
969 if (NumPlaceArgs > 0)
970 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000971
Douglas Gregor6642ca22010-02-26 05:06:18 +0000972 // C++ [expr.new]p19:
973 //
974 // If the new-expression begins with a unary :: operator, the
975 // deallocation function’s name is looked up in the global
976 // scope. Otherwise, if the allocated type is a class type T or an
977 // array thereof, the deallocation function’s name is looked up in
978 // the scope of T. If this lookup fails to find the name, or if
979 // the allocated type is not a class type or array thereof, the
980 // deallocation function’s name is looked up in the global scope.
981 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
982 if (AllocType->isRecordType() && !UseGlobal) {
983 CXXRecordDecl *RD
984 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
985 LookupQualifiedName(FoundDelete, RD);
986 }
John McCallfb6f5262010-03-18 08:19:33 +0000987 if (FoundDelete.isAmbiguous())
988 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000989
990 if (FoundDelete.empty()) {
991 DeclareGlobalNewDelete();
992 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
993 }
994
995 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000996
997 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
998
John McCallfb6f5262010-03-18 08:19:33 +0000999 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001000 // C++ [expr.new]p20:
1001 // A declaration of a placement deallocation function matches the
1002 // declaration of a placement allocation function if it has the
1003 // same number of parameters and, after parameter transformations
1004 // (8.3.5), all parameter types except the first are
1005 // identical. [...]
1006 //
1007 // To perform this comparison, we compute the function type that
1008 // the deallocation function should have, and use that type both
1009 // for template argument deduction and for comparison purposes.
1010 QualType ExpectedFunctionType;
1011 {
1012 const FunctionProtoType *Proto
1013 = OperatorNew->getType()->getAs<FunctionProtoType>();
1014 llvm::SmallVector<QualType, 4> ArgTypes;
1015 ArgTypes.push_back(Context.VoidPtrTy);
1016 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1017 ArgTypes.push_back(Proto->getArgType(I));
1018
1019 ExpectedFunctionType
1020 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1021 ArgTypes.size(),
1022 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001023 0, false, false, 0, 0,
1024 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001025 }
1026
1027 for (LookupResult::iterator D = FoundDelete.begin(),
1028 DEnd = FoundDelete.end();
1029 D != DEnd; ++D) {
1030 FunctionDecl *Fn = 0;
1031 if (FunctionTemplateDecl *FnTmpl
1032 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1033 // Perform template argument deduction to try to match the
1034 // expected function type.
1035 TemplateDeductionInfo Info(Context, StartLoc);
1036 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1037 continue;
1038 } else
1039 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1040
1041 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001042 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001043 }
1044 } else {
1045 // C++ [expr.new]p20:
1046 // [...] Any non-placement deallocation function matches a
1047 // non-placement allocation function. [...]
1048 for (LookupResult::iterator D = FoundDelete.begin(),
1049 DEnd = FoundDelete.end();
1050 D != DEnd; ++D) {
1051 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1052 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001053 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001054 }
1055 }
1056
1057 // C++ [expr.new]p20:
1058 // [...] If the lookup finds a single matching deallocation
1059 // function, that function will be called; otherwise, no
1060 // deallocation function will be called.
1061 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001062 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001063
1064 // C++0x [expr.new]p20:
1065 // If the lookup finds the two-parameter form of a usual
1066 // deallocation function (3.7.4.2) and that function, considered
1067 // as a placement deallocation function, would have been
1068 // selected as a match for the allocation function, the program
1069 // is ill-formed.
1070 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1071 isNonPlacementDeallocationFunction(OperatorDelete)) {
1072 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1073 << SourceRange(PlaceArgs[0]->getLocStart(),
1074 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1075 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1076 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001077 } else {
1078 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001079 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001080 }
1081 }
1082
Sebastian Redlfaf68082008-12-03 20:26:15 +00001083 return false;
1084}
1085
Sebastian Redl33a31012008-12-04 22:20:51 +00001086/// FindAllocationOverload - Find an fitting overload for the allocation
1087/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001088bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1089 DeclarationName Name, Expr** Args,
1090 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001091 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001092 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1093 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001094 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001095 if (AllowMissing)
1096 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001097 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001098 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001099 }
1100
John McCallfb6f5262010-03-18 08:19:33 +00001101 if (R.isAmbiguous())
1102 return true;
1103
1104 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001105
John McCallbc077cf2010-02-08 23:07:23 +00001106 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001107 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1108 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001109 // Even member operator new/delete are implicitly treated as
1110 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001111 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001112
John McCalla0296f72010-03-19 07:35:19 +00001113 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1114 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001115 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1116 Candidates,
1117 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001118 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001119 }
1120
John McCalla0296f72010-03-19 07:35:19 +00001121 FunctionDecl *Fn = cast<FunctionDecl>(D);
1122 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001123 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001124 }
1125
1126 // Do the resolution.
1127 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001128 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001129 case OR_Success: {
1130 // Got one!
1131 FunctionDecl *FnDecl = Best->Function;
1132 // The first argument is size_t, and the first parameter must be size_t,
1133 // too. This is checked on declaration and can be assumed. (It can't be
1134 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001135 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001136 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1137 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-03-26 20:35:59 +00001138 OwningExprResult Result
1139 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1140 FnDecl->getParamDecl(i)),
1141 SourceLocation(),
1142 Owned(Args[i]->Retain()));
1143 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001144 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001145
1146 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001147 }
1148 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001149 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001150 return false;
1151 }
1152
1153 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001154 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001155 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001156 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001157 return true;
1158
1159 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001160 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001161 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001162 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001163 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001164
1165 case OR_Deleted:
1166 Diag(StartLoc, diag::err_ovl_deleted_call)
1167 << Best->Function->isDeleted()
1168 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001169 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001170 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001171 }
1172 assert(false && "Unreachable, bad result from BestViableFunction");
1173 return true;
1174}
1175
1176
Sebastian Redlfaf68082008-12-03 20:26:15 +00001177/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1178/// delete. These are:
1179/// @code
1180/// void* operator new(std::size_t) throw(std::bad_alloc);
1181/// void* operator new[](std::size_t) throw(std::bad_alloc);
1182/// void operator delete(void *) throw();
1183/// void operator delete[](void *) throw();
1184/// @endcode
1185/// Note that the placement and nothrow forms of new are *not* implicitly
1186/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001187void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001188 if (GlobalNewDeleteDeclared)
1189 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001190
1191 // C++ [basic.std.dynamic]p2:
1192 // [...] The following allocation and deallocation functions (18.4) are
1193 // implicitly declared in global scope in each translation unit of a
1194 // program
1195 //
1196 // void* operator new(std::size_t) throw(std::bad_alloc);
1197 // void* operator new[](std::size_t) throw(std::bad_alloc);
1198 // void operator delete(void*) throw();
1199 // void operator delete[](void*) throw();
1200 //
1201 // These implicit declarations introduce only the function names operator
1202 // new, operator new[], operator delete, operator delete[].
1203 //
1204 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1205 // "std" or "bad_alloc" as necessary to form the exception specification.
1206 // However, we do not make these implicit declarations visible to name
1207 // lookup.
Douglas Gregor87f54062009-09-15 22:30:29 +00001208 if (!StdBadAlloc) {
1209 // The "std::bad_alloc" class has not yet been declared, so build it
1210 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001211 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregorcdf87022010-06-29 17:53:46 +00001212 getStdNamespace(),
Douglas Gregor87f54062009-09-15 22:30:29 +00001213 SourceLocation(),
1214 &PP.getIdentifierTable().get("bad_alloc"),
1215 SourceLocation(), 0);
1216 StdBadAlloc->setImplicit(true);
1217 }
1218
Sebastian Redlfaf68082008-12-03 20:26:15 +00001219 GlobalNewDeleteDeclared = true;
1220
1221 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1222 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001223 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001224
Sebastian Redlfaf68082008-12-03 20:26:15 +00001225 DeclareGlobalAllocationFunction(
1226 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001227 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001228 DeclareGlobalAllocationFunction(
1229 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001230 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001231 DeclareGlobalAllocationFunction(
1232 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1233 Context.VoidTy, VoidPtr);
1234 DeclareGlobalAllocationFunction(
1235 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1236 Context.VoidTy, VoidPtr);
1237}
1238
1239/// DeclareGlobalAllocationFunction - Declares a single implicit global
1240/// allocation function if it doesn't already exist.
1241void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001242 QualType Return, QualType Argument,
1243 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001244 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1245
1246 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001247 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001248 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001249 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001250 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001251 // Only look at non-template functions, as it is the predefined,
1252 // non-templated allocation function we are trying to declare here.
1253 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1254 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001255 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001256 Func->getParamDecl(0)->getType().getUnqualifiedType());
1257 // FIXME: Do we need to check for default arguments here?
1258 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1259 return;
1260 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001261 }
1262 }
1263
Douglas Gregor87f54062009-09-15 22:30:29 +00001264 QualType BadAllocType;
1265 bool HasBadAllocExceptionSpec
1266 = (Name.getCXXOverloadedOperator() == OO_New ||
1267 Name.getCXXOverloadedOperator() == OO_Array_New);
1268 if (HasBadAllocExceptionSpec) {
1269 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1270 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1271 }
1272
1273 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1274 true, false,
1275 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001276 &BadAllocType,
1277 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001278 FunctionDecl *Alloc =
1279 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001280 FnType, /*TInfo=*/0, FunctionDecl::None,
1281 FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001282 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001283
1284 if (AddMallocAttr)
1285 Alloc->addAttr(::new (Context) MallocAttr());
1286
Sebastian Redlfaf68082008-12-03 20:26:15 +00001287 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001288 0, Argument, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001289 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001290 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001291 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001292
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001293 // FIXME: Also add this declaration to the IdentifierResolver, but
1294 // make sure it is at the end of the chain to coincide with the
1295 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001296 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001297}
1298
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001299bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1300 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001301 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001302 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001303 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001304 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001305
John McCall27b18f82009-11-17 02:14:36 +00001306 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001307 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001308
Chandler Carruthb6f99172010-06-28 00:30:51 +00001309 Found.suppressDiagnostics();
1310
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001311 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1312 F != FEnd; ++F) {
1313 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1314 if (Delete->isUsualDeallocationFunction()) {
1315 Operator = Delete;
Chandler Carruthb6f99172010-06-28 00:30:51 +00001316 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1317 F.getPair());
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001318 return false;
1319 }
1320 }
1321
1322 // We did find operator delete/operator delete[] declarations, but
1323 // none of them were suitable.
1324 if (!Found.empty()) {
1325 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1326 << Name << RD;
1327
1328 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1329 F != FEnd; ++F) {
Douglas Gregor861eb802010-04-25 20:55:08 +00001330 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001331 << Name;
1332 }
1333
1334 return true;
1335 }
1336
1337 // Look for a global declaration.
1338 DeclareGlobalNewDelete();
1339 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1340
1341 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1342 Expr* DeallocArgs[1];
1343 DeallocArgs[0] = &Null;
1344 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1345 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1346 Operator))
1347 return true;
1348
1349 assert(Operator && "Did not find a deallocation function!");
1350 return false;
1351}
1352
Sebastian Redlbd150f42008-11-21 19:14:01 +00001353/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1354/// @code ::delete ptr; @endcode
1355/// or
1356/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001357Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001358Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001359 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001360 // C++ [expr.delete]p1:
1361 // The operand shall have a pointer type, or a class type having a single
1362 // conversion function to a pointer type. The result has type void.
1363 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001364 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1365
Anders Carlssona471db02009-08-16 20:29:29 +00001366 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001367
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001368 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001369 if (!Ex->isTypeDependent()) {
1370 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001371
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001372 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCallda4458e2010-03-31 01:36:47 +00001373 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1374
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001375 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001376 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001377 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001378 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001379 NamedDecl *D = I.getDecl();
1380 if (isa<UsingShadowDecl>(D))
1381 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1382
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001383 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001384 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001385 continue;
1386
John McCallda4458e2010-03-31 01:36:47 +00001387 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001388
1389 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1390 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1391 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001392 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001393 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001394 if (ObjectPtrConversions.size() == 1) {
1395 // We have a single conversion to a pointer-to-object type. Perform
1396 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001397 // TODO: don't redo the conversion calculation.
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001398 Operand.release();
John McCallda4458e2010-03-31 01:36:47 +00001399 if (!PerformImplicitConversion(Ex,
1400 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001401 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001402 Operand = Owned(Ex);
1403 Type = Ex->getType();
1404 }
1405 }
1406 else if (ObjectPtrConversions.size() > 1) {
1407 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1408 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001409 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1410 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001411 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001412 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001413 }
1414
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001415 if (!Type->isPointerType())
1416 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1417 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001418
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001419 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001420 if (Pointee->isVoidType() && !isSFINAEContext()) {
1421 // The C++ standard bans deleting a pointer to a non-object type, which
1422 // effectively bans deletion of "void*". However, most compilers support
1423 // this, so we treat it as a warning unless we're in a SFINAE context.
1424 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1425 << Type << Ex->getSourceRange();
1426 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001427 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1428 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001429 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001430 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001431 PDiag(diag::warn_delete_incomplete)
1432 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001433 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001434
Douglas Gregor98496dc2009-09-29 21:38:53 +00001435 // C++ [expr.delete]p2:
1436 // [Note: a pointer to a const type can be the operand of a
1437 // delete-expression; it is not necessary to cast away the constness
1438 // (5.2.11) of the pointer expression before it is used as the operand
1439 // of the delete-expression. ]
1440 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1441 CastExpr::CK_NoOp);
1442
1443 // Update the operand.
1444 Operand.take();
1445 Operand = ExprArg(*this, Ex);
1446
Anders Carlssona471db02009-08-16 20:29:29 +00001447 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1448 ArrayForm ? OO_Array_Delete : OO_Delete);
1449
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001450 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1451 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1452
1453 if (!UseGlobal &&
1454 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001455 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001456
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001457 if (!RD->hasTrivialDestructor())
Douglas Gregore71edda2010-07-01 22:47:18 +00001458 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump11289f42009-09-09 15:08:12 +00001459 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001460 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001461 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001462
Anders Carlssona471db02009-08-16 20:29:29 +00001463 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001464 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001465 DeclareGlobalNewDelete();
1466 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001467 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001468 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001469 OperatorDelete))
1470 return ExprError();
1471 }
Mike Stump11289f42009-09-09 15:08:12 +00001472
John McCall0f55a032010-04-20 02:18:25 +00001473 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1474
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001475 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001476 }
1477
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001478 Operand.release();
1479 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001480 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001481}
1482
Douglas Gregor633caca2009-11-23 23:44:04 +00001483/// \brief Check the use of the given variable as a C++ condition in an if,
1484/// while, do-while, or switch statement.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001485Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1486 SourceLocation StmtLoc,
1487 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001488 QualType T = ConditionVar->getType();
1489
1490 // C++ [stmt.select]p2:
1491 // The declarator shall not specify a function or an array.
1492 if (T->isFunctionType())
1493 return ExprError(Diag(ConditionVar->getLocation(),
1494 diag::err_invalid_use_of_function_type)
1495 << ConditionVar->getSourceRange());
1496 else if (T->isArrayType())
1497 return ExprError(Diag(ConditionVar->getLocation(),
1498 diag::err_invalid_use_of_array_type)
1499 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001500
Douglas Gregore60e41a2010-05-06 17:25:47 +00001501 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1502 ConditionVar->getLocation(),
1503 ConditionVar->getType().getNonReferenceType());
1504 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1505 Condition->Destroy(Context);
1506 return ExprError();
1507 }
1508
1509 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001510}
1511
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001512/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1513bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1514 // C++ 6.4p4:
1515 // The value of a condition that is an initialized declaration in a statement
1516 // other than a switch statement is the value of the declared variable
1517 // implicitly converted to type bool. If that conversion is ill-formed, the
1518 // program is ill-formed.
1519 // The value of a condition that is an expression is the value of the
1520 // expression, implicitly converted to bool.
1521 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001522 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001523}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001524
1525/// Helper function to determine whether this is the (deprecated) C++
1526/// conversion from a string literal to a pointer to non-const char or
1527/// non-const wchar_t (for narrow and wide string literals,
1528/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001529bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001530Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1531 // Look inside the implicit cast, if it exists.
1532 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1533 From = Cast->getSubExpr();
1534
1535 // A string literal (2.13.4) that is not a wide string literal can
1536 // be converted to an rvalue of type "pointer to char"; a wide
1537 // string literal can be converted to an rvalue of type "pointer
1538 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001539 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001540 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001541 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001542 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001543 // This conversion is considered only when there is an
1544 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001545 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001546 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1547 (!StrLit->isWide() &&
1548 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1549 ToPointeeType->getKind() == BuiltinType::Char_S))))
1550 return true;
1551 }
1552
1553 return false;
1554}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001555
Douglas Gregora4253922010-04-16 22:17:36 +00001556static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1557 SourceLocation CastLoc,
1558 QualType Ty,
1559 CastExpr::CastKind Kind,
1560 CXXMethodDecl *Method,
1561 Sema::ExprArg Arg) {
1562 Expr *From = Arg.takeAs<Expr>();
1563
1564 switch (Kind) {
1565 default: assert(0 && "Unhandled cast kind!");
1566 case CastExpr::CK_ConstructorConversion: {
1567 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1568
1569 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1570 Sema::MultiExprArg(S, (void **)&From, 1),
1571 CastLoc, ConstructorArgs))
1572 return S.ExprError();
1573
1574 Sema::OwningExprResult Result =
1575 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1576 move_arg(ConstructorArgs));
1577 if (Result.isInvalid())
1578 return S.ExprError();
1579
1580 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1581 }
1582
1583 case CastExpr::CK_UserDefinedConversion: {
1584 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1585
1586 // Create an implicit call expr that calls it.
1587 // FIXME: pass the FoundDecl for the user-defined conversion here
1588 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1589 return S.MaybeBindToTemporary(CE);
1590 }
1591 }
1592}
1593
Douglas Gregor5fb53972009-01-14 15:45:31 +00001594/// PerformImplicitConversion - Perform an implicit conversion of the
1595/// expression From to the type ToType using the pre-computed implicit
1596/// conversion sequence ICS. Returns true if there was an error, false
1597/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001598/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001599/// used in the error message.
1600bool
1601Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1602 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001603 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001604 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001605 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001606 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001607 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001608 return true;
1609 break;
1610
Anders Carlsson110b07b2009-09-15 06:28:28 +00001611 case ImplicitConversionSequence::UserDefinedConversion: {
1612
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001613 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1614 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001615 QualType BeforeToType;
1616 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001617 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001618
1619 // If the user-defined conversion is specified by a conversion function,
1620 // the initial standard conversion sequence converts the source type to
1621 // the implicit object parameter of the conversion function.
1622 BeforeToType = Context.getTagDeclType(Conv->getParent());
1623 } else if (const CXXConstructorDecl *Ctor =
1624 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001625 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001626 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001627 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001628 // If the user-defined conversion is specified by a constructor, the
1629 // initial standard conversion sequence converts the source type to the
1630 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001631 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1632 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001633 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001634 else
1635 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001636 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001637 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001638 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001639 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001640 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001641 return true;
1642 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001643
Anders Carlssone9766d52009-09-09 21:33:21 +00001644 OwningExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001645 = BuildCXXCastArgument(*this,
1646 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001647 ToType.getNonReferenceType(),
1648 CastKind, cast<CXXMethodDecl>(FD),
1649 Owned(From));
1650
1651 if (CastArg.isInvalid())
1652 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001653
1654 From = CastArg.takeAs<Expr>();
1655
Eli Friedmane96f1d32009-11-27 04:41:50 +00001656 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001657 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001658 }
John McCall0d1da222010-01-12 00:44:57 +00001659
1660 case ImplicitConversionSequence::AmbiguousConversion:
1661 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1662 PDiag(diag::err_typecheck_ambiguous_condition)
1663 << From->getSourceRange());
1664 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001665
Douglas Gregor39c16d42008-10-24 04:54:22 +00001666 case ImplicitConversionSequence::EllipsisConversion:
1667 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001669
1670 case ImplicitConversionSequence::BadConversion:
1671 return true;
1672 }
1673
1674 // Everything went well.
1675 return false;
1676}
1677
1678/// PerformImplicitConversion - Perform an implicit conversion of the
1679/// expression From to the type ToType by following the standard
1680/// conversion sequence SCS. Returns true if there was an error, false
1681/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001682/// expression. Flavor is the context in which we're performing this
1683/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001684bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001685Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001686 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001687 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001688 // Overall FIXME: we are recomputing too many types here and doing far too
1689 // much extra work. What this means is that we need to keep track of more
1690 // information that is computed when we try the implicit conversion initially,
1691 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001692 QualType FromType = From->getType();
1693
Douglas Gregor2fe98832008-11-03 19:09:14 +00001694 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001695 // FIXME: When can ToType be a reference type?
1696 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001697 if (SCS.Second == ICK_Derived_To_Base) {
1698 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1699 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1700 MultiExprArg(*this, (void **)&From, 1),
1701 /*FIXME:ConstructLoc*/SourceLocation(),
1702 ConstructorArgs))
1703 return true;
1704 OwningExprResult FromResult =
1705 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1706 ToType, SCS.CopyConstructor,
1707 move_arg(ConstructorArgs));
1708 if (FromResult.isInvalid())
1709 return true;
1710 From = FromResult.takeAs<Expr>();
1711 return false;
1712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713 OwningExprResult FromResult =
1714 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1715 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001716 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001717
Anders Carlsson6eb55572009-08-25 05:12:04 +00001718 if (FromResult.isInvalid())
1719 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001720
Anders Carlsson6eb55572009-08-25 05:12:04 +00001721 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001722 return false;
1723 }
1724
Douglas Gregor980fb162010-04-29 18:24:40 +00001725 // Resolve overloaded function references.
1726 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1727 DeclAccessPair Found;
1728 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1729 true, Found);
1730 if (!Fn)
1731 return true;
1732
1733 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1734 return true;
1735
1736 From = FixOverloadedFunctionReference(From, Found, Fn);
1737 FromType = From->getType();
1738 }
1739
Douglas Gregor39c16d42008-10-24 04:54:22 +00001740 // Perform the first implicit conversion.
1741 switch (SCS.First) {
1742 case ICK_Identity:
1743 case ICK_Lvalue_To_Rvalue:
1744 // Nothing to do.
1745 break;
1746
1747 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001748 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001749 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001750 break;
1751
1752 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001753 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001754 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001755 break;
1756
1757 default:
1758 assert(false && "Improper first standard conversion");
1759 break;
1760 }
1761
1762 // Perform the second implicit conversion
1763 switch (SCS.Second) {
1764 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001765 // If both sides are functions (or pointers/references to them), there could
1766 // be incompatible exception declarations.
1767 if (CheckExceptionSpecCompatibility(From, ToType))
1768 return true;
1769 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001770 break;
1771
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001772 case ICK_NoReturn_Adjustment:
1773 // If both sides are functions (or pointers/references to them), there could
1774 // be incompatible exception declarations.
1775 if (CheckExceptionSpecCompatibility(From, ToType))
1776 return true;
1777
1778 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1779 CastExpr::CK_NoOp);
1780 break;
1781
Douglas Gregor39c16d42008-10-24 04:54:22 +00001782 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001783 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001784 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1785 break;
1786
1787 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001788 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001789 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1790 break;
1791
1792 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001793 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001794 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1795 break;
1796
Douglas Gregor39c16d42008-10-24 04:54:22 +00001797 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00001798 if (ToType->isRealFloatingType())
Eli Friedman06ed2a52009-10-20 08:27:19 +00001799 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1800 else
1801 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1802 break;
1803
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001804 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001805 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001806 break;
1807
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001808 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001809 if (SCS.IncompatibleObjC) {
1810 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001811 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001812 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001813 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001814 << From->getSourceRange();
1815 }
1816
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001817
1818 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssona70cff62010-04-24 19:06:50 +00001819 CXXBaseSpecifierArray BasePath;
1820 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001821 return true;
Anders Carlssona70cff62010-04-24 19:06:50 +00001822 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001823 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001824 }
1825
1826 case ICK_Pointer_Member: {
1827 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001828 CXXBaseSpecifierArray BasePath;
1829 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1830 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001831 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001832 if (CheckExceptionSpecCompatibility(From, ToType))
1833 return true;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001834 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001835 break;
1836 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001837 case ICK_Boolean_Conversion: {
1838 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1839 if (FromType->isMemberPointerType())
1840 Kind = CastExpr::CK_MemberPointerToBoolean;
1841
1842 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001843 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001844 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001845
Douglas Gregor88d292c2010-05-13 16:44:06 +00001846 case ICK_Derived_To_Base: {
1847 CXXBaseSpecifierArray BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001848 if (CheckDerivedToBaseConversion(From->getType(),
1849 ToType.getNonReferenceType(),
1850 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001851 From->getSourceRange(),
1852 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001853 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001854 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001855
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001856 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001857 CastExpr::CK_DerivedToBase,
1858 /*isLvalue=*/(From->getType()->isRecordType() &&
1859 From->isLvalue(Context) == Expr::LV_Valid),
1860 BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001861 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001862 }
1863
Douglas Gregor46188682010-05-18 22:42:18 +00001864 case ICK_Vector_Conversion:
1865 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1866 break;
1867
1868 case ICK_Vector_Splat:
1869 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1870 break;
1871
1872 case ICK_Complex_Real:
1873 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1874 break;
1875
1876 case ICK_Lvalue_To_Rvalue:
1877 case ICK_Array_To_Pointer:
1878 case ICK_Function_To_Pointer:
1879 case ICK_Qualification:
1880 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001881 assert(false && "Improper second standard conversion");
1882 break;
1883 }
1884
1885 switch (SCS.Third) {
1886 case ICK_Identity:
1887 // Nothing to do.
1888 break;
1889
1890 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001891 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1892 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001893 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00001894 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregore489a7d2010-02-28 18:30:25 +00001895
1896 if (SCS.DeprecatedStringLiteralToCharPtr)
1897 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1898 << ToType.getNonReferenceType();
1899
Douglas Gregor39c16d42008-10-24 04:54:22 +00001900 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001901
Douglas Gregor39c16d42008-10-24 04:54:22 +00001902 default:
Douglas Gregor46188682010-05-18 22:42:18 +00001903 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00001904 break;
1905 }
1906
1907 return false;
1908}
1909
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001910Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1911 SourceLocation KWLoc,
1912 SourceLocation LParen,
1913 TypeTy *Ty,
1914 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001915 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001916
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001917 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1918 // all traits except __is_class, __is_enum and __is_union require a the type
1919 // to be complete.
1920 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001921 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001922 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001923 return ExprError();
1924 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001925
1926 // There is no point in eagerly computing the value. The traits are designed
1927 // to be used from type trait templates, so Ty will be a template parameter
1928 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001929 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1930 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001931}
Sebastian Redl5822f082009-02-07 20:10:22 +00001932
1933QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001934 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001935 const char *OpSpelling = isIndirect ? "->*" : ".*";
1936 // C++ 5.5p2
1937 // The binary operator .* [p3: ->*] binds its second operand, which shall
1938 // be of type "pointer to member of T" (where T is a completely-defined
1939 // class type) [...]
1940 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001941 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001942 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001943 Diag(Loc, diag::err_bad_memptr_rhs)
1944 << OpSpelling << RType << rex->getSourceRange();
1945 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001946 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001947
Sebastian Redl5822f082009-02-07 20:10:22 +00001948 QualType Class(MemPtr->getClass(), 0);
1949
Sebastian Redlc72350e2010-04-10 10:14:54 +00001950 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1951 return QualType();
1952
Sebastian Redl5822f082009-02-07 20:10:22 +00001953 // C++ 5.5p2
1954 // [...] to its first operand, which shall be of class T or of a class of
1955 // which T is an unambiguous and accessible base class. [p3: a pointer to
1956 // such a class]
1957 QualType LType = lex->getType();
1958 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001959 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001960 LType = Ptr->getPointeeType().getNonReferenceType();
1961 else {
1962 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001963 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001964 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001965 return QualType();
1966 }
1967 }
1968
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001969 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00001970 // If we want to check the hierarchy, we need a complete type.
1971 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1972 << OpSpelling << (int)isIndirect)) {
1973 return QualType();
1974 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001975 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001976 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001977 // FIXME: Would it be useful to print full ambiguity paths, or is that
1978 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001979 if (!IsDerivedFrom(LType, Class, Paths) ||
1980 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1981 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001982 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001983 return QualType();
1984 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001985 // Cast LHS to type of use.
1986 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1987 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlssona70cff62010-04-24 19:06:50 +00001988
1989 CXXBaseSpecifierArray BasePath;
1990 BuildBasePathArray(Paths, BasePath);
1991 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1992 BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00001993 }
1994
Douglas Gregore1823702010-07-07 23:37:33 +00001995 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00001996 // Diagnose use of pointer-to-member type which when used as
1997 // the functional cast in a pointer-to-member expression.
1998 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1999 return QualType();
2000 }
Sebastian Redl5822f082009-02-07 20:10:22 +00002001 // C++ 5.5p2
2002 // The result is an object or a function of the type specified by the
2003 // second operand.
2004 // The cv qualifiers are the union of those in the pointer and the left side,
2005 // in accordance with 5.5p5 and 5.2.5.
2006 // FIXME: This returns a dereferenced member function pointer as a normal
2007 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00002008 // calling them. There's also a GCC extension to get a function pointer to the
2009 // thing, which is another complication, because this type - unlike the type
2010 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00002011 // argument.
2012 // We probably need a "MemberFunctionClosureType" or something like that.
2013 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002014 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00002015 return Result;
2016}
Sebastian Redl1a99f442009-04-16 17:51:27 +00002017
Sebastian Redl1a99f442009-04-16 17:51:27 +00002018/// \brief Try to convert a type to another according to C++0x 5.16p3.
2019///
2020/// This is part of the parameter validation for the ? operator. If either
2021/// value operand is a class type, the two operands are attempted to be
2022/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002023/// It returns true if the program is ill-formed and has already been diagnosed
2024/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002025static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2026 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002027 bool &HaveConversion,
2028 QualType &ToType) {
2029 HaveConversion = false;
2030 ToType = To->getType();
2031
2032 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2033 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002034 // C++0x 5.16p3
2035 // The process for determining whether an operand expression E1 of type T1
2036 // can be converted to match an operand expression E2 of type T2 is defined
2037 // as follows:
2038 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00002039 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2040 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002041 // E1 can be converted to match E2 if E1 can be implicitly converted to
2042 // type "lvalue reference to T2", subject to the constraint that in the
2043 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002044 QualType T = Self.Context.getLValueReferenceType(ToType);
2045 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2046
2047 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2048 if (InitSeq.isDirectReferenceBinding()) {
2049 ToType = T;
2050 HaveConversion = true;
2051 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002052 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002053
2054 if (InitSeq.isAmbiguous())
2055 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002056 }
John McCall65eb8792010-02-25 01:37:24 +00002057
Sebastian Redl1a99f442009-04-16 17:51:27 +00002058 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2059 // -- if E1 and E2 have class type, and the underlying class types are
2060 // the same or one is a base class of the other:
2061 QualType FTy = From->getType();
2062 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002063 const RecordType *FRec = FTy->getAs<RecordType>();
2064 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002065 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2066 Self.IsDerivedFrom(FTy, TTy);
2067 if (FRec && TRec &&
2068 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002069 // E1 can be converted to match E2 if the class of T2 is the
2070 // same type as, or a base class of, the class of T1, and
2071 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002072 if (FRec == TRec || FDerivedFromT) {
2073 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002074 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2075 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2076 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2077 HaveConversion = true;
2078 return false;
2079 }
2080
2081 if (InitSeq.isAmbiguous())
2082 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2083 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002084 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002085
2086 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002087 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002088
2089 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2090 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002091 // if E2 were converted to an rvalue (or the type it has, if E2 is
2092 // an rvalue).
2093 //
2094 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2095 // to the array-to-pointer or function-to-pointer conversions.
2096 if (!TTy->getAs<TagType>())
2097 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002098
2099 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2100 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2101 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2102 ToType = TTy;
2103 if (InitSeq.isAmbiguous())
2104 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2105
Sebastian Redl1a99f442009-04-16 17:51:27 +00002106 return false;
2107}
2108
2109/// \brief Try to find a common type for two according to C++0x 5.16p5.
2110///
2111/// This is part of the parameter validation for the ? operator. If either
2112/// value operand is a class type, overload resolution is used to find a
2113/// conversion to a common type.
2114static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2115 SourceLocation Loc) {
2116 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002117 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002118 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002119
2120 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002121 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002122 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002123 // We found a match. Perform the conversions on the arguments and move on.
2124 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002125 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002126 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002127 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002128 break;
2129 return false;
2130
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002131 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002132 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2133 << LHS->getType() << RHS->getType()
2134 << LHS->getSourceRange() << RHS->getSourceRange();
2135 return true;
2136
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002137 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002138 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2139 << LHS->getType() << RHS->getType()
2140 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002141 // FIXME: Print the possible common types by printing the return types of
2142 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002143 break;
2144
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002145 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002146 assert(false && "Conditional operator has only built-in overloads");
2147 break;
2148 }
2149 return true;
2150}
2151
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002152/// \brief Perform an "extended" implicit conversion as returned by
2153/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002154static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2155 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2156 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2157 SourceLocation());
2158 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2159 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2160 Sema::MultiExprArg(Self, (void **)&E, 1));
2161 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002162 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002163
2164 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002165 return false;
2166}
2167
Sebastian Redl1a99f442009-04-16 17:51:27 +00002168/// \brief Check the operands of ?: under C++ semantics.
2169///
2170/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2171/// extension. In this case, LHS == Cond. (But they're not aliases.)
2172QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2173 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002174 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2175 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002176
2177 // C++0x 5.16p1
2178 // The first expression is contextually converted to bool.
2179 if (!Cond->isTypeDependent()) {
2180 if (CheckCXXBooleanCondition(Cond))
2181 return QualType();
2182 }
2183
2184 // Either of the arguments dependent?
2185 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2186 return Context.DependentTy;
2187
2188 // C++0x 5.16p2
2189 // If either the second or the third operand has type (cv) void, ...
2190 QualType LTy = LHS->getType();
2191 QualType RTy = RHS->getType();
2192 bool LVoid = LTy->isVoidType();
2193 bool RVoid = RTy->isVoidType();
2194 if (LVoid || RVoid) {
2195 // ... then the [l2r] conversions are performed on the second and third
2196 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002197 DefaultFunctionArrayLvalueConversion(LHS);
2198 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002199 LTy = LHS->getType();
2200 RTy = RHS->getType();
2201
2202 // ... and one of the following shall hold:
2203 // -- The second or the third operand (but not both) is a throw-
2204 // expression; the result is of the type of the other and is an rvalue.
2205 bool LThrow = isa<CXXThrowExpr>(LHS);
2206 bool RThrow = isa<CXXThrowExpr>(RHS);
2207 if (LThrow && !RThrow)
2208 return RTy;
2209 if (RThrow && !LThrow)
2210 return LTy;
2211
2212 // -- Both the second and third operands have type void; the result is of
2213 // type void and is an rvalue.
2214 if (LVoid && RVoid)
2215 return Context.VoidTy;
2216
2217 // Neither holds, error.
2218 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2219 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2220 << LHS->getSourceRange() << RHS->getSourceRange();
2221 return QualType();
2222 }
2223
2224 // Neither is void.
2225
2226 // C++0x 5.16p3
2227 // Otherwise, if the second and third operand have different types, and
2228 // either has (cv) class type, and attempt is made to convert each of those
2229 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002230 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002231 (LTy->isRecordType() || RTy->isRecordType())) {
2232 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2233 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002234 QualType L2RType, R2LType;
2235 bool HaveL2R, HaveR2L;
2236 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002237 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002238 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002239 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002240
Sebastian Redl1a99f442009-04-16 17:51:27 +00002241 // If both can be converted, [...] the program is ill-formed.
2242 if (HaveL2R && HaveR2L) {
2243 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2244 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2245 return QualType();
2246 }
2247
2248 // If exactly one conversion is possible, that conversion is applied to
2249 // the chosen operand and the converted operands are used in place of the
2250 // original operands for the remainder of this section.
2251 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002252 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002253 return QualType();
2254 LTy = LHS->getType();
2255 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002256 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002257 return QualType();
2258 RTy = RHS->getType();
2259 }
2260 }
2261
2262 // C++0x 5.16p4
2263 // If the second and third operands are lvalues and have the same type,
2264 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002265 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002266 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2267 RHS->isLvalue(Context) == Expr::LV_Valid)
2268 return LTy;
2269
2270 // C++0x 5.16p5
2271 // Otherwise, the result is an rvalue. If the second and third operands
2272 // do not have the same type, and either has (cv) class type, ...
2273 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2274 // ... overload resolution is used to determine the conversions (if any)
2275 // to be applied to the operands. If the overload resolution fails, the
2276 // program is ill-formed.
2277 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2278 return QualType();
2279 }
2280
2281 // C++0x 5.16p6
2282 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2283 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002284 DefaultFunctionArrayLvalueConversion(LHS);
2285 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002286 LTy = LHS->getType();
2287 RTy = RHS->getType();
2288
2289 // After those conversions, one of the following shall hold:
2290 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002291 // is of that type. If the operands have class type, the result
2292 // is a prvalue temporary of the result type, which is
2293 // copy-initialized from either the second operand or the third
2294 // operand depending on the value of the first operand.
2295 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2296 if (LTy->isRecordType()) {
2297 // The operands have class type. Make a temporary copy.
2298 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2299 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2300 SourceLocation(),
2301 Owned(LHS));
2302 if (LHSCopy.isInvalid())
2303 return QualType();
2304
2305 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2306 SourceLocation(),
2307 Owned(RHS));
2308 if (RHSCopy.isInvalid())
2309 return QualType();
2310
2311 LHS = LHSCopy.takeAs<Expr>();
2312 RHS = RHSCopy.takeAs<Expr>();
2313 }
2314
Sebastian Redl1a99f442009-04-16 17:51:27 +00002315 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002316 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002317
Douglas Gregor46188682010-05-18 22:42:18 +00002318 // Extension: conditional operator involving vector types.
2319 if (LTy->isVectorType() || RTy->isVectorType())
2320 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2321
Sebastian Redl1a99f442009-04-16 17:51:27 +00002322 // -- The second and third operands have arithmetic or enumeration type;
2323 // the usual arithmetic conversions are performed to bring them to a
2324 // common type, and the result is of that type.
2325 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2326 UsualArithmeticConversions(LHS, RHS);
2327 return LHS->getType();
2328 }
2329
2330 // -- The second and third operands have pointer type, or one has pointer
2331 // type and the other is a null pointer constant; pointer conversions
2332 // and qualification conversions are performed to bring them to their
2333 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002334 // -- The second and third operands have pointer to member type, or one has
2335 // pointer to member type and the other is a null pointer constant;
2336 // pointer to member conversions and qualification conversions are
2337 // performed to bring them to a common type, whose cv-qualification
2338 // shall match the cv-qualification of either the second or the third
2339 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002340 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002341 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002342 isSFINAEContext()? 0 : &NonStandardCompositeType);
2343 if (!Composite.isNull()) {
2344 if (NonStandardCompositeType)
2345 Diag(QuestionLoc,
2346 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2347 << LTy << RTy << Composite
2348 << LHS->getSourceRange() << RHS->getSourceRange();
2349
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002350 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002351 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002352
Douglas Gregor697a3912010-04-01 22:47:07 +00002353 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002354 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2355 if (!Composite.isNull())
2356 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002357
Sebastian Redl1a99f442009-04-16 17:51:27 +00002358 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2359 << LHS->getType() << RHS->getType()
2360 << LHS->getSourceRange() << RHS->getSourceRange();
2361 return QualType();
2362}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002363
2364/// \brief Find a merged pointer type and convert the two expressions to it.
2365///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002366/// This finds the composite pointer type (or member pointer type) for @p E1
2367/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2368/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002369/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002370///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002371/// \param Loc The location of the operator requiring these two expressions to
2372/// be converted to the composite pointer type.
2373///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002374/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2375/// a non-standard (but still sane) composite type to which both expressions
2376/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2377/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002378QualType Sema::FindCompositePointerType(SourceLocation Loc,
2379 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002380 bool *NonStandardCompositeType) {
2381 if (NonStandardCompositeType)
2382 *NonStandardCompositeType = false;
2383
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002384 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2385 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002386
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002387 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2388 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002389 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002390
2391 // C++0x 5.9p2
2392 // Pointer conversions and qualification conversions are performed on
2393 // pointer operands to bring them to their composite pointer type. If
2394 // one operand is a null pointer constant, the composite pointer type is
2395 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002396 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002397 if (T2->isMemberPointerType())
2398 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2399 else
2400 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002401 return T2;
2402 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002403 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002404 if (T1->isMemberPointerType())
2405 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2406 else
2407 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002408 return T1;
2409 }
Mike Stump11289f42009-09-09 15:08:12 +00002410
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002411 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002412 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2413 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002414 return QualType();
2415
2416 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2417 // the other has type "pointer to cv2 T" and the composite pointer type is
2418 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2419 // Otherwise, the composite pointer type is a pointer type similar to the
2420 // type of one of the operands, with a cv-qualification signature that is
2421 // the union of the cv-qualification signatures of the operand types.
2422 // In practice, the first part here is redundant; it's subsumed by the second.
2423 // What we do here is, we build the two possible composite types, and try the
2424 // conversions in both directions. If only one works, or if the two composite
2425 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002426 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002427 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2428 QualifierVector QualifierUnion;
2429 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2430 ContainingClassVector;
2431 ContainingClassVector MemberOfClass;
2432 QualType Composite1 = Context.getCanonicalType(T1),
2433 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002434 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002435 do {
2436 const PointerType *Ptr1, *Ptr2;
2437 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2438 (Ptr2 = Composite2->getAs<PointerType>())) {
2439 Composite1 = Ptr1->getPointeeType();
2440 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002441
2442 // If we're allowed to create a non-standard composite type, keep track
2443 // of where we need to fill in additional 'const' qualifiers.
2444 if (NonStandardCompositeType &&
2445 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2446 NeedConstBefore = QualifierUnion.size();
2447
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002448 QualifierUnion.push_back(
2449 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2450 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2451 continue;
2452 }
Mike Stump11289f42009-09-09 15:08:12 +00002453
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002454 const MemberPointerType *MemPtr1, *MemPtr2;
2455 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2456 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2457 Composite1 = MemPtr1->getPointeeType();
2458 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002459
2460 // If we're allowed to create a non-standard composite type, keep track
2461 // of where we need to fill in additional 'const' qualifiers.
2462 if (NonStandardCompositeType &&
2463 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2464 NeedConstBefore = QualifierUnion.size();
2465
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002466 QualifierUnion.push_back(
2467 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2468 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2469 MemPtr2->getClass()));
2470 continue;
2471 }
Mike Stump11289f42009-09-09 15:08:12 +00002472
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002473 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002474
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002475 // Cannot unwrap any more types.
2476 break;
2477 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002478
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002479 if (NeedConstBefore && NonStandardCompositeType) {
2480 // Extension: Add 'const' to qualifiers that come before the first qualifier
2481 // mismatch, so that our (non-standard!) composite type meets the
2482 // requirements of C++ [conv.qual]p4 bullet 3.
2483 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2484 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2485 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2486 *NonStandardCompositeType = true;
2487 }
2488 }
2489 }
2490
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002491 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002492 ContainingClassVector::reverse_iterator MOC
2493 = MemberOfClass.rbegin();
2494 for (QualifierVector::reverse_iterator
2495 I = QualifierUnion.rbegin(),
2496 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002497 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002498 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002499 if (MOC->first && MOC->second) {
2500 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002501 Composite1 = Context.getMemberPointerType(
2502 Context.getQualifiedType(Composite1, Quals),
2503 MOC->first);
2504 Composite2 = Context.getMemberPointerType(
2505 Context.getQualifiedType(Composite2, Quals),
2506 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002507 } else {
2508 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002509 Composite1
2510 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2511 Composite2
2512 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002513 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002514 }
2515
Douglas Gregor19175ff2010-04-16 23:20:25 +00002516 // Try to convert to the first composite pointer type.
2517 InitializedEntity Entity1
2518 = InitializedEntity::InitializeTemporary(Composite1);
2519 InitializationKind Kind
2520 = InitializationKind::CreateCopy(Loc, SourceLocation());
2521 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2522 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregor19175ff2010-04-16 23:20:25 +00002524 if (E1ToC1 && E2ToC1) {
2525 // Conversion to Composite1 is viable.
2526 if (!Context.hasSameType(Composite1, Composite2)) {
2527 // Composite2 is a different type from Composite1. Check whether
2528 // Composite2 is also viable.
2529 InitializedEntity Entity2
2530 = InitializedEntity::InitializeTemporary(Composite2);
2531 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2532 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2533 if (E1ToC2 && E2ToC2) {
2534 // Both Composite1 and Composite2 are viable and are different;
2535 // this is an ambiguity.
2536 return QualType();
2537 }
2538 }
2539
2540 // Convert E1 to Composite1
2541 OwningExprResult E1Result
2542 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2543 if (E1Result.isInvalid())
2544 return QualType();
2545 E1 = E1Result.takeAs<Expr>();
2546
2547 // Convert E2 to Composite1
2548 OwningExprResult E2Result
2549 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2550 if (E2Result.isInvalid())
2551 return QualType();
2552 E2 = E2Result.takeAs<Expr>();
2553
2554 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002555 }
2556
Douglas Gregor19175ff2010-04-16 23:20:25 +00002557 // Check whether Composite2 is viable.
2558 InitializedEntity Entity2
2559 = InitializedEntity::InitializeTemporary(Composite2);
2560 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2561 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2562 if (!E1ToC2 || !E2ToC2)
2563 return QualType();
2564
2565 // Convert E1 to Composite2
2566 OwningExprResult E1Result
2567 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2568 if (E1Result.isInvalid())
2569 return QualType();
2570 E1 = E1Result.takeAs<Expr>();
2571
2572 // Convert E2 to Composite2
2573 OwningExprResult E2Result
2574 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2575 if (E2Result.isInvalid())
2576 return QualType();
2577 E2 = E2Result.takeAs<Expr>();
2578
2579 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002580}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002581
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002582Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002583 if (!Context.getLangOptions().CPlusPlus)
2584 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregor363b1512009-12-24 18:51:59 +00002586 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2587
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002588 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002589 if (!RT)
2590 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002591
John McCall67da35c2010-02-04 22:26:26 +00002592 // If this is the result of a call expression, our source might
2593 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002594 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2595 QualType Ty = CE->getCallee()->getType();
2596 if (const PointerType *PT = Ty->getAs<PointerType>())
2597 Ty = PT->getPointeeType();
Fariborz Jahanianffcfecd2010-02-18 20:31:02 +00002598 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2599 Ty = BPT->getPointeeType();
2600
John McCall9dd450b2009-09-21 23:43:11 +00002601 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002602 if (FTy->getResultType()->isReferenceType())
2603 return Owned(E);
2604 }
Fariborz Jahanian1d446082010-06-16 18:56:04 +00002605 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2606 QualType Ty = ME->getType();
2607 if (const PointerType *PT = Ty->getAs<PointerType>())
2608 Ty = PT->getPointeeType();
2609 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2610 Ty = BPT->getPointeeType();
2611 if (Ty->isReferenceType())
2612 return Owned(E);
2613 }
2614
John McCall67da35c2010-02-04 22:26:26 +00002615
2616 // That should be enough to guarantee that this type is complete.
2617 // If it has a trivial destructor, we can avoid the extra copy.
2618 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2619 if (RD->hasTrivialDestructor())
2620 return Owned(E);
2621
Douglas Gregore71edda2010-07-01 22:47:18 +00002622 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002623 ExprTemporaries.push_back(Temp);
Douglas Gregore71edda2010-07-01 22:47:18 +00002624 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002625 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002626 CheckDestructorAccess(E->getExprLoc(), Destructor,
2627 PDiag(diag::err_access_dtor_temp)
2628 << E->getType());
2629 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002630 // FIXME: Add the temporary to the temporaries vector.
2631 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2632}
2633
Anders Carlsson6e997b22009-12-15 20:51:39 +00002634Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002635 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002636
John McCallcc7e5bf2010-05-06 08:58:33 +00002637 // Check any implicit conversions within the expression.
2638 CheckImplicitConversions(SubExpr);
2639
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002640 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2641 assert(ExprTemporaries.size() >= FirstTemporary);
2642 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002643 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002644
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002645 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002646 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002647 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002648 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2649 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002650
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002651 return E;
2652}
2653
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002654Sema::OwningExprResult
2655Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2656 if (SubExpr.isInvalid())
2657 return ExprError();
2658
2659 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2660}
2661
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002662FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2663 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2664 assert(ExprTemporaries.size() >= FirstTemporary);
2665
2666 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2667 CXXTemporary **Temporaries =
2668 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2669
2670 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2671
2672 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2673 ExprTemporaries.end());
2674
2675 return E;
2676}
2677
Mike Stump11289f42009-09-09 15:08:12 +00002678Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002679Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002680 tok::TokenKind OpKind, TypeTy *&ObjectType,
2681 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002682 // Since this might be a postfix expression, get rid of ParenListExprs.
2683 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002684
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002685 Expr *BaseExpr = (Expr*)Base.get();
2686 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002687
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002688 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002689 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002690 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002691 // If we have a pointer to a dependent type and are using the -> operator,
2692 // the object type is the type that the pointer points to. We might still
2693 // have enough information about that type to do something useful.
2694 if (OpKind == tok::arrow)
2695 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2696 BaseType = Ptr->getPointeeType();
2697
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002698 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002699 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002700 return move(Base);
2701 }
Mike Stump11289f42009-09-09 15:08:12 +00002702
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002703 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002704 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002705 // returned, with the original second operand.
2706 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002707 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002708 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002709 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002710 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002711
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002712 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002713 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002714 BaseExpr = (Expr*)Base.get();
2715 if (BaseExpr == NULL)
2716 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002717 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002718 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002719 BaseType = BaseExpr->getType();
2720 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002721 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002722 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002723 for (unsigned i = 0; i < Locations.size(); i++)
2724 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002725 return ExprError();
2726 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
Douglas Gregore4f764f2009-11-20 19:58:21 +00002729 if (BaseType->isPointerType())
2730 BaseType = BaseType->getPointeeType();
2731 }
Mike Stump11289f42009-09-09 15:08:12 +00002732
2733 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002734 // vector types or Objective-C interfaces. Just return early and let
2735 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002736 if (!BaseType->isRecordType()) {
2737 // C++ [basic.lookup.classref]p2:
2738 // [...] If the type of the object expression is of pointer to scalar
2739 // type, the unqualified-id is looked up in the context of the complete
2740 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002741 //
2742 // This also indicates that we should be parsing a
2743 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002744 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002745 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002746 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002747 }
Mike Stump11289f42009-09-09 15:08:12 +00002748
Douglas Gregor3fad6172009-11-17 05:17:33 +00002749 // The object type must be complete (or dependent).
2750 if (!BaseType->isDependentType() &&
2751 RequireCompleteType(OpLoc, BaseType,
2752 PDiag(diag::err_incomplete_member_access)))
2753 return ExprError();
2754
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002755 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002756 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002757 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002758 // type C (or of pointer to a class type C), the unqualified-id is looked
2759 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002760 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002761 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002762}
2763
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002764Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2765 ExprArg MemExpr) {
2766 Expr *E = (Expr *) MemExpr.get();
2767 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2768 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2769 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregora771f462010-03-31 17:46:05 +00002770 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002771
2772 return ActOnCallExpr(/*Scope*/ 0,
2773 move(MemExpr),
2774 /*LPLoc*/ ExpectedLParenLoc,
2775 Sema::MultiExprArg(*this, 0, 0),
2776 /*CommaLocs*/ 0,
2777 /*RPLoc*/ ExpectedLParenLoc);
2778}
Douglas Gregore610ada2010-02-24 18:44:31 +00002779
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002780Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2781 SourceLocation OpLoc,
2782 tok::TokenKind OpKind,
2783 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002784 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002785 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002786 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002787 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002788 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002789 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002790
2791 // C++ [expr.pseudo]p2:
2792 // The left-hand side of the dot operator shall be of scalar type. The
2793 // left-hand side of the arrow operator shall be of pointer to scalar type.
2794 // This scalar type is the object type.
2795 Expr *BaseE = (Expr *)Base.get();
2796 QualType ObjectType = BaseE->getType();
2797 if (OpKind == tok::arrow) {
2798 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2799 ObjectType = Ptr->getPointeeType();
2800 } else if (!BaseE->isTypeDependent()) {
2801 // The user wrote "p->" when she probably meant "p."; fix it.
2802 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2803 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002804 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002805 if (isSFINAEContext())
2806 return ExprError();
2807
2808 OpKind = tok::period;
2809 }
2810 }
2811
2812 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2813 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2814 << ObjectType << BaseE->getSourceRange();
2815 return ExprError();
2816 }
2817
2818 // C++ [expr.pseudo]p2:
2819 // [...] The cv-unqualified versions of the object type and of the type
2820 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002821 if (DestructedTypeInfo) {
2822 QualType DestructedType = DestructedTypeInfo->getType();
2823 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002824 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002825 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2826 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2827 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2828 << ObjectType << DestructedType << BaseE->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002829 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002830
2831 // Recover by setting the destructed type to the object type.
2832 DestructedType = ObjectType;
2833 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2834 DestructedTypeStart);
2835 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2836 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002837 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002838
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002839 // C++ [expr.pseudo]p2:
2840 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2841 // form
2842 //
2843 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2844 //
2845 // shall designate the same scalar type.
2846 if (ScopeTypeInfo) {
2847 QualType ScopeType = ScopeTypeInfo->getType();
2848 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00002849 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002850
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002851 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002852 diag::err_pseudo_dtor_type_mismatch)
2853 << ObjectType << ScopeType << BaseE->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002854 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002855
2856 ScopeType = QualType();
2857 ScopeTypeInfo = 0;
2858 }
2859 }
2860
2861 OwningExprResult Result
2862 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2863 Base.takeAs<Expr>(),
2864 OpKind == tok::arrow,
2865 OpLoc,
2866 (NestedNameSpecifier *) SS.getScopeRep(),
2867 SS.getRange(),
2868 ScopeTypeInfo,
2869 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002870 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002871 Destructed));
2872
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002873 if (HasTrailingLParen)
2874 return move(Result);
2875
Douglas Gregor678f90d2010-02-25 01:56:36 +00002876 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002877}
2878
2879Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2880 SourceLocation OpLoc,
2881 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002882 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002883 UnqualifiedId &FirstTypeName,
2884 SourceLocation CCLoc,
2885 SourceLocation TildeLoc,
2886 UnqualifiedId &SecondTypeName,
2887 bool HasTrailingLParen) {
2888 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2889 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2890 "Invalid first type name in pseudo-destructor");
2891 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2892 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2893 "Invalid second type name in pseudo-destructor");
2894
2895 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002896
2897 // C++ [expr.pseudo]p2:
2898 // The left-hand side of the dot operator shall be of scalar type. The
2899 // left-hand side of the arrow operator shall be of pointer to scalar type.
2900 // This scalar type is the object type.
2901 QualType ObjectType = BaseE->getType();
2902 if (OpKind == tok::arrow) {
2903 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2904 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002905 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002906 // The user wrote "p->" when she probably meant "p."; fix it.
2907 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002908 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002909 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002910 if (isSFINAEContext())
2911 return ExprError();
2912
2913 OpKind = tok::period;
2914 }
2915 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002916
2917 // Compute the object type that we should use for name lookup purposes. Only
2918 // record types and dependent types matter.
2919 void *ObjectTypePtrForLookup = 0;
2920 if (!SS.isSet()) {
Gabor Greif2cd6c7b2010-06-17 11:29:31 +00002921 ObjectTypePtrForLookup = const_cast<RecordType*>(
2922 ObjectType->getAs<RecordType>());
Douglas Gregor678f90d2010-02-25 01:56:36 +00002923 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2924 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2925 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002926
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002927 // Convert the name of the type being destructed (following the ~) into a
2928 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002929 QualType DestructedType;
2930 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002931 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002932 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2933 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2934 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002935 S, &SS, true, ObjectTypePtrForLookup);
2936 if (!T &&
2937 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2938 (!SS.isSet() && ObjectType->isDependentType()))) {
2939 // The name of the type being destroyed is a dependent name, and we
2940 // couldn't find anything useful in scope. Just store the identifier and
2941 // it's location, and we'll perform (qualified) name lookup again at
2942 // template instantiation time.
2943 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2944 SecondTypeName.StartLocation);
2945 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002946 Diag(SecondTypeName.StartLocation,
2947 diag::err_pseudo_dtor_destructor_non_type)
2948 << SecondTypeName.Identifier << ObjectType;
2949 if (isSFINAEContext())
2950 return ExprError();
2951
2952 // Recover by assuming we had the right type all along.
2953 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002954 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002955 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002956 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002957 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002958 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002959 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2960 TemplateId->getTemplateArgs(),
2961 TemplateId->NumArgs);
2962 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2963 TemplateId->TemplateNameLoc,
2964 TemplateId->LAngleLoc,
2965 TemplateArgsPtr,
2966 TemplateId->RAngleLoc);
2967 if (T.isInvalid() || !T.get()) {
2968 // Recover by assuming we had the right type all along.
2969 DestructedType = ObjectType;
2970 } else
2971 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002972 }
2973
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002974 // If we've performed some kind of recovery, (re-)build the type source
2975 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002976 if (!DestructedType.isNull()) {
2977 if (!DestructedTypeInfo)
2978 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002979 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002980 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2981 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002982
2983 // Convert the name of the scope type (the type prior to '::') into a type.
2984 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002985 QualType ScopeType;
2986 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2987 FirstTypeName.Identifier) {
2988 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2989 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2990 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002991 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002992 if (!T) {
2993 Diag(FirstTypeName.StartLocation,
2994 diag::err_pseudo_dtor_destructor_non_type)
2995 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002996
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002997 if (isSFINAEContext())
2998 return ExprError();
2999
3000 // Just drop this type. It's unnecessary anyway.
3001 ScopeType = QualType();
3002 } else
3003 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003004 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003005 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003006 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003007 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3008 TemplateId->getTemplateArgs(),
3009 TemplateId->NumArgs);
3010 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
3011 TemplateId->TemplateNameLoc,
3012 TemplateId->LAngleLoc,
3013 TemplateArgsPtr,
3014 TemplateId->RAngleLoc);
3015 if (T.isInvalid() || !T.get()) {
3016 // Recover by dropping this type.
3017 ScopeType = QualType();
3018 } else
3019 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003020 }
3021 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00003022
3023 if (!ScopeType.isNull() && !ScopeTypeInfo)
3024 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3025 FirstTypeName.StartLocation);
3026
3027
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003028 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003029 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003030 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00003031}
3032
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003033CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00003034 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003035 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00003036 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3037 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00003038 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3039
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003040 MemberExpr *ME =
3041 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3042 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00003043 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00003044 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3045 CXXMemberCallExpr *CE =
3046 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3047 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003048 return CE;
3049}
3050
Anders Carlsson85a307d2009-05-17 18:41:29 +00003051Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3052 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003053 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00003054 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00003055 else
3056 return ExprError();
3057
Anders Carlsson85a307d2009-05-17 18:41:29 +00003058 return Owned(FullExpr);
3059}