blob: 4d93e72be20f3b67d52fd4ed5840f3da6f05ecd2 [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.
Douglas Gregorfe17d252010-02-16 19:09:40 +000056 QualType SearchType;
57 DeclContext *LookupCtx = 0;
58 bool isDependent = false;
59 bool LookInScope = false;
60
61 // If we have an object type, it's because we are in a
62 // pseudo-destructor-expression or a member access expression, and
63 // we know what type we're looking for.
64 if (ObjectTypePtr)
65 SearchType = GetTypeFromParser(ObjectTypePtr);
66
67 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000068 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
69
70 bool AlreadySearched = false;
71 bool LookAtPrefix = true;
72 if (!getLangOptions().CPlusPlus0x) {
73 // C++ [basic.lookup.qual]p6:
74 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
75 // the type-names are looked up as types in the scope designated by the
76 // nested-name-specifier. In a qualified-id of the form:
77 //
78 // ::[opt] nested-name-specifier ̃ class-name
79 //
80 // where the nested-name-specifier designates a namespace scope, and in
81 // a qualified-id of the form:
82 //
83 // ::opt nested-name-specifier class-name :: ̃ class-name
84 //
85 // the class-names are looked up as types in the scope designated by
86 // the nested-name-specifier.
87 //
88 // Here, we check the first case (completely) and determine whether the
89 // code below is permitted to look at the prefix of the
90 // nested-name-specifier (as we do in C++0x).
91 DeclContext *DC = computeDeclContext(SS, EnteringContext);
92 if (DC && DC->isFileContext()) {
93 AlreadySearched = true;
94 LookupCtx = DC;
95 isDependent = false;
96 } else if (DC && isa<CXXRecordDecl>(DC))
97 LookAtPrefix = false;
98 }
99
100 // C++0x [basic.lookup.qual]p6:
Douglas Gregorfe17d252010-02-16 19:09:40 +0000101 // If a pseudo-destructor-name (5.2.4) contains a
102 // nested-name-specifier, the type-names are looked up as types
103 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth8f254812010-02-21 10:19:54 +0000104 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +0000105 //
106 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
107 //
108 // the second class-name is looked up in the same scope as the first.
109 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000110 // To implement this, we look at the prefix of the
111 // nested-name-specifier we were given, and determine the lookup
112 // context from that.
113 //
114 // We also fold in the second case from the C++03 rules quoted further
115 // above.
116 NestedNameSpecifier *Prefix = 0;
117 if (AlreadySearched) {
118 // Nothing left to do.
119 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
120 CXXScopeSpec PrefixSS;
121 PrefixSS.setScopeRep(Prefix);
122 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
123 isDependent = isDependentScopeSpecifier(PrefixSS);
124 } else if (getLangOptions().CPlusPlus0x &&
125 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
126 if (!LookupCtx->isTranslationUnit())
127 LookupCtx = LookupCtx->getParent();
128 isDependent = LookupCtx && LookupCtx->isDependentContext();
129 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000130 LookupCtx = computeDeclContext(SearchType);
131 isDependent = SearchType->isDependentType();
132 } else {
133 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000134 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000135 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000136
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000137 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000138 } else if (ObjectTypePtr) {
139 // C++ [basic.lookup.classref]p3:
140 // If the unqualified-id is ~type-name, the type-name is looked up
141 // in the context of the entire postfix-expression. If the type T
142 // of the object expression is of a class type C, the type-name is
143 // also looked up in the scope of class C. At least one of the
144 // lookups shall find a name that refers to (possibly
145 // cv-qualified) T.
146 LookupCtx = computeDeclContext(SearchType);
147 isDependent = SearchType->isDependentType();
148 assert((isDependent || !SearchType->isIncompleteType()) &&
149 "Caller should have completed object type");
150
151 LookInScope = true;
152 } else {
153 // Perform lookup into the current scope (only).
154 LookInScope = true;
155 }
156
157 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
158 for (unsigned Step = 0; Step != 2; ++Step) {
159 // Look for the name first in the computed lookup context (if we
160 // have one) and, if that fails to find a match, in the sope (if
161 // we're allowed to look there).
162 Found.clear();
163 if (Step == 0 && LookupCtx)
164 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000165 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 LookupName(Found, S);
167 else
168 continue;
169
170 // FIXME: Should we be suppressing ambiguities here?
171 if (Found.isAmbiguous())
172 return 0;
173
174 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
175 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000176
177 if (SearchType.isNull() || SearchType->isDependentType() ||
178 Context.hasSameUnqualifiedType(T, SearchType)) {
179 // We found our type!
180
181 return T.getAsOpaquePtr();
182 }
183 }
184
185 // If the name that we found is a class template name, and it is
186 // the same name as the template name in the last part of the
187 // nested-name-specifier (if present) or the object type, then
188 // this is the destructor for that class.
189 // FIXME: This is a workaround until we get real drafting for core
190 // issue 399, for which there isn't even an obvious direction.
191 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
192 QualType MemberOfType;
193 if (SS.isSet()) {
194 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
195 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000196 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
197 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000198 }
199 }
200 if (MemberOfType.isNull())
201 MemberOfType = SearchType;
202
203 if (MemberOfType.isNull())
204 continue;
205
206 // We're referring into a class template specialization. If the
207 // class template we found is the same as the template being
208 // specialized, we found what we are looking for.
209 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
210 if (ClassTemplateSpecializationDecl *Spec
211 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
212 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
213 Template->getCanonicalDecl())
214 return MemberOfType.getAsOpaquePtr();
215 }
216
217 continue;
218 }
219
220 // We're referring to an unresolved class template
221 // specialization. Determine whether we class template we found
222 // is the same as the template being specialized or, if we don't
223 // know which template is being specialized, that it at least
224 // has the same name.
225 if (const TemplateSpecializationType *SpecType
226 = MemberOfType->getAs<TemplateSpecializationType>()) {
227 TemplateName SpecName = SpecType->getTemplateName();
228
229 // The class template we found is the same template being
230 // specialized.
231 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
232 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
233 return MemberOfType.getAsOpaquePtr();
234
235 continue;
236 }
237
238 // The class template we found has the same name as the
239 // (dependent) template name being specialized.
240 if (DependentTemplateName *DepTemplate
241 = SpecName.getAsDependentTemplateName()) {
242 if (DepTemplate->isIdentifier() &&
243 DepTemplate->getIdentifier() == Template->getIdentifier())
244 return MemberOfType.getAsOpaquePtr();
245
246 continue;
247 }
248 }
249 }
250 }
251
252 if (isDependent) {
253 // We didn't find our type, but that's okay: it's dependent
254 // anyway.
255 NestedNameSpecifier *NNS = 0;
256 SourceRange Range;
257 if (SS.isSet()) {
258 NNS = (NestedNameSpecifier *)SS.getScopeRep();
259 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
260 } else {
261 NNS = NestedNameSpecifier::Create(Context, &II);
262 Range = SourceRange(NameLoc);
263 }
264
Abramo Bagnarad7548482010-05-19 21:37:53 +0000265 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
266 Range, NameLoc).getAsOpaquePtr();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000267 }
268
269 if (ObjectTypePtr)
270 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
271 << &II;
272 else
273 Diag(NameLoc, diag::err_destructor_class_name);
274
275 return 0;
276}
277
Douglas Gregor9da64192010-04-26 22:37:10 +0000278/// \brief Build a C++ typeid expression with a type operand.
279Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
280 SourceLocation TypeidLoc,
281 TypeSourceInfo *Operand,
282 SourceLocation RParenLoc) {
283 // C++ [expr.typeid]p4:
284 // The top-level cv-qualifiers of the lvalue expression or the type-id
285 // that is the operand of typeid are always ignored.
286 // If the type of the type-id is a class type or a reference to a class
287 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000288 Qualifiers Quals;
289 QualType T
290 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
291 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000292 if (T->getAs<RecordType>() &&
293 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
294 return ExprError();
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000295
Douglas Gregor9da64192010-04-26 22:37:10 +0000296 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
297 Operand,
298 SourceRange(TypeidLoc, RParenLoc)));
299}
300
301/// \brief Build a C++ typeid expression with an expression operand.
302Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
303 SourceLocation TypeidLoc,
304 ExprArg Operand,
305 SourceLocation RParenLoc) {
306 bool isUnevaluatedOperand = true;
307 Expr *E = static_cast<Expr *>(Operand.get());
308 if (E && !E->isTypeDependent()) {
309 QualType T = E->getType();
310 if (const RecordType *RecordT = T->getAs<RecordType>()) {
311 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
312 // C++ [expr.typeid]p3:
313 // [...] If the type of the expression is a class type, the class
314 // shall be completely-defined.
315 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
316 return ExprError();
317
318 // C++ [expr.typeid]p3:
319 // When typeid is applied to an expression other than an lvalue of a
320 // polymorphic class type [...] [the] expression is an unevaluated
321 // operand. [...]
Douglas Gregor88d292c2010-05-13 16:44:06 +0000322 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000323 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000324
325 // We require a vtable to query the type at run time.
326 MarkVTableUsed(TypeidLoc, RecordD);
327 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000328 }
329
330 // C++ [expr.typeid]p4:
331 // [...] If the type of the type-id is a reference to a possibly
332 // cv-qualified type, the result of the typeid expression refers to a
333 // std::type_info object representing the cv-unqualified referenced
334 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000335 Qualifiers Quals;
336 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
337 if (!Context.hasSameType(T, UnqualT)) {
338 T = UnqualT;
339 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, E->isLvalue(Context));
Douglas Gregor9da64192010-04-26 22:37:10 +0000340 Operand.release();
341 Operand = Owned(E);
342 }
343 }
344
345 // If this is an unevaluated operand, clear out the set of
346 // declaration references we have been computing and eliminate any
347 // temporaries introduced in its computation.
348 if (isUnevaluatedOperand)
349 ExprEvalContexts.back().Context = Unevaluated;
350
351 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
352 Operand.takeAs<Expr>(),
353 SourceRange(TypeidLoc, RParenLoc)));
354}
355
356/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000357Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000358Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
359 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000360 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000361 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000362 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000363
Chris Lattnerec7f7732008-11-20 05:51:55 +0000364 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000365 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
366 LookupQualifiedName(R, StdNamespace);
John McCall67c00872009-12-02 08:25:40 +0000367 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000368 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000369 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor9da64192010-04-26 22:37:10 +0000370
Sebastian Redlc4704762008-11-11 11:37:55 +0000371 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor9da64192010-04-26 22:37:10 +0000372
373 if (isType) {
374 // The operand is a type; handle it as such.
375 TypeSourceInfo *TInfo = 0;
376 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
377 if (T.isNull())
378 return ExprError();
379
380 if (!TInfo)
381 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000382
Douglas Gregor9da64192010-04-26 22:37:10 +0000383 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000384 }
Mike Stump11289f42009-09-09 15:08:12 +0000385
Douglas Gregor9da64192010-04-26 22:37:10 +0000386 // The operand is an expression.
387 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000388}
389
Steve Naroff66356bd2007-09-16 14:56:35 +0000390/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000391Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000392Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000393 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000394 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000395 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
396 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000397}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000398
Sebastian Redl576fd422009-05-10 18:38:11 +0000399/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
400Action::OwningExprResult
401Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
402 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
403}
404
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000405/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000406Action::OwningExprResult
407Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000408 Expr *Ex = E.takeAs<Expr>();
409 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
410 return ExprError();
411 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
412}
413
414/// CheckCXXThrowOperand - Validate the operand of a throw.
415bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
416 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000417 // A throw-expression initializes a temporary object, called the exception
418 // object, the type of which is determined by removing any top-level
419 // cv-qualifiers from the static type of the operand of throw and adjusting
420 // the type from "array of T" or "function returning T" to "pointer to T"
421 // or "pointer to function returning T", [...]
422 if (E->getType().hasQualifiers())
423 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
424 E->isLvalue(Context) == Expr::LV_Valid);
425
Sebastian Redl4de47b42009-04-27 20:27:31 +0000426 DefaultFunctionArrayConversion(E);
427
428 // If the type of the exception would be an incomplete type or a pointer
429 // to an incomplete type other than (cv) void the program is ill-formed.
430 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000431 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000432 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000433 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000434 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000435 }
436 if (!isPointer || !Ty->isVoidType()) {
437 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000438 PDiag(isPointer ? diag::err_throw_incomplete_ptr
439 : diag::err_throw_incomplete)
440 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000441 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000442
Douglas Gregore8154332010-04-15 18:05:39 +0000443 if (RequireNonAbstractType(ThrowLoc, E->getType(),
444 PDiag(diag::err_throw_abstract_type)
445 << E->getSourceRange()))
446 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000447 }
448
John McCall2e6567a2010-04-22 01:10:34 +0000449 // Initialize the exception result. This implicitly weeds out
450 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000451 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000452 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000453 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
454 /*NRVO=*/false);
John McCall2e6567a2010-04-22 01:10:34 +0000455 OwningExprResult Res = PerformCopyInitialization(Entity,
456 SourceLocation(),
457 Owned(E));
458 if (Res.isInvalid())
459 return true;
460 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000461
Eli Friedman91a3d272010-06-03 20:39:03 +0000462 // If the exception has class type, we need additional handling.
463 const RecordType *RecordTy = Ty->getAs<RecordType>();
464 if (!RecordTy)
465 return false;
466 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
467
Douglas Gregor88d292c2010-05-13 16:44:06 +0000468 // If we are throwing a polymorphic class type or pointer thereof,
469 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000470 MarkVTableUsed(ThrowLoc, RD);
471
472 // If the class has a non-trivial destructor, we must be able to call it.
473 if (RD->hasTrivialDestructor())
474 return false;
475
476 CXXDestructorDecl *Destructor =
477 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context));
478 if (!Destructor)
479 return false;
480
481 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
482 CheckDestructorAccess(E->getExprLoc(), Destructor,
483 PDiag(diag::err_access_dtor_temp) << Ty);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000484 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000485}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000486
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000487Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000488 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
489 /// is a non-lvalue expression whose value is the address of the object for
490 /// which the function is called.
491
John McCall87fe5d52010-05-20 01:18:31 +0000492 DeclContext *DC = getFunctionLevelDeclContext();
493 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000494 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000495 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000496 MD->getThisType(Context),
497 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000498
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000499 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000500}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000501
502/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
503/// Can be interpreted either as function-style casting ("int(x)")
504/// or class type construction ("ClassType(x,y,z)")
505/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000506Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000507Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
508 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000509 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000510 SourceLocation *CommaLocs,
511 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000512 if (!TypeRep)
513 return ExprError();
514
John McCall97513962010-01-15 18:39:57 +0000515 TypeSourceInfo *TInfo;
516 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
517 if (!TInfo)
518 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000519 unsigned NumExprs = exprs.size();
520 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000521 SourceLocation TyBeginLoc = TypeRange.getBegin();
522 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
523
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000524 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000525 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000526 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000527
528 return Owned(CXXUnresolvedConstructExpr::Create(Context,
529 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000530 LParenLoc,
531 Exprs, NumExprs,
532 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000533 }
534
Anders Carlsson55243162009-08-27 03:53:50 +0000535 if (Ty->isArrayType())
536 return ExprError(Diag(TyBeginLoc,
537 diag::err_value_init_for_array_type) << FullRange);
538 if (!Ty->isVoidType() &&
539 RequireCompleteType(TyBeginLoc, Ty,
540 PDiag(diag::err_invalid_incomplete_type_use)
541 << FullRange))
542 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000543
Anders Carlsson55243162009-08-27 03:53:50 +0000544 if (RequireNonAbstractType(TyBeginLoc, Ty,
545 diag::err_allocation_of_abstract_type))
546 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000547
548
Douglas Gregordd04d332009-01-16 18:33:17 +0000549 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000550 // If the expression list is a single expression, the type conversion
551 // expression is equivalent (in definedness, and if defined in meaning) to the
552 // corresponding cast expression.
553 //
554 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000555 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000556 CXXBaseSpecifierArray BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +0000557 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
558 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000559 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000560
561 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000562
563 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000564 TInfo, TyBeginLoc, Kind,
Anders Carlsson5d270e82010-04-24 18:38:56 +0000565 Exprs[0], BasePath,
566 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000567 }
568
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000569 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000570 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000571
Mike Stump11289f42009-09-09 15:08:12 +0000572 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000573 !Record->hasTrivialDestructor()) {
Eli Friedmana6824272010-01-31 20:58:15 +0000574 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
575 InitializationKind Kind
576 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
577 LParenLoc, RParenLoc)
578 : InitializationKind::CreateValue(TypeRange.getBegin(),
579 LParenLoc, RParenLoc);
580 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
581 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
582 move(exprs));
Douglas Gregordd04d332009-01-16 18:33:17 +0000583
Eli Friedmana6824272010-01-31 20:58:15 +0000584 // FIXME: Improve AST representation?
585 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000586 }
587
588 // Fall through to value-initialize an object of class type that
589 // doesn't have a user-declared default constructor.
590 }
591
592 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000593 // If the expression list specifies more than a single value, the type shall
594 // be a class with a suitably declared constructor.
595 //
596 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000597 return ExprError(Diag(CommaLocs[0],
598 diag::err_builtin_func_cast_more_than_one_arg)
599 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000600
601 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000602 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000603 // The expression T(), where T is a simple-type-specifier for a non-array
604 // complete object type or the (possibly cv-qualified) void type, creates an
605 // rvalue of the specified type, which is value-initialized.
606 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000607 exprs.release();
608 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000609}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000610
611
Sebastian Redlbd150f42008-11-21 19:14:01 +0000612/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
613/// @code new (memory) int[size][4] @endcode
614/// or
615/// @code ::new Foo(23, "hello") @endcode
616/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000617Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000618Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000619 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000620 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000621 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000622 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000623 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000624 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000625 // If the specified type is an array, unwrap it and save the expression.
626 if (D.getNumTypeObjects() > 0 &&
627 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
628 DeclaratorChunk &Chunk = D.getTypeObject(0);
629 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000630 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
631 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000632 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000633 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
634 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000635
636 if (ParenTypeId) {
637 // Can't have dynamic array size when the type-id is in parentheses.
638 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
639 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
640 !NumElts->isIntegerConstantExpr(Context)) {
641 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
642 << NumElts->getSourceRange();
643 return ExprError();
644 }
645 }
646
Sebastian Redl351bb782008-12-02 14:43:59 +0000647 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000648 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000649 }
650
Douglas Gregor73341c42009-09-11 00:18:58 +0000651 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000652 if (ArraySize) {
653 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000654 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
655 break;
656
657 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
658 if (Expr *NumElts = (Expr *)Array.NumElts) {
659 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
660 !NumElts->isIntegerConstantExpr(Context)) {
661 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
662 << NumElts->getSourceRange();
663 return ExprError();
664 }
665 }
666 }
667 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000668
John McCallbcd03502009-12-07 02:54:59 +0000669 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCall8cb7bdf2010-06-04 23:28:52 +0000670 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
671 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000672 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000673 return ExprError();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000674
675 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000676 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000677 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000678 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000679 PlacementRParen,
680 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000681 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000682 D.getSourceRange().getBegin(),
Ted Kremenekabb1f912010-06-25 22:48:49 +0000683 R,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000684 Owned(ArraySize),
685 ConstructorLParen,
686 move(ConstructorArgs),
687 ConstructorRParen);
688}
689
Mike Stump11289f42009-09-09 15:08:12 +0000690Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000691Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
692 SourceLocation PlacementLParen,
693 MultiExprArg PlacementArgs,
694 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000695 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000696 QualType AllocType,
697 SourceLocation TypeLoc,
698 SourceRange TypeRange,
699 ExprArg ArraySizeE,
700 SourceLocation ConstructorLParen,
701 MultiExprArg ConstructorArgs,
702 SourceLocation ConstructorRParen) {
703 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000704 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000705
Douglas Gregorcda95f42010-05-16 16:01:03 +0000706 // Per C++0x [expr.new]p5, the type being constructed may be a
707 // typedef of an array type.
708 if (!ArraySizeE.get()) {
709 if (const ConstantArrayType *Array
710 = Context.getAsConstantArrayType(AllocType)) {
711 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
712 Context.getSizeType(),
713 TypeRange.getEnd()));
714 AllocType = Array->getElementType();
715 }
716 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000717
Douglas Gregorcda95f42010-05-16 16:01:03 +0000718 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000719
Sebastian Redlbd150f42008-11-21 19:14:01 +0000720 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
721 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000722 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000723 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000724 QualType SizeType = ArraySize->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000725 if (!SizeType->isIntegralOrEnumerationType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000726 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
727 diag::err_array_size_not_integral)
728 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000729 // Let's see if this is a constant < 0. If so, we reject it out of hand.
730 // We don't care about special rules, so we tell the machinery it's not
731 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000732 if (!ArraySize->isValueDependent()) {
733 llvm::APSInt Value;
734 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
735 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000736 llvm::APInt::getNullValue(Value.getBitWidth()),
737 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000738 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
739 diag::err_typecheck_negative_array_size)
740 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000741 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000742 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000743
Eli Friedman06ed2a52009-10-20 08:27:19 +0000744 ImpCastExprToType(ArraySize, Context.getSizeType(),
745 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000746 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000747
Sebastian Redlbd150f42008-11-21 19:14:01 +0000748 FunctionDecl *OperatorNew = 0;
749 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000750 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
751 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000752
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000753 if (!AllocType->isDependentType() &&
754 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
755 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000756 SourceRange(PlacementLParen, PlacementRParen),
757 UseGlobal, AllocType, ArraySize, PlaceArgs,
758 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000759 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000760 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000761 if (OperatorNew) {
762 // Add default arguments, if any.
763 const FunctionProtoType *Proto =
764 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000765 VariadicCallType CallType =
766 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000767
768 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
769 Proto, 1, PlaceArgs, NumPlaceArgs,
770 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000771 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000772
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000773 NumPlaceArgs = AllPlaceArgs.size();
774 if (NumPlaceArgs > 0)
775 PlaceArgs = &AllPlaceArgs[0];
776 }
777
Sebastian Redlbd150f42008-11-21 19:14:01 +0000778 bool Init = ConstructorLParen.isValid();
779 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000780 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000781 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
782 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000783 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
784
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000785 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000786 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000787 SourceRange InitRange(ConsArgs[0]->getLocStart(),
788 ConsArgs[NumConsArgs - 1]->getLocEnd());
789
790 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
791 return ExprError();
792 }
793
Douglas Gregor85dabae2009-12-16 01:38:02 +0000794 if (!AllocType->isDependentType() &&
795 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
796 // C++0x [expr.new]p15:
797 // A new-expression that creates an object of type T initializes that
798 // object as follows:
799 InitializationKind Kind
800 // - If the new-initializer is omitted, the object is default-
801 // initialized (8.5); if no initialization is performed,
802 // the object has indeterminate value
803 = !Init? InitializationKind::CreateDefault(TypeLoc)
804 // - Otherwise, the new-initializer is interpreted according to the
805 // initialization rules of 8.5 for direct-initialization.
806 : InitializationKind::CreateDirect(TypeLoc,
807 ConstructorLParen,
808 ConstructorRParen);
809
Douglas Gregor85dabae2009-12-16 01:38:02 +0000810 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000811 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000812 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000813 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
814 move(ConstructorArgs));
815 if (FullInit.isInvalid())
816 return ExprError();
817
818 // FullInit is our initializer; walk through it to determine if it's a
819 // constructor call, which CXXNewExpr handles directly.
820 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
821 if (CXXBindTemporaryExpr *Binder
822 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
823 FullInitExpr = Binder->getSubExpr();
824 if (CXXConstructExpr *Construct
825 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
826 Constructor = Construct->getConstructor();
827 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
828 AEnd = Construct->arg_end();
829 A != AEnd; ++A)
830 ConvertedConstructorArgs.push_back(A->Retain());
831 } else {
832 // Take the converted initializer.
833 ConvertedConstructorArgs.push_back(FullInit.release());
834 }
835 } else {
836 // No initialization required.
837 }
838
839 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000840 NumConsArgs = ConvertedConstructorArgs.size();
841 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000842 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000843
Douglas Gregor6642ca22010-02-26 05:06:18 +0000844 // Mark the new and delete operators as referenced.
845 if (OperatorNew)
846 MarkDeclarationReferenced(StartLoc, OperatorNew);
847 if (OperatorDelete)
848 MarkDeclarationReferenced(StartLoc, OperatorDelete);
849
Sebastian Redlbd150f42008-11-21 19:14:01 +0000850 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000851
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000852 PlacementArgs.release();
853 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000854 ArraySizeE.release();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000855
856 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000857 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
858 PlaceArgs, NumPlaceArgs, ParenTypeId,
859 ArraySize, Constructor, Init,
860 ConsArgs, NumConsArgs, OperatorDelete,
861 ResultType, StartLoc,
862 Init ? ConstructorRParen :
Ted Kremenekabb1f912010-06-25 22:48:49 +0000863 TypeRange.getEnd()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000864}
865
866/// CheckAllocatedType - Checks that a type is suitable as the allocated type
867/// in a new-expression.
868/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000869bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000870 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000871 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
872 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000873 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000874 return Diag(Loc, diag::err_bad_new_type)
875 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000876 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000877 return Diag(Loc, diag::err_bad_new_type)
878 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000879 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000880 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000881 PDiag(diag::err_new_incomplete_type)
882 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000883 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000884 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000885 diag::err_allocation_of_abstract_type))
886 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000887
Sebastian Redlbd150f42008-11-21 19:14:01 +0000888 return false;
889}
890
Douglas Gregor6642ca22010-02-26 05:06:18 +0000891/// \brief Determine whether the given function is a non-placement
892/// deallocation function.
893static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
894 if (FD->isInvalidDecl())
895 return false;
896
897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
898 return Method->isUsualDeallocationFunction();
899
900 return ((FD->getOverloadedOperator() == OO_Delete ||
901 FD->getOverloadedOperator() == OO_Array_Delete) &&
902 FD->getNumParams() == 1);
903}
904
Sebastian Redlfaf68082008-12-03 20:26:15 +0000905/// FindAllocationFunctions - Finds the overloads of operator new and delete
906/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000907bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
908 bool UseGlobal, QualType AllocType,
909 bool IsArray, Expr **PlaceArgs,
910 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000911 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000912 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000913 // --- Choosing an allocation function ---
914 // C++ 5.3.4p8 - 14 & 18
915 // 1) If UseGlobal is true, only look in the global scope. Else, also look
916 // in the scope of the allocated class.
917 // 2) If an array size is given, look for operator new[], else look for
918 // operator new.
919 // 3) The first argument is always size_t. Append the arguments from the
920 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000921
922 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
923 // We don't care about the actual value of this argument.
924 // FIXME: Should the Sema create the expression and embed it in the syntax
925 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000926 IntegerLiteral Size(llvm::APInt::getNullValue(
927 Context.Target.getPointerWidth(0)),
928 Context.getSizeType(),
929 SourceLocation());
930 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000931 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
932
Douglas Gregor6642ca22010-02-26 05:06:18 +0000933 // C++ [expr.new]p8:
934 // If the allocated type is a non-array type, the allocation
935 // function’s name is operator new and the deallocation function’s
936 // name is operator delete. If the allocated type is an array
937 // type, the allocation function’s name is operator new[] and the
938 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000939 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
940 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000941 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
942 IsArray ? OO_Array_Delete : OO_Delete);
943
Sebastian Redlfaf68082008-12-03 20:26:15 +0000944 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000945 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000946 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000947 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000948 AllocArgs.size(), Record, /*AllowMissing=*/true,
949 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000950 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000951 }
952 if (!OperatorNew) {
953 // Didn't find a member overload. Look for a global one.
954 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000955 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000956 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000957 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
958 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000959 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000960 }
961
John McCall0f55a032010-04-20 02:18:25 +0000962 // We don't need an operator delete if we're running under
963 // -fno-exceptions.
964 if (!getLangOptions().Exceptions) {
965 OperatorDelete = 0;
966 return false;
967 }
968
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000969 // FindAllocationOverload can change the passed in arguments, so we need to
970 // copy them back.
971 if (NumPlaceArgs > 0)
972 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000973
Douglas Gregor6642ca22010-02-26 05:06:18 +0000974 // C++ [expr.new]p19:
975 //
976 // If the new-expression begins with a unary :: operator, the
977 // deallocation function’s name is looked up in the global
978 // scope. Otherwise, if the allocated type is a class type T or an
979 // array thereof, the deallocation function’s name is looked up in
980 // the scope of T. If this lookup fails to find the name, or if
981 // the allocated type is not a class type or array thereof, the
982 // deallocation function’s name is looked up in the global scope.
983 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
984 if (AllocType->isRecordType() && !UseGlobal) {
985 CXXRecordDecl *RD
986 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
987 LookupQualifiedName(FoundDelete, RD);
988 }
John McCallfb6f5262010-03-18 08:19:33 +0000989 if (FoundDelete.isAmbiguous())
990 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000991
992 if (FoundDelete.empty()) {
993 DeclareGlobalNewDelete();
994 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
995 }
996
997 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000998
999 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1000
John McCallfb6f5262010-03-18 08:19:33 +00001001 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001002 // C++ [expr.new]p20:
1003 // A declaration of a placement deallocation function matches the
1004 // declaration of a placement allocation function if it has the
1005 // same number of parameters and, after parameter transformations
1006 // (8.3.5), all parameter types except the first are
1007 // identical. [...]
1008 //
1009 // To perform this comparison, we compute the function type that
1010 // the deallocation function should have, and use that type both
1011 // for template argument deduction and for comparison purposes.
1012 QualType ExpectedFunctionType;
1013 {
1014 const FunctionProtoType *Proto
1015 = OperatorNew->getType()->getAs<FunctionProtoType>();
1016 llvm::SmallVector<QualType, 4> ArgTypes;
1017 ArgTypes.push_back(Context.VoidPtrTy);
1018 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1019 ArgTypes.push_back(Proto->getArgType(I));
1020
1021 ExpectedFunctionType
1022 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1023 ArgTypes.size(),
1024 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001025 0, false, false, 0, 0,
1026 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001027 }
1028
1029 for (LookupResult::iterator D = FoundDelete.begin(),
1030 DEnd = FoundDelete.end();
1031 D != DEnd; ++D) {
1032 FunctionDecl *Fn = 0;
1033 if (FunctionTemplateDecl *FnTmpl
1034 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1035 // Perform template argument deduction to try to match the
1036 // expected function type.
1037 TemplateDeductionInfo Info(Context, StartLoc);
1038 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1039 continue;
1040 } else
1041 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1042
1043 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001044 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001045 }
1046 } else {
1047 // C++ [expr.new]p20:
1048 // [...] Any non-placement deallocation function matches a
1049 // non-placement allocation function. [...]
1050 for (LookupResult::iterator D = FoundDelete.begin(),
1051 DEnd = FoundDelete.end();
1052 D != DEnd; ++D) {
1053 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1054 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001055 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001056 }
1057 }
1058
1059 // C++ [expr.new]p20:
1060 // [...] If the lookup finds a single matching deallocation
1061 // function, that function will be called; otherwise, no
1062 // deallocation function will be called.
1063 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001064 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001065
1066 // C++0x [expr.new]p20:
1067 // If the lookup finds the two-parameter form of a usual
1068 // deallocation function (3.7.4.2) and that function, considered
1069 // as a placement deallocation function, would have been
1070 // selected as a match for the allocation function, the program
1071 // is ill-formed.
1072 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1073 isNonPlacementDeallocationFunction(OperatorDelete)) {
1074 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1075 << SourceRange(PlaceArgs[0]->getLocStart(),
1076 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1077 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1078 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001079 } else {
1080 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001081 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001082 }
1083 }
1084
Sebastian Redlfaf68082008-12-03 20:26:15 +00001085 return false;
1086}
1087
Sebastian Redl33a31012008-12-04 22:20:51 +00001088/// FindAllocationOverload - Find an fitting overload for the allocation
1089/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001090bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1091 DeclarationName Name, Expr** Args,
1092 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001093 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001094 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1095 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001096 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001097 if (AllowMissing)
1098 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001099 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001100 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001101 }
1102
John McCallfb6f5262010-03-18 08:19:33 +00001103 if (R.isAmbiguous())
1104 return true;
1105
1106 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001107
John McCallbc077cf2010-02-08 23:07:23 +00001108 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001109 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1110 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001111 // Even member operator new/delete are implicitly treated as
1112 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001113 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001114
John McCalla0296f72010-03-19 07:35:19 +00001115 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1116 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001117 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1118 Candidates,
1119 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001120 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001121 }
1122
John McCalla0296f72010-03-19 07:35:19 +00001123 FunctionDecl *Fn = cast<FunctionDecl>(D);
1124 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001125 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001126 }
1127
1128 // Do the resolution.
1129 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001130 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001131 case OR_Success: {
1132 // Got one!
1133 FunctionDecl *FnDecl = Best->Function;
1134 // The first argument is size_t, and the first parameter must be size_t,
1135 // too. This is checked on declaration and can be assumed. (It can't be
1136 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001137 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001138 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1139 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-03-26 20:35:59 +00001140 OwningExprResult Result
1141 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1142 FnDecl->getParamDecl(i)),
1143 SourceLocation(),
1144 Owned(Args[i]->Retain()));
1145 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001146 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001147
1148 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001149 }
1150 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001151 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001152 return false;
1153 }
1154
1155 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001156 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001157 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001158 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001159 return true;
1160
1161 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001162 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001163 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001164 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001165 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001166
1167 case OR_Deleted:
1168 Diag(StartLoc, diag::err_ovl_deleted_call)
1169 << Best->Function->isDeleted()
1170 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001171 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001172 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001173 }
1174 assert(false && "Unreachable, bad result from BestViableFunction");
1175 return true;
1176}
1177
1178
Sebastian Redlfaf68082008-12-03 20:26:15 +00001179/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1180/// delete. These are:
1181/// @code
1182/// void* operator new(std::size_t) throw(std::bad_alloc);
1183/// void* operator new[](std::size_t) throw(std::bad_alloc);
1184/// void operator delete(void *) throw();
1185/// void operator delete[](void *) throw();
1186/// @endcode
1187/// Note that the placement and nothrow forms of new are *not* implicitly
1188/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001189void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001190 if (GlobalNewDeleteDeclared)
1191 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001192
1193 // C++ [basic.std.dynamic]p2:
1194 // [...] The following allocation and deallocation functions (18.4) are
1195 // implicitly declared in global scope in each translation unit of a
1196 // program
1197 //
1198 // void* operator new(std::size_t) throw(std::bad_alloc);
1199 // void* operator new[](std::size_t) throw(std::bad_alloc);
1200 // void operator delete(void*) throw();
1201 // void operator delete[](void*) throw();
1202 //
1203 // These implicit declarations introduce only the function names operator
1204 // new, operator new[], operator delete, operator delete[].
1205 //
1206 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1207 // "std" or "bad_alloc" as necessary to form the exception specification.
1208 // However, we do not make these implicit declarations visible to name
1209 // lookup.
1210 if (!StdNamespace) {
1211 // The "std" namespace has not yet been defined, so build one implicitly.
1212 StdNamespace = NamespaceDecl::Create(Context,
1213 Context.getTranslationUnitDecl(),
1214 SourceLocation(),
1215 &PP.getIdentifierTable().get("std"));
1216 StdNamespace->setImplicit(true);
1217 }
1218
1219 if (!StdBadAlloc) {
1220 // The "std::bad_alloc" class has not yet been declared, so build it
1221 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001222 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor87f54062009-09-15 22:30:29 +00001223 StdNamespace,
1224 SourceLocation(),
1225 &PP.getIdentifierTable().get("bad_alloc"),
1226 SourceLocation(), 0);
1227 StdBadAlloc->setImplicit(true);
1228 }
1229
Sebastian Redlfaf68082008-12-03 20:26:15 +00001230 GlobalNewDeleteDeclared = true;
1231
1232 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1233 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001234 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001235
Sebastian Redlfaf68082008-12-03 20:26:15 +00001236 DeclareGlobalAllocationFunction(
1237 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001238 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001239 DeclareGlobalAllocationFunction(
1240 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001241 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001242 DeclareGlobalAllocationFunction(
1243 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1244 Context.VoidTy, VoidPtr);
1245 DeclareGlobalAllocationFunction(
1246 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1247 Context.VoidTy, VoidPtr);
1248}
1249
1250/// DeclareGlobalAllocationFunction - Declares a single implicit global
1251/// allocation function if it doesn't already exist.
1252void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001253 QualType Return, QualType Argument,
1254 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001255 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1256
1257 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001258 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001259 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001260 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001261 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001262 // Only look at non-template functions, as it is the predefined,
1263 // non-templated allocation function we are trying to declare here.
1264 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1265 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001266 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001267 Func->getParamDecl(0)->getType().getUnqualifiedType());
1268 // FIXME: Do we need to check for default arguments here?
1269 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1270 return;
1271 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001272 }
1273 }
1274
Douglas Gregor87f54062009-09-15 22:30:29 +00001275 QualType BadAllocType;
1276 bool HasBadAllocExceptionSpec
1277 = (Name.getCXXOverloadedOperator() == OO_New ||
1278 Name.getCXXOverloadedOperator() == OO_Array_New);
1279 if (HasBadAllocExceptionSpec) {
1280 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1281 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1282 }
1283
1284 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1285 true, false,
1286 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001287 &BadAllocType,
1288 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001289 FunctionDecl *Alloc =
1290 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001291 FnType, /*TInfo=*/0, FunctionDecl::None,
1292 FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001293 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001294
1295 if (AddMallocAttr)
1296 Alloc->addAttr(::new (Context) MallocAttr());
1297
Sebastian Redlfaf68082008-12-03 20:26:15 +00001298 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001299 0, Argument, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001300 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001301 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001302 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001303
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001304 // FIXME: Also add this declaration to the IdentifierResolver, but
1305 // make sure it is at the end of the chain to coincide with the
1306 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001307 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001308}
1309
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001310bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1311 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001312 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001313 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001314 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001315 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001316
John McCall27b18f82009-11-17 02:14:36 +00001317 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001318 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001319
1320 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1321 F != FEnd; ++F) {
1322 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1323 if (Delete->isUsualDeallocationFunction()) {
1324 Operator = Delete;
1325 return false;
1326 }
1327 }
1328
1329 // We did find operator delete/operator delete[] declarations, but
1330 // none of them were suitable.
1331 if (!Found.empty()) {
1332 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1333 << Name << RD;
1334
1335 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1336 F != FEnd; ++F) {
Douglas Gregor861eb802010-04-25 20:55:08 +00001337 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001338 << Name;
1339 }
1340
1341 return true;
1342 }
1343
1344 // Look for a global declaration.
1345 DeclareGlobalNewDelete();
1346 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1347
1348 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1349 Expr* DeallocArgs[1];
1350 DeallocArgs[0] = &Null;
1351 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1352 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1353 Operator))
1354 return true;
1355
1356 assert(Operator && "Did not find a deallocation function!");
1357 return false;
1358}
1359
Sebastian Redlbd150f42008-11-21 19:14:01 +00001360/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1361/// @code ::delete ptr; @endcode
1362/// or
1363/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001364Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001365Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001366 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001367 // C++ [expr.delete]p1:
1368 // The operand shall have a pointer type, or a class type having a single
1369 // conversion function to a pointer type. The result has type void.
1370 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001371 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1372
Anders Carlssona471db02009-08-16 20:29:29 +00001373 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001374
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001375 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001376 if (!Ex->isTypeDependent()) {
1377 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001378
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001379 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCallda4458e2010-03-31 01:36:47 +00001380 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1381
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001382 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001383 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001384 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001385 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001386 NamedDecl *D = I.getDecl();
1387 if (isa<UsingShadowDecl>(D))
1388 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1389
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001390 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001391 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001392 continue;
1393
John McCallda4458e2010-03-31 01:36:47 +00001394 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001395
1396 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1397 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1398 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001399 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001400 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001401 if (ObjectPtrConversions.size() == 1) {
1402 // We have a single conversion to a pointer-to-object type. Perform
1403 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001404 // TODO: don't redo the conversion calculation.
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001405 Operand.release();
John McCallda4458e2010-03-31 01:36:47 +00001406 if (!PerformImplicitConversion(Ex,
1407 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001408 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001409 Operand = Owned(Ex);
1410 Type = Ex->getType();
1411 }
1412 }
1413 else if (ObjectPtrConversions.size() > 1) {
1414 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1415 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001416 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1417 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001418 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001419 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001420 }
1421
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001422 if (!Type->isPointerType())
1423 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1424 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001425
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001426 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001427 if (Pointee->isVoidType() && !isSFINAEContext()) {
1428 // The C++ standard bans deleting a pointer to a non-object type, which
1429 // effectively bans deletion of "void*". However, most compilers support
1430 // this, so we treat it as a warning unless we're in a SFINAE context.
1431 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1432 << Type << Ex->getSourceRange();
1433 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001434 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1435 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001436 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001437 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001438 PDiag(diag::warn_delete_incomplete)
1439 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001440 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001441
Douglas Gregor98496dc2009-09-29 21:38:53 +00001442 // C++ [expr.delete]p2:
1443 // [Note: a pointer to a const type can be the operand of a
1444 // delete-expression; it is not necessary to cast away the constness
1445 // (5.2.11) of the pointer expression before it is used as the operand
1446 // of the delete-expression. ]
1447 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1448 CastExpr::CK_NoOp);
1449
1450 // Update the operand.
1451 Operand.take();
1452 Operand = ExprArg(*this, Ex);
1453
Anders Carlssona471db02009-08-16 20:29:29 +00001454 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1455 ArrayForm ? OO_Array_Delete : OO_Delete);
1456
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001457 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1458 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1459
1460 if (!UseGlobal &&
1461 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001462 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001463
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001464 if (!RD->hasTrivialDestructor())
1465 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001466 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001467 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001468 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001469
Anders Carlssona471db02009-08-16 20:29:29 +00001470 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001471 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001472 DeclareGlobalNewDelete();
1473 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001474 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001475 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001476 OperatorDelete))
1477 return ExprError();
1478 }
Mike Stump11289f42009-09-09 15:08:12 +00001479
John McCall0f55a032010-04-20 02:18:25 +00001480 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1481
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001482 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001483 }
1484
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001485 Operand.release();
1486 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001487 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001488}
1489
Douglas Gregor633caca2009-11-23 23:44:04 +00001490/// \brief Check the use of the given variable as a C++ condition in an if,
1491/// while, do-while, or switch statement.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001492Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1493 SourceLocation StmtLoc,
1494 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001495 QualType T = ConditionVar->getType();
1496
1497 // C++ [stmt.select]p2:
1498 // The declarator shall not specify a function or an array.
1499 if (T->isFunctionType())
1500 return ExprError(Diag(ConditionVar->getLocation(),
1501 diag::err_invalid_use_of_function_type)
1502 << ConditionVar->getSourceRange());
1503 else if (T->isArrayType())
1504 return ExprError(Diag(ConditionVar->getLocation(),
1505 diag::err_invalid_use_of_array_type)
1506 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001507
Douglas Gregore60e41a2010-05-06 17:25:47 +00001508 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1509 ConditionVar->getLocation(),
1510 ConditionVar->getType().getNonReferenceType());
1511 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1512 Condition->Destroy(Context);
1513 return ExprError();
1514 }
1515
1516 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001517}
1518
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001519/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1520bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1521 // C++ 6.4p4:
1522 // The value of a condition that is an initialized declaration in a statement
1523 // other than a switch statement is the value of the declared variable
1524 // implicitly converted to type bool. If that conversion is ill-formed, the
1525 // program is ill-formed.
1526 // The value of a condition that is an expression is the value of the
1527 // expression, implicitly converted to bool.
1528 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001529 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001530}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001531
1532/// Helper function to determine whether this is the (deprecated) C++
1533/// conversion from a string literal to a pointer to non-const char or
1534/// non-const wchar_t (for narrow and wide string literals,
1535/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001536bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001537Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1538 // Look inside the implicit cast, if it exists.
1539 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1540 From = Cast->getSubExpr();
1541
1542 // A string literal (2.13.4) that is not a wide string literal can
1543 // be converted to an rvalue of type "pointer to char"; a wide
1544 // string literal can be converted to an rvalue of type "pointer
1545 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001546 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001547 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001548 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001549 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001550 // This conversion is considered only when there is an
1551 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001552 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001553 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1554 (!StrLit->isWide() &&
1555 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1556 ToPointeeType->getKind() == BuiltinType::Char_S))))
1557 return true;
1558 }
1559
1560 return false;
1561}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001562
Douglas Gregora4253922010-04-16 22:17:36 +00001563static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1564 SourceLocation CastLoc,
1565 QualType Ty,
1566 CastExpr::CastKind Kind,
1567 CXXMethodDecl *Method,
1568 Sema::ExprArg Arg) {
1569 Expr *From = Arg.takeAs<Expr>();
1570
1571 switch (Kind) {
1572 default: assert(0 && "Unhandled cast kind!");
1573 case CastExpr::CK_ConstructorConversion: {
1574 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1575
1576 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1577 Sema::MultiExprArg(S, (void **)&From, 1),
1578 CastLoc, ConstructorArgs))
1579 return S.ExprError();
1580
1581 Sema::OwningExprResult Result =
1582 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1583 move_arg(ConstructorArgs));
1584 if (Result.isInvalid())
1585 return S.ExprError();
1586
1587 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1588 }
1589
1590 case CastExpr::CK_UserDefinedConversion: {
1591 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1592
1593 // Create an implicit call expr that calls it.
1594 // FIXME: pass the FoundDecl for the user-defined conversion here
1595 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1596 return S.MaybeBindToTemporary(CE);
1597 }
1598 }
1599}
1600
Douglas Gregor5fb53972009-01-14 15:45:31 +00001601/// PerformImplicitConversion - Perform an implicit conversion of the
1602/// expression From to the type ToType using the pre-computed implicit
1603/// conversion sequence ICS. Returns true if there was an error, false
1604/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001605/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001606/// used in the error message.
1607bool
1608Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1609 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001610 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001611 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001612 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001613 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001614 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001615 return true;
1616 break;
1617
Anders Carlsson110b07b2009-09-15 06:28:28 +00001618 case ImplicitConversionSequence::UserDefinedConversion: {
1619
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001620 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1621 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001622 QualType BeforeToType;
1623 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001624 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001625
1626 // If the user-defined conversion is specified by a conversion function,
1627 // the initial standard conversion sequence converts the source type to
1628 // the implicit object parameter of the conversion function.
1629 BeforeToType = Context.getTagDeclType(Conv->getParent());
1630 } else if (const CXXConstructorDecl *Ctor =
1631 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001632 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001633 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001634 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001635 // If the user-defined conversion is specified by a constructor, the
1636 // initial standard conversion sequence converts the source type to the
1637 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001638 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1639 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001640 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001641 else
1642 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001643 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001644 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001645 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001646 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001647 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001648 return true;
1649 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001650
Anders Carlssone9766d52009-09-09 21:33:21 +00001651 OwningExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001652 = BuildCXXCastArgument(*this,
1653 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001654 ToType.getNonReferenceType(),
1655 CastKind, cast<CXXMethodDecl>(FD),
1656 Owned(From));
1657
1658 if (CastArg.isInvalid())
1659 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001660
1661 From = CastArg.takeAs<Expr>();
1662
Eli Friedmane96f1d32009-11-27 04:41:50 +00001663 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001664 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001665 }
John McCall0d1da222010-01-12 00:44:57 +00001666
1667 case ImplicitConversionSequence::AmbiguousConversion:
1668 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1669 PDiag(diag::err_typecheck_ambiguous_condition)
1670 << From->getSourceRange());
1671 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001672
Douglas Gregor39c16d42008-10-24 04:54:22 +00001673 case ImplicitConversionSequence::EllipsisConversion:
1674 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001675 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001676
1677 case ImplicitConversionSequence::BadConversion:
1678 return true;
1679 }
1680
1681 // Everything went well.
1682 return false;
1683}
1684
1685/// PerformImplicitConversion - Perform an implicit conversion of the
1686/// expression From to the type ToType by following the standard
1687/// conversion sequence SCS. Returns true if there was an error, false
1688/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001689/// expression. Flavor is the context in which we're performing this
1690/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001691bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001692Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001693 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001694 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001695 // Overall FIXME: we are recomputing too many types here and doing far too
1696 // much extra work. What this means is that we need to keep track of more
1697 // information that is computed when we try the implicit conversion initially,
1698 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001699 QualType FromType = From->getType();
1700
Douglas Gregor2fe98832008-11-03 19:09:14 +00001701 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001702 // FIXME: When can ToType be a reference type?
1703 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001704 if (SCS.Second == ICK_Derived_To_Base) {
1705 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1706 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1707 MultiExprArg(*this, (void **)&From, 1),
1708 /*FIXME:ConstructLoc*/SourceLocation(),
1709 ConstructorArgs))
1710 return true;
1711 OwningExprResult FromResult =
1712 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1713 ToType, SCS.CopyConstructor,
1714 move_arg(ConstructorArgs));
1715 if (FromResult.isInvalid())
1716 return true;
1717 From = FromResult.takeAs<Expr>();
1718 return false;
1719 }
Mike Stump11289f42009-09-09 15:08:12 +00001720 OwningExprResult FromResult =
1721 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1722 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001723 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001724
Anders Carlsson6eb55572009-08-25 05:12:04 +00001725 if (FromResult.isInvalid())
1726 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001727
Anders Carlsson6eb55572009-08-25 05:12:04 +00001728 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001729 return false;
1730 }
1731
Douglas Gregor980fb162010-04-29 18:24:40 +00001732 // Resolve overloaded function references.
1733 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1734 DeclAccessPair Found;
1735 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1736 true, Found);
1737 if (!Fn)
1738 return true;
1739
1740 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1741 return true;
1742
1743 From = FixOverloadedFunctionReference(From, Found, Fn);
1744 FromType = From->getType();
1745 }
1746
Douglas Gregor39c16d42008-10-24 04:54:22 +00001747 // Perform the first implicit conversion.
1748 switch (SCS.First) {
1749 case ICK_Identity:
1750 case ICK_Lvalue_To_Rvalue:
1751 // Nothing to do.
1752 break;
1753
1754 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001755 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001756 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001757 break;
1758
1759 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001760 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001761 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001762 break;
1763
1764 default:
1765 assert(false && "Improper first standard conversion");
1766 break;
1767 }
1768
1769 // Perform the second implicit conversion
1770 switch (SCS.Second) {
1771 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001772 // If both sides are functions (or pointers/references to them), there could
1773 // be incompatible exception declarations.
1774 if (CheckExceptionSpecCompatibility(From, ToType))
1775 return true;
1776 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001777 break;
1778
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001779 case ICK_NoReturn_Adjustment:
1780 // If both sides are functions (or pointers/references to them), there could
1781 // be incompatible exception declarations.
1782 if (CheckExceptionSpecCompatibility(From, ToType))
1783 return true;
1784
1785 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1786 CastExpr::CK_NoOp);
1787 break;
1788
Douglas Gregor39c16d42008-10-24 04:54:22 +00001789 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001790 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001791 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1792 break;
1793
1794 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001795 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001796 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1797 break;
1798
1799 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001800 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001801 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1802 break;
1803
Douglas Gregor39c16d42008-10-24 04:54:22 +00001804 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00001805 if (ToType->isRealFloatingType())
Eli Friedman06ed2a52009-10-20 08:27:19 +00001806 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1807 else
1808 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1809 break;
1810
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001811 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001812 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001813 break;
1814
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001815 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001816 if (SCS.IncompatibleObjC) {
1817 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001818 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001819 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001820 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001821 << From->getSourceRange();
1822 }
1823
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001824
1825 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssona70cff62010-04-24 19:06:50 +00001826 CXXBaseSpecifierArray BasePath;
1827 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001828 return true;
Anders Carlssona70cff62010-04-24 19:06:50 +00001829 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001830 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001831 }
1832
1833 case ICK_Pointer_Member: {
1834 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001835 CXXBaseSpecifierArray BasePath;
1836 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1837 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001838 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001839 if (CheckExceptionSpecCompatibility(From, ToType))
1840 return true;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001841 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001842 break;
1843 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001844 case ICK_Boolean_Conversion: {
1845 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1846 if (FromType->isMemberPointerType())
1847 Kind = CastExpr::CK_MemberPointerToBoolean;
1848
1849 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001850 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001851 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001852
Douglas Gregor88d292c2010-05-13 16:44:06 +00001853 case ICK_Derived_To_Base: {
1854 CXXBaseSpecifierArray BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001855 if (CheckDerivedToBaseConversion(From->getType(),
1856 ToType.getNonReferenceType(),
1857 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001858 From->getSourceRange(),
1859 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001860 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001861 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001862
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001863 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001864 CastExpr::CK_DerivedToBase,
1865 /*isLvalue=*/(From->getType()->isRecordType() &&
1866 From->isLvalue(Context) == Expr::LV_Valid),
1867 BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001868 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001869 }
1870
Douglas Gregor46188682010-05-18 22:42:18 +00001871 case ICK_Vector_Conversion:
1872 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1873 break;
1874
1875 case ICK_Vector_Splat:
1876 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1877 break;
1878
1879 case ICK_Complex_Real:
1880 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1881 break;
1882
1883 case ICK_Lvalue_To_Rvalue:
1884 case ICK_Array_To_Pointer:
1885 case ICK_Function_To_Pointer:
1886 case ICK_Qualification:
1887 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001888 assert(false && "Improper second standard conversion");
1889 break;
1890 }
1891
1892 switch (SCS.Third) {
1893 case ICK_Identity:
1894 // Nothing to do.
1895 break;
1896
1897 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001898 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1899 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001900 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00001901 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregore489a7d2010-02-28 18:30:25 +00001902
1903 if (SCS.DeprecatedStringLiteralToCharPtr)
1904 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1905 << ToType.getNonReferenceType();
1906
Douglas Gregor39c16d42008-10-24 04:54:22 +00001907 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001908
Douglas Gregor39c16d42008-10-24 04:54:22 +00001909 default:
Douglas Gregor46188682010-05-18 22:42:18 +00001910 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00001911 break;
1912 }
1913
1914 return false;
1915}
1916
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001917Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1918 SourceLocation KWLoc,
1919 SourceLocation LParen,
1920 TypeTy *Ty,
1921 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001922 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001924 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1925 // all traits except __is_class, __is_enum and __is_union require a the type
1926 // to be complete.
1927 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001928 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001929 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001930 return ExprError();
1931 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001932
1933 // There is no point in eagerly computing the value. The traits are designed
1934 // to be used from type trait templates, so Ty will be a template parameter
1935 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001936 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1937 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001938}
Sebastian Redl5822f082009-02-07 20:10:22 +00001939
1940QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001941 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001942 const char *OpSpelling = isIndirect ? "->*" : ".*";
1943 // C++ 5.5p2
1944 // The binary operator .* [p3: ->*] binds its second operand, which shall
1945 // be of type "pointer to member of T" (where T is a completely-defined
1946 // class type) [...]
1947 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001948 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001949 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001950 Diag(Loc, diag::err_bad_memptr_rhs)
1951 << OpSpelling << RType << rex->getSourceRange();
1952 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001953 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001954
Sebastian Redl5822f082009-02-07 20:10:22 +00001955 QualType Class(MemPtr->getClass(), 0);
1956
Sebastian Redlc72350e2010-04-10 10:14:54 +00001957 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1958 return QualType();
1959
Sebastian Redl5822f082009-02-07 20:10:22 +00001960 // C++ 5.5p2
1961 // [...] to its first operand, which shall be of class T or of a class of
1962 // which T is an unambiguous and accessible base class. [p3: a pointer to
1963 // such a class]
1964 QualType LType = lex->getType();
1965 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001966 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001967 LType = Ptr->getPointeeType().getNonReferenceType();
1968 else {
1969 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001970 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001971 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001972 return QualType();
1973 }
1974 }
1975
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001976 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00001977 // If we want to check the hierarchy, we need a complete type.
1978 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1979 << OpSpelling << (int)isIndirect)) {
1980 return QualType();
1981 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001982 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001983 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001984 // FIXME: Would it be useful to print full ambiguity paths, or is that
1985 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001986 if (!IsDerivedFrom(LType, Class, Paths) ||
1987 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1988 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001989 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001990 return QualType();
1991 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001992 // Cast LHS to type of use.
1993 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1994 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlssona70cff62010-04-24 19:06:50 +00001995
1996 CXXBaseSpecifierArray BasePath;
1997 BuildBasePathArray(Paths, BasePath);
1998 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1999 BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00002000 }
2001
Fariborz Jahanianfff3fb22009-11-18 22:16:17 +00002002 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00002003 // Diagnose use of pointer-to-member type which when used as
2004 // the functional cast in a pointer-to-member expression.
2005 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2006 return QualType();
2007 }
Sebastian Redl5822f082009-02-07 20:10:22 +00002008 // C++ 5.5p2
2009 // The result is an object or a function of the type specified by the
2010 // second operand.
2011 // The cv qualifiers are the union of those in the pointer and the left side,
2012 // in accordance with 5.5p5 and 5.2.5.
2013 // FIXME: This returns a dereferenced member function pointer as a normal
2014 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00002015 // calling them. There's also a GCC extension to get a function pointer to the
2016 // thing, which is another complication, because this type - unlike the type
2017 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00002018 // argument.
2019 // We probably need a "MemberFunctionClosureType" or something like that.
2020 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002021 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00002022 return Result;
2023}
Sebastian Redl1a99f442009-04-16 17:51:27 +00002024
Sebastian Redl1a99f442009-04-16 17:51:27 +00002025/// \brief Try to convert a type to another according to C++0x 5.16p3.
2026///
2027/// This is part of the parameter validation for the ? operator. If either
2028/// value operand is a class type, the two operands are attempted to be
2029/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002030/// It returns true if the program is ill-formed and has already been diagnosed
2031/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002032static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2033 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002034 bool &HaveConversion,
2035 QualType &ToType) {
2036 HaveConversion = false;
2037 ToType = To->getType();
2038
2039 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2040 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002041 // C++0x 5.16p3
2042 // The process for determining whether an operand expression E1 of type T1
2043 // can be converted to match an operand expression E2 of type T2 is defined
2044 // as follows:
2045 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00002046 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2047 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002048 // E1 can be converted to match E2 if E1 can be implicitly converted to
2049 // type "lvalue reference to T2", subject to the constraint that in the
2050 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002051 QualType T = Self.Context.getLValueReferenceType(ToType);
2052 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2053
2054 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2055 if (InitSeq.isDirectReferenceBinding()) {
2056 ToType = T;
2057 HaveConversion = true;
2058 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002059 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002060
2061 if (InitSeq.isAmbiguous())
2062 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002063 }
John McCall65eb8792010-02-25 01:37:24 +00002064
Sebastian Redl1a99f442009-04-16 17:51:27 +00002065 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2066 // -- if E1 and E2 have class type, and the underlying class types are
2067 // the same or one is a base class of the other:
2068 QualType FTy = From->getType();
2069 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002070 const RecordType *FRec = FTy->getAs<RecordType>();
2071 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002072 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2073 Self.IsDerivedFrom(FTy, TTy);
2074 if (FRec && TRec &&
2075 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002076 // E1 can be converted to match E2 if the class of T2 is the
2077 // same type as, or a base class of, the class of T1, and
2078 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002079 if (FRec == TRec || FDerivedFromT) {
2080 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002081 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2082 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2083 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2084 HaveConversion = true;
2085 return false;
2086 }
2087
2088 if (InitSeq.isAmbiguous())
2089 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2090 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002091 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002092
2093 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002094 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002095
2096 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2097 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002098 // if E2 were converted to an rvalue (or the type it has, if E2 is
2099 // an rvalue).
2100 //
2101 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2102 // to the array-to-pointer or function-to-pointer conversions.
2103 if (!TTy->getAs<TagType>())
2104 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002105
2106 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2107 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2108 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2109 ToType = TTy;
2110 if (InitSeq.isAmbiguous())
2111 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2112
Sebastian Redl1a99f442009-04-16 17:51:27 +00002113 return false;
2114}
2115
2116/// \brief Try to find a common type for two according to C++0x 5.16p5.
2117///
2118/// This is part of the parameter validation for the ? operator. If either
2119/// value operand is a class type, overload resolution is used to find a
2120/// conversion to a common type.
2121static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2122 SourceLocation Loc) {
2123 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002124 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002125 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002126
2127 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002128 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002129 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002130 // We found a match. Perform the conversions on the arguments and move on.
2131 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002132 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002133 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002134 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002135 break;
2136 return false;
2137
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002138 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002139 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2140 << LHS->getType() << RHS->getType()
2141 << LHS->getSourceRange() << RHS->getSourceRange();
2142 return true;
2143
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002144 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002145 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2146 << LHS->getType() << RHS->getType()
2147 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002148 // FIXME: Print the possible common types by printing the return types of
2149 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002150 break;
2151
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002152 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002153 assert(false && "Conditional operator has only built-in overloads");
2154 break;
2155 }
2156 return true;
2157}
2158
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002159/// \brief Perform an "extended" implicit conversion as returned by
2160/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002161static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2162 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2163 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2164 SourceLocation());
2165 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2166 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2167 Sema::MultiExprArg(Self, (void **)&E, 1));
2168 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002169 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002170
2171 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002172 return false;
2173}
2174
Sebastian Redl1a99f442009-04-16 17:51:27 +00002175/// \brief Check the operands of ?: under C++ semantics.
2176///
2177/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2178/// extension. In this case, LHS == Cond. (But they're not aliases.)
2179QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2180 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002181 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2182 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002183
2184 // C++0x 5.16p1
2185 // The first expression is contextually converted to bool.
2186 if (!Cond->isTypeDependent()) {
2187 if (CheckCXXBooleanCondition(Cond))
2188 return QualType();
2189 }
2190
2191 // Either of the arguments dependent?
2192 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2193 return Context.DependentTy;
2194
2195 // C++0x 5.16p2
2196 // If either the second or the third operand has type (cv) void, ...
2197 QualType LTy = LHS->getType();
2198 QualType RTy = RHS->getType();
2199 bool LVoid = LTy->isVoidType();
2200 bool RVoid = RTy->isVoidType();
2201 if (LVoid || RVoid) {
2202 // ... then the [l2r] conversions are performed on the second and third
2203 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002204 DefaultFunctionArrayLvalueConversion(LHS);
2205 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002206 LTy = LHS->getType();
2207 RTy = RHS->getType();
2208
2209 // ... and one of the following shall hold:
2210 // -- The second or the third operand (but not both) is a throw-
2211 // expression; the result is of the type of the other and is an rvalue.
2212 bool LThrow = isa<CXXThrowExpr>(LHS);
2213 bool RThrow = isa<CXXThrowExpr>(RHS);
2214 if (LThrow && !RThrow)
2215 return RTy;
2216 if (RThrow && !LThrow)
2217 return LTy;
2218
2219 // -- Both the second and third operands have type void; the result is of
2220 // type void and is an rvalue.
2221 if (LVoid && RVoid)
2222 return Context.VoidTy;
2223
2224 // Neither holds, error.
2225 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2226 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2227 << LHS->getSourceRange() << RHS->getSourceRange();
2228 return QualType();
2229 }
2230
2231 // Neither is void.
2232
2233 // C++0x 5.16p3
2234 // Otherwise, if the second and third operand have different types, and
2235 // either has (cv) class type, and attempt is made to convert each of those
2236 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002237 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002238 (LTy->isRecordType() || RTy->isRecordType())) {
2239 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2240 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002241 QualType L2RType, R2LType;
2242 bool HaveL2R, HaveR2L;
2243 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002244 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002245 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002246 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002247
Sebastian Redl1a99f442009-04-16 17:51:27 +00002248 // If both can be converted, [...] the program is ill-formed.
2249 if (HaveL2R && HaveR2L) {
2250 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2251 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2252 return QualType();
2253 }
2254
2255 // If exactly one conversion is possible, that conversion is applied to
2256 // the chosen operand and the converted operands are used in place of the
2257 // original operands for the remainder of this section.
2258 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002259 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002260 return QualType();
2261 LTy = LHS->getType();
2262 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002263 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002264 return QualType();
2265 RTy = RHS->getType();
2266 }
2267 }
2268
2269 // C++0x 5.16p4
2270 // If the second and third operands are lvalues and have the same type,
2271 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002272 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002273 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2274 RHS->isLvalue(Context) == Expr::LV_Valid)
2275 return LTy;
2276
2277 // C++0x 5.16p5
2278 // Otherwise, the result is an rvalue. If the second and third operands
2279 // do not have the same type, and either has (cv) class type, ...
2280 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2281 // ... overload resolution is used to determine the conversions (if any)
2282 // to be applied to the operands. If the overload resolution fails, the
2283 // program is ill-formed.
2284 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2285 return QualType();
2286 }
2287
2288 // C++0x 5.16p6
2289 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2290 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002291 DefaultFunctionArrayLvalueConversion(LHS);
2292 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002293 LTy = LHS->getType();
2294 RTy = RHS->getType();
2295
2296 // After those conversions, one of the following shall hold:
2297 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002298 // is of that type. If the operands have class type, the result
2299 // is a prvalue temporary of the result type, which is
2300 // copy-initialized from either the second operand or the third
2301 // operand depending on the value of the first operand.
2302 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2303 if (LTy->isRecordType()) {
2304 // The operands have class type. Make a temporary copy.
2305 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2306 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2307 SourceLocation(),
2308 Owned(LHS));
2309 if (LHSCopy.isInvalid())
2310 return QualType();
2311
2312 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2313 SourceLocation(),
2314 Owned(RHS));
2315 if (RHSCopy.isInvalid())
2316 return QualType();
2317
2318 LHS = LHSCopy.takeAs<Expr>();
2319 RHS = RHSCopy.takeAs<Expr>();
2320 }
2321
Sebastian Redl1a99f442009-04-16 17:51:27 +00002322 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002323 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002324
Douglas Gregor46188682010-05-18 22:42:18 +00002325 // Extension: conditional operator involving vector types.
2326 if (LTy->isVectorType() || RTy->isVectorType())
2327 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2328
Sebastian Redl1a99f442009-04-16 17:51:27 +00002329 // -- The second and third operands have arithmetic or enumeration type;
2330 // the usual arithmetic conversions are performed to bring them to a
2331 // common type, and the result is of that type.
2332 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2333 UsualArithmeticConversions(LHS, RHS);
2334 return LHS->getType();
2335 }
2336
2337 // -- The second and third operands have pointer type, or one has pointer
2338 // type and the other is a null pointer constant; pointer conversions
2339 // and qualification conversions are performed to bring them to their
2340 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002341 // -- The second and third operands have pointer to member type, or one has
2342 // pointer to member type and the other is a null pointer constant;
2343 // pointer to member conversions and qualification conversions are
2344 // performed to bring them to a common type, whose cv-qualification
2345 // shall match the cv-qualification of either the second or the third
2346 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002347 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002348 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002349 isSFINAEContext()? 0 : &NonStandardCompositeType);
2350 if (!Composite.isNull()) {
2351 if (NonStandardCompositeType)
2352 Diag(QuestionLoc,
2353 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2354 << LTy << RTy << Composite
2355 << LHS->getSourceRange() << RHS->getSourceRange();
2356
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002357 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002358 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002359
Douglas Gregor697a3912010-04-01 22:47:07 +00002360 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002361 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2362 if (!Composite.isNull())
2363 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002364
Sebastian Redl1a99f442009-04-16 17:51:27 +00002365 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2366 << LHS->getType() << RHS->getType()
2367 << LHS->getSourceRange() << RHS->getSourceRange();
2368 return QualType();
2369}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002370
2371/// \brief Find a merged pointer type and convert the two expressions to it.
2372///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002373/// This finds the composite pointer type (or member pointer type) for @p E1
2374/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2375/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002376/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002377///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002378/// \param Loc The location of the operator requiring these two expressions to
2379/// be converted to the composite pointer type.
2380///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002381/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2382/// a non-standard (but still sane) composite type to which both expressions
2383/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2384/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002385QualType Sema::FindCompositePointerType(SourceLocation Loc,
2386 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002387 bool *NonStandardCompositeType) {
2388 if (NonStandardCompositeType)
2389 *NonStandardCompositeType = false;
2390
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002391 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2392 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002393
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002394 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2395 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002396 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002397
2398 // C++0x 5.9p2
2399 // Pointer conversions and qualification conversions are performed on
2400 // pointer operands to bring them to their composite pointer type. If
2401 // one operand is a null pointer constant, the composite pointer type is
2402 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002403 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002404 if (T2->isMemberPointerType())
2405 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2406 else
2407 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002408 return T2;
2409 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002410 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002411 if (T1->isMemberPointerType())
2412 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2413 else
2414 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002415 return T1;
2416 }
Mike Stump11289f42009-09-09 15:08:12 +00002417
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002418 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002419 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2420 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002421 return QualType();
2422
2423 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2424 // the other has type "pointer to cv2 T" and the composite pointer type is
2425 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2426 // Otherwise, the composite pointer type is a pointer type similar to the
2427 // type of one of the operands, with a cv-qualification signature that is
2428 // the union of the cv-qualification signatures of the operand types.
2429 // In practice, the first part here is redundant; it's subsumed by the second.
2430 // What we do here is, we build the two possible composite types, and try the
2431 // conversions in both directions. If only one works, or if the two composite
2432 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002433 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002434 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2435 QualifierVector QualifierUnion;
2436 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2437 ContainingClassVector;
2438 ContainingClassVector MemberOfClass;
2439 QualType Composite1 = Context.getCanonicalType(T1),
2440 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002441 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002442 do {
2443 const PointerType *Ptr1, *Ptr2;
2444 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2445 (Ptr2 = Composite2->getAs<PointerType>())) {
2446 Composite1 = Ptr1->getPointeeType();
2447 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002448
2449 // If we're allowed to create a non-standard composite type, keep track
2450 // of where we need to fill in additional 'const' qualifiers.
2451 if (NonStandardCompositeType &&
2452 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2453 NeedConstBefore = QualifierUnion.size();
2454
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002455 QualifierUnion.push_back(
2456 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2457 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2458 continue;
2459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002461 const MemberPointerType *MemPtr1, *MemPtr2;
2462 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2463 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2464 Composite1 = MemPtr1->getPointeeType();
2465 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002466
2467 // If we're allowed to create a non-standard composite type, keep track
2468 // of where we need to fill in additional 'const' qualifiers.
2469 if (NonStandardCompositeType &&
2470 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2471 NeedConstBefore = QualifierUnion.size();
2472
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002473 QualifierUnion.push_back(
2474 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2475 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2476 MemPtr2->getClass()));
2477 continue;
2478 }
Mike Stump11289f42009-09-09 15:08:12 +00002479
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002480 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002481
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002482 // Cannot unwrap any more types.
2483 break;
2484 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002485
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002486 if (NeedConstBefore && NonStandardCompositeType) {
2487 // Extension: Add 'const' to qualifiers that come before the first qualifier
2488 // mismatch, so that our (non-standard!) composite type meets the
2489 // requirements of C++ [conv.qual]p4 bullet 3.
2490 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2491 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2492 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2493 *NonStandardCompositeType = true;
2494 }
2495 }
2496 }
2497
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002498 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002499 ContainingClassVector::reverse_iterator MOC
2500 = MemberOfClass.rbegin();
2501 for (QualifierVector::reverse_iterator
2502 I = QualifierUnion.rbegin(),
2503 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002504 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002505 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002506 if (MOC->first && MOC->second) {
2507 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002508 Composite1 = Context.getMemberPointerType(
2509 Context.getQualifiedType(Composite1, Quals),
2510 MOC->first);
2511 Composite2 = Context.getMemberPointerType(
2512 Context.getQualifiedType(Composite2, Quals),
2513 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002514 } else {
2515 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002516 Composite1
2517 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2518 Composite2
2519 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002520 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002521 }
2522
Douglas Gregor19175ff2010-04-16 23:20:25 +00002523 // Try to convert to the first composite pointer type.
2524 InitializedEntity Entity1
2525 = InitializedEntity::InitializeTemporary(Composite1);
2526 InitializationKind Kind
2527 = InitializationKind::CreateCopy(Loc, SourceLocation());
2528 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2529 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00002530
Douglas Gregor19175ff2010-04-16 23:20:25 +00002531 if (E1ToC1 && E2ToC1) {
2532 // Conversion to Composite1 is viable.
2533 if (!Context.hasSameType(Composite1, Composite2)) {
2534 // Composite2 is a different type from Composite1. Check whether
2535 // Composite2 is also viable.
2536 InitializedEntity Entity2
2537 = InitializedEntity::InitializeTemporary(Composite2);
2538 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2539 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2540 if (E1ToC2 && E2ToC2) {
2541 // Both Composite1 and Composite2 are viable and are different;
2542 // this is an ambiguity.
2543 return QualType();
2544 }
2545 }
2546
2547 // Convert E1 to Composite1
2548 OwningExprResult E1Result
2549 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2550 if (E1Result.isInvalid())
2551 return QualType();
2552 E1 = E1Result.takeAs<Expr>();
2553
2554 // Convert E2 to Composite1
2555 OwningExprResult E2Result
2556 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2557 if (E2Result.isInvalid())
2558 return QualType();
2559 E2 = E2Result.takeAs<Expr>();
2560
2561 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002562 }
2563
Douglas Gregor19175ff2010-04-16 23:20:25 +00002564 // Check whether Composite2 is viable.
2565 InitializedEntity Entity2
2566 = InitializedEntity::InitializeTemporary(Composite2);
2567 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2568 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2569 if (!E1ToC2 || !E2ToC2)
2570 return QualType();
2571
2572 // Convert E1 to Composite2
2573 OwningExprResult E1Result
2574 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2575 if (E1Result.isInvalid())
2576 return QualType();
2577 E1 = E1Result.takeAs<Expr>();
2578
2579 // Convert E2 to Composite2
2580 OwningExprResult E2Result
2581 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2582 if (E2Result.isInvalid())
2583 return QualType();
2584 E2 = E2Result.takeAs<Expr>();
2585
2586 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002587}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002588
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002589Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002590 if (!Context.getLangOptions().CPlusPlus)
2591 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002592
Douglas Gregor363b1512009-12-24 18:51:59 +00002593 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2594
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002595 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002596 if (!RT)
2597 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002598
John McCall67da35c2010-02-04 22:26:26 +00002599 // If this is the result of a call expression, our source might
2600 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002601 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2602 QualType Ty = CE->getCallee()->getType();
2603 if (const PointerType *PT = Ty->getAs<PointerType>())
2604 Ty = PT->getPointeeType();
Fariborz Jahanianffcfecd2010-02-18 20:31:02 +00002605 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2606 Ty = BPT->getPointeeType();
2607
John McCall9dd450b2009-09-21 23:43:11 +00002608 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002609 if (FTy->getResultType()->isReferenceType())
2610 return Owned(E);
2611 }
Fariborz Jahanian1d446082010-06-16 18:56:04 +00002612 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2613 QualType Ty = ME->getType();
2614 if (const PointerType *PT = Ty->getAs<PointerType>())
2615 Ty = PT->getPointeeType();
2616 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2617 Ty = BPT->getPointeeType();
2618 if (Ty->isReferenceType())
2619 return Owned(E);
2620 }
2621
John McCall67da35c2010-02-04 22:26:26 +00002622
2623 // That should be enough to guarantee that this type is complete.
2624 // If it has a trivial destructor, we can avoid the extra copy.
2625 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2626 if (RD->hasTrivialDestructor())
2627 return Owned(E);
2628
Mike Stump11289f42009-09-09 15:08:12 +00002629 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002630 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002631 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002632 if (CXXDestructorDecl *Destructor =
John McCall8e36d532010-04-07 00:41:46 +00002633 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002634 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002635 CheckDestructorAccess(E->getExprLoc(), Destructor,
2636 PDiag(diag::err_access_dtor_temp)
2637 << E->getType());
2638 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002639 // FIXME: Add the temporary to the temporaries vector.
2640 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2641}
2642
Anders Carlsson6e997b22009-12-15 20:51:39 +00002643Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002644 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002645
John McCallcc7e5bf2010-05-06 08:58:33 +00002646 // Check any implicit conversions within the expression.
2647 CheckImplicitConversions(SubExpr);
2648
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002649 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2650 assert(ExprTemporaries.size() >= FirstTemporary);
2651 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002652 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002653
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002654 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002655 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002656 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002657 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2658 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002659
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002660 return E;
2661}
2662
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002663Sema::OwningExprResult
2664Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2665 if (SubExpr.isInvalid())
2666 return ExprError();
2667
2668 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2669}
2670
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002671FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2672 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2673 assert(ExprTemporaries.size() >= FirstTemporary);
2674
2675 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2676 CXXTemporary **Temporaries =
2677 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2678
2679 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2680
2681 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2682 ExprTemporaries.end());
2683
2684 return E;
2685}
2686
Mike Stump11289f42009-09-09 15:08:12 +00002687Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002688Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002689 tok::TokenKind OpKind, TypeTy *&ObjectType,
2690 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002691 // Since this might be a postfix expression, get rid of ParenListExprs.
2692 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002693
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002694 Expr *BaseExpr = (Expr*)Base.get();
2695 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002696
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002697 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002698 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002699 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002700 // If we have a pointer to a dependent type and are using the -> operator,
2701 // the object type is the type that the pointer points to. We might still
2702 // have enough information about that type to do something useful.
2703 if (OpKind == tok::arrow)
2704 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2705 BaseType = Ptr->getPointeeType();
2706
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002707 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002708 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002709 return move(Base);
2710 }
Mike Stump11289f42009-09-09 15:08:12 +00002711
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002712 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002713 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002714 // returned, with the original second operand.
2715 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002716 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002717 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002718 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002719 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002720
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002721 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002722 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002723 BaseExpr = (Expr*)Base.get();
2724 if (BaseExpr == NULL)
2725 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002726 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002727 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002728 BaseType = BaseExpr->getType();
2729 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002730 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002731 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002732 for (unsigned i = 0; i < Locations.size(); i++)
2733 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002734 return ExprError();
2735 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002736 }
Mike Stump11289f42009-09-09 15:08:12 +00002737
Douglas Gregore4f764f2009-11-20 19:58:21 +00002738 if (BaseType->isPointerType())
2739 BaseType = BaseType->getPointeeType();
2740 }
Mike Stump11289f42009-09-09 15:08:12 +00002741
2742 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002743 // vector types or Objective-C interfaces. Just return early and let
2744 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002745 if (!BaseType->isRecordType()) {
2746 // C++ [basic.lookup.classref]p2:
2747 // [...] If the type of the object expression is of pointer to scalar
2748 // type, the unqualified-id is looked up in the context of the complete
2749 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002750 //
2751 // This also indicates that we should be parsing a
2752 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002753 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002754 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002755 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002756 }
Mike Stump11289f42009-09-09 15:08:12 +00002757
Douglas Gregor3fad6172009-11-17 05:17:33 +00002758 // The object type must be complete (or dependent).
2759 if (!BaseType->isDependentType() &&
2760 RequireCompleteType(OpLoc, BaseType,
2761 PDiag(diag::err_incomplete_member_access)))
2762 return ExprError();
2763
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002764 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002765 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002766 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002767 // type C (or of pointer to a class type C), the unqualified-id is looked
2768 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002769 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002770 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002771}
2772
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002773Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2774 ExprArg MemExpr) {
2775 Expr *E = (Expr *) MemExpr.get();
2776 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2777 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2778 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregora771f462010-03-31 17:46:05 +00002779 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002780
2781 return ActOnCallExpr(/*Scope*/ 0,
2782 move(MemExpr),
2783 /*LPLoc*/ ExpectedLParenLoc,
2784 Sema::MultiExprArg(*this, 0, 0),
2785 /*CommaLocs*/ 0,
2786 /*RPLoc*/ ExpectedLParenLoc);
2787}
Douglas Gregore610ada2010-02-24 18:44:31 +00002788
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002789Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2790 SourceLocation OpLoc,
2791 tok::TokenKind OpKind,
2792 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002793 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002794 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002795 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002796 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002797 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002798 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002799
2800 // C++ [expr.pseudo]p2:
2801 // The left-hand side of the dot operator shall be of scalar type. The
2802 // left-hand side of the arrow operator shall be of pointer to scalar type.
2803 // This scalar type is the object type.
2804 Expr *BaseE = (Expr *)Base.get();
2805 QualType ObjectType = BaseE->getType();
2806 if (OpKind == tok::arrow) {
2807 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2808 ObjectType = Ptr->getPointeeType();
2809 } else if (!BaseE->isTypeDependent()) {
2810 // The user wrote "p->" when she probably meant "p."; fix it.
2811 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2812 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002813 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002814 if (isSFINAEContext())
2815 return ExprError();
2816
2817 OpKind = tok::period;
2818 }
2819 }
2820
2821 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2822 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2823 << ObjectType << BaseE->getSourceRange();
2824 return ExprError();
2825 }
2826
2827 // C++ [expr.pseudo]p2:
2828 // [...] The cv-unqualified versions of the object type and of the type
2829 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002830 if (DestructedTypeInfo) {
2831 QualType DestructedType = DestructedTypeInfo->getType();
2832 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002833 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002834 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2835 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2836 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2837 << ObjectType << DestructedType << BaseE->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002838 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002839
2840 // Recover by setting the destructed type to the object type.
2841 DestructedType = ObjectType;
2842 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2843 DestructedTypeStart);
2844 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2845 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002846 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002847
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002848 // C++ [expr.pseudo]p2:
2849 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2850 // form
2851 //
2852 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2853 //
2854 // shall designate the same scalar type.
2855 if (ScopeTypeInfo) {
2856 QualType ScopeType = ScopeTypeInfo->getType();
2857 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00002858 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002859
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002860 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002861 diag::err_pseudo_dtor_type_mismatch)
2862 << ObjectType << ScopeType << BaseE->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002863 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002864
2865 ScopeType = QualType();
2866 ScopeTypeInfo = 0;
2867 }
2868 }
2869
2870 OwningExprResult Result
2871 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2872 Base.takeAs<Expr>(),
2873 OpKind == tok::arrow,
2874 OpLoc,
2875 (NestedNameSpecifier *) SS.getScopeRep(),
2876 SS.getRange(),
2877 ScopeTypeInfo,
2878 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002879 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002880 Destructed));
2881
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002882 if (HasTrailingLParen)
2883 return move(Result);
2884
Douglas Gregor678f90d2010-02-25 01:56:36 +00002885 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002886}
2887
2888Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2889 SourceLocation OpLoc,
2890 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002891 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002892 UnqualifiedId &FirstTypeName,
2893 SourceLocation CCLoc,
2894 SourceLocation TildeLoc,
2895 UnqualifiedId &SecondTypeName,
2896 bool HasTrailingLParen) {
2897 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2898 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2899 "Invalid first type name in pseudo-destructor");
2900 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2901 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2902 "Invalid second type name in pseudo-destructor");
2903
2904 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002905
2906 // C++ [expr.pseudo]p2:
2907 // The left-hand side of the dot operator shall be of scalar type. The
2908 // left-hand side of the arrow operator shall be of pointer to scalar type.
2909 // This scalar type is the object type.
2910 QualType ObjectType = BaseE->getType();
2911 if (OpKind == tok::arrow) {
2912 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2913 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002914 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002915 // The user wrote "p->" when she probably meant "p."; fix it.
2916 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002917 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002918 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002919 if (isSFINAEContext())
2920 return ExprError();
2921
2922 OpKind = tok::period;
2923 }
2924 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002925
2926 // Compute the object type that we should use for name lookup purposes. Only
2927 // record types and dependent types matter.
2928 void *ObjectTypePtrForLookup = 0;
2929 if (!SS.isSet()) {
Gabor Greif2cd6c7b2010-06-17 11:29:31 +00002930 ObjectTypePtrForLookup = const_cast<RecordType*>(
2931 ObjectType->getAs<RecordType>());
Douglas Gregor678f90d2010-02-25 01:56:36 +00002932 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2933 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2934 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002935
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002936 // Convert the name of the type being destructed (following the ~) into a
2937 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002938 QualType DestructedType;
2939 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002940 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002941 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2942 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2943 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002944 S, &SS, true, ObjectTypePtrForLookup);
2945 if (!T &&
2946 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2947 (!SS.isSet() && ObjectType->isDependentType()))) {
2948 // The name of the type being destroyed is a dependent name, and we
2949 // couldn't find anything useful in scope. Just store the identifier and
2950 // it's location, and we'll perform (qualified) name lookup again at
2951 // template instantiation time.
2952 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2953 SecondTypeName.StartLocation);
2954 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002955 Diag(SecondTypeName.StartLocation,
2956 diag::err_pseudo_dtor_destructor_non_type)
2957 << SecondTypeName.Identifier << ObjectType;
2958 if (isSFINAEContext())
2959 return ExprError();
2960
2961 // Recover by assuming we had the right type all along.
2962 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002963 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002964 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002965 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002966 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002967 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002968 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2969 TemplateId->getTemplateArgs(),
2970 TemplateId->NumArgs);
2971 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2972 TemplateId->TemplateNameLoc,
2973 TemplateId->LAngleLoc,
2974 TemplateArgsPtr,
2975 TemplateId->RAngleLoc);
2976 if (T.isInvalid() || !T.get()) {
2977 // Recover by assuming we had the right type all along.
2978 DestructedType = ObjectType;
2979 } else
2980 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002981 }
2982
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002983 // If we've performed some kind of recovery, (re-)build the type source
2984 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002985 if (!DestructedType.isNull()) {
2986 if (!DestructedTypeInfo)
2987 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002988 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002989 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2990 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002991
2992 // Convert the name of the scope type (the type prior to '::') into a type.
2993 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002994 QualType ScopeType;
2995 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2996 FirstTypeName.Identifier) {
2997 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2998 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2999 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003000 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003001 if (!T) {
3002 Diag(FirstTypeName.StartLocation,
3003 diag::err_pseudo_dtor_destructor_non_type)
3004 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003005
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003006 if (isSFINAEContext())
3007 return ExprError();
3008
3009 // Just drop this type. It's unnecessary anyway.
3010 ScopeType = QualType();
3011 } else
3012 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003013 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003014 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003015 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003016 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3017 TemplateId->getTemplateArgs(),
3018 TemplateId->NumArgs);
3019 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
3020 TemplateId->TemplateNameLoc,
3021 TemplateId->LAngleLoc,
3022 TemplateArgsPtr,
3023 TemplateId->RAngleLoc);
3024 if (T.isInvalid() || !T.get()) {
3025 // Recover by dropping this type.
3026 ScopeType = QualType();
3027 } else
3028 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003029 }
3030 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00003031
3032 if (!ScopeType.isNull() && !ScopeTypeInfo)
3033 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3034 FirstTypeName.StartLocation);
3035
3036
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003037 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003038 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003039 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00003040}
3041
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003042CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00003043 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003044 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00003045 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3046 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00003047 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3048
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003049 MemberExpr *ME =
3050 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3051 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00003052 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00003053 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3054 CXXMemberCallExpr *CE =
3055 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3056 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003057 return CE;
3058}
3059
Anders Carlsson85a307d2009-05-17 18:41:29 +00003060Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3061 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003062 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00003063 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00003064 else
3065 return ExprError();
3066
Anders Carlsson85a307d2009-05-17 18:41:29 +00003067 return Owned(FullExpr);
3068}