blob: 8a3dcc9bcbf61ce4f0379d0774f227976e0c87b0 [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/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"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000027#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000028using namespace clang;
29
Douglas Gregorfe17d252010-02-16 19:09:40 +000030Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
31 IdentifierInfo &II,
32 SourceLocation NameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000033 Scope *S, CXXScopeSpec &SS,
Douglas Gregorfe17d252010-02-16 19:09:40 +000034 TypeTy *ObjectTypePtr,
35 bool EnteringContext) {
36 // Determine where to perform name lookup.
37
38 // FIXME: This area of the standard is very messy, and the current
39 // wording is rather unclear about which scopes we search for the
40 // destructor name; see core issues 399 and 555. Issue 399 in
41 // particular shows where the current description of destructor name
42 // lookup is completely out of line with existing practice, e.g.,
43 // this appears to be ill-formed:
44 //
45 // namespace N {
46 // template <typename T> struct S {
47 // ~S();
48 // };
49 // }
50 //
51 // void f(N::S<int>* s) {
52 // s->N::S<int>::~S();
53 // }
54 //
Douglas Gregor46841e12010-02-23 00:15:22 +000055 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +000056 // For this reason, we're currently only doing the C++03 version of this
57 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +000058 QualType SearchType;
59 DeclContext *LookupCtx = 0;
60 bool isDependent = false;
61 bool LookInScope = false;
62
63 // If we have an object type, it's because we are in a
64 // pseudo-destructor-expression or a member access expression, and
65 // we know what type we're looking for.
66 if (ObjectTypePtr)
67 SearchType = GetTypeFromParser(ObjectTypePtr);
68
69 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000070 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
71
72 bool AlreadySearched = false;
73 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000074 // C++ [basic.lookup.qual]p6:
75 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
76 // the type-names are looked up as types in the scope designated by the
77 // nested-name-specifier. In a qualified-id of the form:
78 //
79 // ::[opt] nested-name-specifier ̃ class-name
80 //
81 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000082 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000083 //
Sebastian Redla771d222010-07-07 23:17:38 +000084 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000085 //
Sebastian Redla771d222010-07-07 23:17:38 +000086 // the class-names are looked up as types in the scope designated by
87 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 //
Sebastian Redla771d222010-07-07 23:17:38 +000089 // Here, we check the first case (completely) and determine whether the
90 // code below is permitted to look at the prefix of the
91 // nested-name-specifier.
92 DeclContext *DC = computeDeclContext(SS, EnteringContext);
93 if (DC && DC->isFileContext()) {
94 AlreadySearched = true;
95 LookupCtx = DC;
96 isDependent = false;
97 } else if (DC && isa<CXXRecordDecl>(DC))
98 LookAtPrefix = false;
99
100 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000101 NestedNameSpecifier *Prefix = 0;
102 if (AlreadySearched) {
103 // Nothing left to do.
104 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
105 CXXScopeSpec PrefixSS;
106 PrefixSS.setScopeRep(Prefix);
107 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
108 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000109 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 LookupCtx = computeDeclContext(SearchType);
111 isDependent = SearchType->isDependentType();
112 } else {
113 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000114 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000115 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000116
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000117 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 } else if (ObjectTypePtr) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T
122 // of the object expression is of a class type C, the type-name is
123 // also looked up in the scope of class C. At least one of the
124 // lookups shall find a name that refers to (possibly
125 // cv-qualified) T.
126 LookupCtx = computeDeclContext(SearchType);
127 isDependent = SearchType->isDependentType();
128 assert((isDependent || !SearchType->isIncompleteType()) &&
129 "Caller should have completed object type");
130
131 LookInScope = true;
132 } else {
133 // Perform lookup into the current scope (only).
134 LookInScope = true;
135 }
136
137 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
138 for (unsigned Step = 0; Step != 2; ++Step) {
139 // Look for the name first in the computed lookup context (if we
140 // have one) and, if that fails to find a match, in the sope (if
141 // we're allowed to look there).
142 Found.clear();
143 if (Step == 0 && LookupCtx)
144 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000145 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000146 LookupName(Found, S);
147 else
148 continue;
149
150 // FIXME: Should we be suppressing ambiguities here?
151 if (Found.isAmbiguous())
152 return 0;
153
154 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
155 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000156
157 if (SearchType.isNull() || SearchType->isDependentType() ||
158 Context.hasSameUnqualifiedType(T, SearchType)) {
159 // We found our type!
160
161 return T.getAsOpaquePtr();
162 }
163 }
164
165 // If the name that we found is a class template name, and it is
166 // the same name as the template name in the last part of the
167 // nested-name-specifier (if present) or the object type, then
168 // this is the destructor for that class.
169 // FIXME: This is a workaround until we get real drafting for core
170 // issue 399, for which there isn't even an obvious direction.
171 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
172 QualType MemberOfType;
173 if (SS.isSet()) {
174 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
175 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000176 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
177 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000178 }
179 }
180 if (MemberOfType.isNull())
181 MemberOfType = SearchType;
182
183 if (MemberOfType.isNull())
184 continue;
185
186 // We're referring into a class template specialization. If the
187 // class template we found is the same as the template being
188 // specialized, we found what we are looking for.
189 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
190 if (ClassTemplateSpecializationDecl *Spec
191 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
192 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
193 Template->getCanonicalDecl())
194 return MemberOfType.getAsOpaquePtr();
195 }
196
197 continue;
198 }
199
200 // We're referring to an unresolved class template
201 // specialization. Determine whether we class template we found
202 // is the same as the template being specialized or, if we don't
203 // know which template is being specialized, that it at least
204 // has the same name.
205 if (const TemplateSpecializationType *SpecType
206 = MemberOfType->getAs<TemplateSpecializationType>()) {
207 TemplateName SpecName = SpecType->getTemplateName();
208
209 // The class template we found is the same template being
210 // specialized.
211 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
212 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214
215 continue;
216 }
217
218 // The class template we found has the same name as the
219 // (dependent) template name being specialized.
220 if (DependentTemplateName *DepTemplate
221 = SpecName.getAsDependentTemplateName()) {
222 if (DepTemplate->isIdentifier() &&
223 DepTemplate->getIdentifier() == Template->getIdentifier())
224 return MemberOfType.getAsOpaquePtr();
225
226 continue;
227 }
228 }
229 }
230 }
231
232 if (isDependent) {
233 // We didn't find our type, but that's okay: it's dependent
234 // anyway.
235 NestedNameSpecifier *NNS = 0;
236 SourceRange Range;
237 if (SS.isSet()) {
238 NNS = (NestedNameSpecifier *)SS.getScopeRep();
239 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
240 } else {
241 NNS = NestedNameSpecifier::Create(Context, &II);
242 Range = SourceRange(NameLoc);
243 }
244
Abramo Bagnarad7548482010-05-19 21:37:53 +0000245 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
246 Range, NameLoc).getAsOpaquePtr();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000247 }
248
249 if (ObjectTypePtr)
250 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
251 << &II;
252 else
253 Diag(NameLoc, diag::err_destructor_class_name);
254
255 return 0;
256}
257
Douglas Gregor9da64192010-04-26 22:37:10 +0000258/// \brief Build a C++ typeid expression with a type operand.
259Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
260 SourceLocation TypeidLoc,
261 TypeSourceInfo *Operand,
262 SourceLocation RParenLoc) {
263 // C++ [expr.typeid]p4:
264 // The top-level cv-qualifiers of the lvalue expression or the type-id
265 // that is the operand of typeid are always ignored.
266 // If the type of the type-id is a class type or a reference to a class
267 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000268 Qualifiers Quals;
269 QualType T
270 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
271 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000272 if (T->getAs<RecordType>() &&
273 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
274 return ExprError();
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000275
Douglas Gregor9da64192010-04-26 22:37:10 +0000276 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
277 Operand,
278 SourceRange(TypeidLoc, RParenLoc)));
279}
280
281/// \brief Build a C++ typeid expression with an expression operand.
282Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
283 SourceLocation TypeidLoc,
John McCallb268a282010-08-23 23:25:46 +0000284 Expr *E,
Douglas Gregor9da64192010-04-26 22:37:10 +0000285 SourceLocation RParenLoc) {
286 bool isUnevaluatedOperand = true;
Douglas Gregor9da64192010-04-26 22:37:10 +0000287 if (E && !E->isTypeDependent()) {
288 QualType T = E->getType();
289 if (const RecordType *RecordT = T->getAs<RecordType>()) {
290 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
291 // C++ [expr.typeid]p3:
292 // [...] If the type of the expression is a class type, the class
293 // shall be completely-defined.
294 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
295 return ExprError();
296
297 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000298 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000299 // polymorphic class type [...] [the] expression is an unevaluated
300 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000301 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000302 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000303
304 // We require a vtable to query the type at run time.
305 MarkVTableUsed(TypeidLoc, RecordD);
306 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000307 }
308
309 // C++ [expr.typeid]p4:
310 // [...] If the type of the type-id is a reference to a possibly
311 // cv-qualified type, the result of the typeid expression refers to a
312 // std::type_info object representing the cv-unqualified referenced
313 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000314 Qualifiers Quals;
315 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
316 if (!Context.hasSameType(T, UnqualT)) {
317 T = UnqualT;
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000318 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, CastCategory(E));
Douglas Gregor9da64192010-04-26 22:37:10 +0000319 }
320 }
321
322 // If this is an unevaluated operand, clear out the set of
323 // declaration references we have been computing and eliminate any
324 // temporaries introduced in its computation.
325 if (isUnevaluatedOperand)
326 ExprEvalContexts.back().Context = Unevaluated;
327
328 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000329 E,
Douglas Gregor9da64192010-04-26 22:37:10 +0000330 SourceRange(TypeidLoc, RParenLoc)));
331}
332
333/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000334Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000335Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
336 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000337 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000338 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000339 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000340
Chris Lattnerec7f7732008-11-20 05:51:55 +0000341 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000342 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +0000343 LookupQualifiedName(R, getStdNamespace());
John McCall67c00872009-12-02 08:25:40 +0000344 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000345 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000346 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor9da64192010-04-26 22:37:10 +0000347
Sebastian Redlc4704762008-11-11 11:37:55 +0000348 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor9da64192010-04-26 22:37:10 +0000349
350 if (isType) {
351 // The operand is a type; handle it as such.
352 TypeSourceInfo *TInfo = 0;
353 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
354 if (T.isNull())
355 return ExprError();
356
357 if (!TInfo)
358 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000359
Douglas Gregor9da64192010-04-26 22:37:10 +0000360 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000361 }
Mike Stump11289f42009-09-09 15:08:12 +0000362
Douglas Gregor9da64192010-04-26 22:37:10 +0000363 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000364 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000365}
366
Steve Naroff66356bd2007-09-16 14:56:35 +0000367/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000368Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000369Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000370 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000371 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000372 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
373 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000374}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000375
Sebastian Redl576fd422009-05-10 18:38:11 +0000376/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
377Action::OwningExprResult
378Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
379 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
380}
381
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000382/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000383Action::OwningExprResult
John McCallb268a282010-08-23 23:25:46 +0000384Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000385 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
386 return ExprError();
387 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
388}
389
390/// CheckCXXThrowOperand - Validate the operand of a throw.
391bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
392 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000393 // A throw-expression initializes a temporary object, called the exception
394 // object, the type of which is determined by removing any top-level
395 // cv-qualifiers from the static type of the operand of throw and adjusting
396 // the type from "array of T" or "function returning T" to "pointer to T"
397 // or "pointer to function returning T", [...]
398 if (E->getType().hasQualifiers())
399 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000400 CastCategory(E));
Douglas Gregor247894b2009-12-23 22:04:40 +0000401
Sebastian Redl4de47b42009-04-27 20:27:31 +0000402 DefaultFunctionArrayConversion(E);
403
404 // If the type of the exception would be an incomplete type or a pointer
405 // to an incomplete type other than (cv) void the program is ill-formed.
406 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000407 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000408 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000409 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000410 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000411 }
412 if (!isPointer || !Ty->isVoidType()) {
413 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000414 PDiag(isPointer ? diag::err_throw_incomplete_ptr
415 : diag::err_throw_incomplete)
416 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000417 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000418
Douglas Gregore8154332010-04-15 18:05:39 +0000419 if (RequireNonAbstractType(ThrowLoc, E->getType(),
420 PDiag(diag::err_throw_abstract_type)
421 << E->getSourceRange()))
422 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000423 }
424
John McCall2e6567a2010-04-22 01:10:34 +0000425 // Initialize the exception result. This implicitly weeds out
426 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000427 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000428 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000429 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
430 /*NRVO=*/false);
John McCall2e6567a2010-04-22 01:10:34 +0000431 OwningExprResult Res = PerformCopyInitialization(Entity,
432 SourceLocation(),
433 Owned(E));
434 if (Res.isInvalid())
435 return true;
436 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000437
Eli Friedman91a3d272010-06-03 20:39:03 +0000438 // If the exception has class type, we need additional handling.
439 const RecordType *RecordTy = Ty->getAs<RecordType>();
440 if (!RecordTy)
441 return false;
442 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
443
Douglas Gregor88d292c2010-05-13 16:44:06 +0000444 // If we are throwing a polymorphic class type or pointer thereof,
445 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000446 MarkVTableUsed(ThrowLoc, RD);
447
448 // If the class has a non-trivial destructor, we must be able to call it.
449 if (RD->hasTrivialDestructor())
450 return false;
451
Douglas Gregorbac74902010-07-01 14:13:13 +0000452 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000453 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000454 if (!Destructor)
455 return false;
456
457 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
458 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000459 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000460 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000461}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000462
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000463Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000464 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
465 /// is a non-lvalue expression whose value is the address of the object for
466 /// which the function is called.
467
John McCall87fe5d52010-05-20 01:18:31 +0000468 DeclContext *DC = getFunctionLevelDeclContext();
469 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000470 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000471 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000472 MD->getThisType(Context),
473 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000474
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000475 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000476}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000477
478/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
479/// Can be interpreted either as function-style casting ("int(x)")
480/// or class type construction ("ClassType(x,y,z)")
481/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000482Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000483Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
484 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000485 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000486 SourceLocation *CommaLocs,
487 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000488 if (!TypeRep)
489 return ExprError();
490
John McCall97513962010-01-15 18:39:57 +0000491 TypeSourceInfo *TInfo;
492 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
493 if (!TInfo)
494 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000495 unsigned NumExprs = exprs.size();
496 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000497 SourceLocation TyBeginLoc = TypeRange.getBegin();
498 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
499
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000500 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000501 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000502 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000503
504 return Owned(CXXUnresolvedConstructExpr::Create(Context,
505 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000506 LParenLoc,
507 Exprs, NumExprs,
508 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000509 }
510
Anders Carlsson55243162009-08-27 03:53:50 +0000511 if (Ty->isArrayType())
512 return ExprError(Diag(TyBeginLoc,
513 diag::err_value_init_for_array_type) << FullRange);
514 if (!Ty->isVoidType() &&
515 RequireCompleteType(TyBeginLoc, Ty,
516 PDiag(diag::err_invalid_incomplete_type_use)
517 << FullRange))
518 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000519
Anders Carlsson55243162009-08-27 03:53:50 +0000520 if (RequireNonAbstractType(TyBeginLoc, Ty,
521 diag::err_allocation_of_abstract_type))
522 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000523
524
Douglas Gregordd04d332009-01-16 18:33:17 +0000525 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000526 // If the expression list is a single expression, the type conversion
527 // expression is equivalent (in definedness, and if defined in meaning) to the
528 // corresponding cast expression.
529 //
530 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000531 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000532 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +0000533 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
534 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000535 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000536
537 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000538
John McCallcf142162010-08-07 06:22:56 +0000539 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000540 Ty.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000541 TInfo, TyBeginLoc, Kind,
542 Exprs[0], &BasePath,
543 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000544 }
545
Douglas Gregor747eb782010-07-08 06:14:04 +0000546 if (Ty->isRecordType()) {
547 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
548 InitializationKind Kind
549 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
550 LParenLoc, RParenLoc)
551 : InitializationKind::CreateValue(TypeRange.getBegin(),
552 LParenLoc, RParenLoc);
553 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
554 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
555 move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000556
Douglas Gregor747eb782010-07-08 06:14:04 +0000557 // FIXME: Improve AST representation?
558 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000559 }
560
561 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000562 // If the expression list specifies more than a single value, the type shall
563 // be a class with a suitably declared constructor.
564 //
565 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000566 return ExprError(Diag(CommaLocs[0],
567 diag::err_builtin_func_cast_more_than_one_arg)
568 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000569
570 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000571 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000572 // The expression T(), where T is a simple-type-specifier for a non-array
573 // complete object type or the (possibly cv-qualified) void type, creates an
574 // rvalue of the specified type, which is value-initialized.
575 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000576 exprs.release();
Douglas Gregor747eb782010-07-08 06:14:04 +0000577 return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000578}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000579
580
Sebastian Redlbd150f42008-11-21 19:14:01 +0000581/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
582/// @code new (memory) int[size][4] @endcode
583/// or
584/// @code ::new Foo(23, "hello") @endcode
585/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000586Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000587Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000588 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000589 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000590 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000591 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000592 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000593 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000594 // If the specified type is an array, unwrap it and save the expression.
595 if (D.getNumTypeObjects() > 0 &&
596 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
597 DeclaratorChunk &Chunk = D.getTypeObject(0);
598 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000599 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
600 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000601 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000602 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
603 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000604
Sebastian Redl351bb782008-12-02 14:43:59 +0000605 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000606 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000607 }
608
Douglas Gregor73341c42009-09-11 00:18:58 +0000609 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000610 if (ArraySize) {
611 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000612 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
613 break;
614
615 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
616 if (Expr *NumElts = (Expr *)Array.NumElts) {
617 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
618 !NumElts->isIntegerConstantExpr(Context)) {
619 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
620 << NumElts->getSourceRange();
621 return ExprError();
622 }
623 }
624 }
625 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000626
John McCallbcd03502009-12-07 02:54:59 +0000627 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCall8cb7bdf2010-06-04 23:28:52 +0000628 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
629 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000630 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000631 return ExprError();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000632
633 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000634 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000635 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000636 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000637 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000638 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000639 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000640 D.getSourceRange().getBegin(),
Ted Kremenekabb1f912010-06-25 22:48:49 +0000641 R,
John McCallb268a282010-08-23 23:25:46 +0000642 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000643 ConstructorLParen,
644 move(ConstructorArgs),
645 ConstructorRParen);
646}
647
Mike Stump11289f42009-09-09 15:08:12 +0000648Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000649Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
650 SourceLocation PlacementLParen,
651 MultiExprArg PlacementArgs,
652 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000653 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000654 QualType AllocType,
655 SourceLocation TypeLoc,
656 SourceRange TypeRange,
John McCallb268a282010-08-23 23:25:46 +0000657 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000658 SourceLocation ConstructorLParen,
659 MultiExprArg ConstructorArgs,
660 SourceLocation ConstructorRParen) {
661 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000662 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000663
Douglas Gregorcda95f42010-05-16 16:01:03 +0000664 // Per C++0x [expr.new]p5, the type being constructed may be a
665 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000666 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000667 if (const ConstantArrayType *Array
668 = Context.getAsConstantArrayType(AllocType)) {
John McCallb268a282010-08-23 23:25:46 +0000669 ArraySize = new (Context) IntegerLiteral(Array->getSize(),
670 Context.getSizeType(),
671 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000672 AllocType = Array->getElementType();
673 }
674 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000675
Douglas Gregorcda95f42010-05-16 16:01:03 +0000676 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000677
Sebastian Redlbd150f42008-11-21 19:14:01 +0000678 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
679 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000680 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor4799d032010-06-30 00:20:43 +0000681
Sebastian Redl351bb782008-12-02 14:43:59 +0000682 QualType SizeType = ArraySize->getType();
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000683
Douglas Gregor4799d032010-06-30 00:20:43 +0000684 OwningExprResult ConvertedSize
John McCallb268a282010-08-23 23:25:46 +0000685 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor4799d032010-06-30 00:20:43 +0000686 PDiag(diag::err_array_size_not_integral),
687 PDiag(diag::err_array_size_incomplete_type)
688 << ArraySize->getSourceRange(),
689 PDiag(diag::err_array_size_explicit_conversion),
690 PDiag(diag::note_array_size_conversion),
691 PDiag(diag::err_array_size_ambiguous_conversion),
692 PDiag(diag::note_array_size_conversion),
693 PDiag(getLangOptions().CPlusPlus0x? 0
694 : diag::ext_array_size_conversion));
695 if (ConvertedSize.isInvalid())
696 return ExprError();
697
John McCallb268a282010-08-23 23:25:46 +0000698 ArraySize = ConvertedSize.take();
Douglas Gregor4799d032010-06-30 00:20:43 +0000699 SizeType = ArraySize->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000700 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000701 return ExprError();
702
Sebastian Redl351bb782008-12-02 14:43:59 +0000703 // Let's see if this is a constant < 0. If so, we reject it out of hand.
704 // We don't care about special rules, so we tell the machinery it's not
705 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000706 if (!ArraySize->isValueDependent()) {
707 llvm::APSInt Value;
708 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
709 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000710 llvm::APInt::getNullValue(Value.getBitWidth()),
711 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000712 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000713 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000714 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000715
716 if (!AllocType->isDependentType()) {
717 unsigned ActiveSizeBits
718 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
719 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
720 Diag(ArraySize->getSourceRange().getBegin(),
721 diag::err_array_too_large)
722 << Value.toString(10)
723 << ArraySize->getSourceRange();
724 return ExprError();
725 }
726 }
Douglas Gregorf2753b32010-07-13 15:54:32 +0000727 } else if (TypeIdParens.isValid()) {
728 // Can't have dynamic array size when the type-id is in parentheses.
729 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
730 << ArraySize->getSourceRange()
731 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
732 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
733
734 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000735 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000736 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000737
Eli Friedman06ed2a52009-10-20 08:27:19 +0000738 ImpCastExprToType(ArraySize, Context.getSizeType(),
739 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000740 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000741
Sebastian Redlbd150f42008-11-21 19:14:01 +0000742 FunctionDecl *OperatorNew = 0;
743 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000744 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
745 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000746
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000747 if (!AllocType->isDependentType() &&
748 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
749 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000750 SourceRange(PlacementLParen, PlacementRParen),
751 UseGlobal, AllocType, ArraySize, PlaceArgs,
752 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000753 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000754 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000755 if (OperatorNew) {
756 // Add default arguments, if any.
757 const FunctionProtoType *Proto =
758 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000759 VariadicCallType CallType =
760 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000761
762 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
763 Proto, 1, PlaceArgs, NumPlaceArgs,
764 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000765 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000766
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000767 NumPlaceArgs = AllPlaceArgs.size();
768 if (NumPlaceArgs > 0)
769 PlaceArgs = &AllPlaceArgs[0];
770 }
771
Sebastian Redlbd150f42008-11-21 19:14:01 +0000772 bool Init = ConstructorLParen.isValid();
773 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000774 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000775 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
776 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +0000777 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000778
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000779 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000780 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000781 SourceRange InitRange(ConsArgs[0]->getLocStart(),
782 ConsArgs[NumConsArgs - 1]->getLocEnd());
783
784 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
785 return ExprError();
786 }
787
Douglas Gregor85dabae2009-12-16 01:38:02 +0000788 if (!AllocType->isDependentType() &&
789 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
790 // C++0x [expr.new]p15:
791 // A new-expression that creates an object of type T initializes that
792 // object as follows:
793 InitializationKind Kind
794 // - If the new-initializer is omitted, the object is default-
795 // initialized (8.5); if no initialization is performed,
796 // the object has indeterminate value
797 = !Init? InitializationKind::CreateDefault(TypeLoc)
798 // - Otherwise, the new-initializer is interpreted according to the
799 // initialization rules of 8.5 for direct-initialization.
800 : InitializationKind::CreateDirect(TypeLoc,
801 ConstructorLParen,
802 ConstructorRParen);
803
Douglas Gregor85dabae2009-12-16 01:38:02 +0000804 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000805 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000806 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000807 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
808 move(ConstructorArgs));
809 if (FullInit.isInvalid())
810 return ExprError();
811
812 // FullInit is our initializer; walk through it to determine if it's a
813 // constructor call, which CXXNewExpr handles directly.
814 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
815 if (CXXBindTemporaryExpr *Binder
816 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
817 FullInitExpr = Binder->getSubExpr();
818 if (CXXConstructExpr *Construct
819 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
820 Constructor = Construct->getConstructor();
821 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
822 AEnd = Construct->arg_end();
823 A != AEnd; ++A)
824 ConvertedConstructorArgs.push_back(A->Retain());
825 } else {
826 // Take the converted initializer.
827 ConvertedConstructorArgs.push_back(FullInit.release());
828 }
829 } else {
830 // No initialization required.
831 }
832
833 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000834 NumConsArgs = ConvertedConstructorArgs.size();
835 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000836 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000837
Douglas Gregor6642ca22010-02-26 05:06:18 +0000838 // Mark the new and delete operators as referenced.
839 if (OperatorNew)
840 MarkDeclarationReferenced(StartLoc, OperatorNew);
841 if (OperatorDelete)
842 MarkDeclarationReferenced(StartLoc, OperatorDelete);
843
Sebastian Redlbd150f42008-11-21 19:14:01 +0000844 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000845
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000846 PlacementArgs.release();
847 ConstructorArgs.release();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000848
849 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000850 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000851 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000852 ArraySize, Constructor, Init,
853 ConsArgs, NumConsArgs, OperatorDelete,
854 ResultType, StartLoc,
855 Init ? ConstructorRParen :
Ted Kremenekabb1f912010-06-25 22:48:49 +0000856 TypeRange.getEnd()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000857}
858
859/// CheckAllocatedType - Checks that a type is suitable as the allocated type
860/// in a new-expression.
861/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000862bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000863 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000864 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
865 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000866 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000867 return Diag(Loc, diag::err_bad_new_type)
868 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000869 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000870 return Diag(Loc, diag::err_bad_new_type)
871 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000872 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000873 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000874 PDiag(diag::err_new_incomplete_type)
875 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000876 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000877 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000878 diag::err_allocation_of_abstract_type))
879 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000880
Sebastian Redlbd150f42008-11-21 19:14:01 +0000881 return false;
882}
883
Douglas Gregor6642ca22010-02-26 05:06:18 +0000884/// \brief Determine whether the given function is a non-placement
885/// deallocation function.
886static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
887 if (FD->isInvalidDecl())
888 return false;
889
890 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
891 return Method->isUsualDeallocationFunction();
892
893 return ((FD->getOverloadedOperator() == OO_Delete ||
894 FD->getOverloadedOperator() == OO_Array_Delete) &&
895 FD->getNumParams() == 1);
896}
897
Sebastian Redlfaf68082008-12-03 20:26:15 +0000898/// FindAllocationFunctions - Finds the overloads of operator new and delete
899/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000900bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
901 bool UseGlobal, QualType AllocType,
902 bool IsArray, Expr **PlaceArgs,
903 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000904 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000905 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000906 // --- Choosing an allocation function ---
907 // C++ 5.3.4p8 - 14 & 18
908 // 1) If UseGlobal is true, only look in the global scope. Else, also look
909 // in the scope of the allocated class.
910 // 2) If an array size is given, look for operator new[], else look for
911 // operator new.
912 // 3) The first argument is always size_t. Append the arguments from the
913 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000914
915 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
916 // We don't care about the actual value of this argument.
917 // FIXME: Should the Sema create the expression and embed it in the syntax
918 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000919 IntegerLiteral Size(llvm::APInt::getNullValue(
920 Context.Target.getPointerWidth(0)),
921 Context.getSizeType(),
922 SourceLocation());
923 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000924 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
925
Douglas Gregor6642ca22010-02-26 05:06:18 +0000926 // C++ [expr.new]p8:
927 // If the allocated type is a non-array type, the allocation
928 // function’s name is operator new and the deallocation function’s
929 // name is operator delete. If the allocated type is an array
930 // type, the allocation function’s name is operator new[] and the
931 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000932 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
933 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000934 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
935 IsArray ? OO_Array_Delete : OO_Delete);
936
Sebastian Redlfaf68082008-12-03 20:26:15 +0000937 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000938 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000939 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000940 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000941 AllocArgs.size(), Record, /*AllowMissing=*/true,
942 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000943 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000944 }
945 if (!OperatorNew) {
946 // Didn't find a member overload. Look for a global one.
947 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000948 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000949 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000950 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
951 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000952 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000953 }
954
John McCall0f55a032010-04-20 02:18:25 +0000955 // We don't need an operator delete if we're running under
956 // -fno-exceptions.
957 if (!getLangOptions().Exceptions) {
958 OperatorDelete = 0;
959 return false;
960 }
961
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000962 // FindAllocationOverload can change the passed in arguments, so we need to
963 // copy them back.
964 if (NumPlaceArgs > 0)
965 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000966
Douglas Gregor6642ca22010-02-26 05:06:18 +0000967 // C++ [expr.new]p19:
968 //
969 // If the new-expression begins with a unary :: operator, the
970 // deallocation function’s name is looked up in the global
971 // scope. Otherwise, if the allocated type is a class type T or an
972 // array thereof, the deallocation function’s name is looked up in
973 // the scope of T. If this lookup fails to find the name, or if
974 // the allocated type is not a class type or array thereof, the
975 // deallocation function’s name is looked up in the global scope.
976 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
977 if (AllocType->isRecordType() && !UseGlobal) {
978 CXXRecordDecl *RD
979 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
980 LookupQualifiedName(FoundDelete, RD);
981 }
John McCallfb6f5262010-03-18 08:19:33 +0000982 if (FoundDelete.isAmbiguous())
983 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000984
985 if (FoundDelete.empty()) {
986 DeclareGlobalNewDelete();
987 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
988 }
989
990 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000991
992 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
993
John McCallfb6f5262010-03-18 08:19:33 +0000994 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +0000995 // C++ [expr.new]p20:
996 // A declaration of a placement deallocation function matches the
997 // declaration of a placement allocation function if it has the
998 // same number of parameters and, after parameter transformations
999 // (8.3.5), all parameter types except the first are
1000 // identical. [...]
1001 //
1002 // To perform this comparison, we compute the function type that
1003 // the deallocation function should have, and use that type both
1004 // for template argument deduction and for comparison purposes.
1005 QualType ExpectedFunctionType;
1006 {
1007 const FunctionProtoType *Proto
1008 = OperatorNew->getType()->getAs<FunctionProtoType>();
1009 llvm::SmallVector<QualType, 4> ArgTypes;
1010 ArgTypes.push_back(Context.VoidPtrTy);
1011 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1012 ArgTypes.push_back(Proto->getArgType(I));
1013
1014 ExpectedFunctionType
1015 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1016 ArgTypes.size(),
1017 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001018 0, false, false, 0, 0,
1019 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001020 }
1021
1022 for (LookupResult::iterator D = FoundDelete.begin(),
1023 DEnd = FoundDelete.end();
1024 D != DEnd; ++D) {
1025 FunctionDecl *Fn = 0;
1026 if (FunctionTemplateDecl *FnTmpl
1027 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1028 // Perform template argument deduction to try to match the
1029 // expected function type.
1030 TemplateDeductionInfo Info(Context, StartLoc);
1031 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1032 continue;
1033 } else
1034 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1035
1036 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001037 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001038 }
1039 } else {
1040 // C++ [expr.new]p20:
1041 // [...] Any non-placement deallocation function matches a
1042 // non-placement allocation function. [...]
1043 for (LookupResult::iterator D = FoundDelete.begin(),
1044 DEnd = FoundDelete.end();
1045 D != DEnd; ++D) {
1046 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1047 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001048 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001049 }
1050 }
1051
1052 // C++ [expr.new]p20:
1053 // [...] If the lookup finds a single matching deallocation
1054 // function, that function will be called; otherwise, no
1055 // deallocation function will be called.
1056 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001057 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001058
1059 // C++0x [expr.new]p20:
1060 // If the lookup finds the two-parameter form of a usual
1061 // deallocation function (3.7.4.2) and that function, considered
1062 // as a placement deallocation function, would have been
1063 // selected as a match for the allocation function, the program
1064 // is ill-formed.
1065 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1066 isNonPlacementDeallocationFunction(OperatorDelete)) {
1067 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1068 << SourceRange(PlaceArgs[0]->getLocStart(),
1069 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1070 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1071 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001072 } else {
1073 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001074 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001075 }
1076 }
1077
Sebastian Redlfaf68082008-12-03 20:26:15 +00001078 return false;
1079}
1080
Sebastian Redl33a31012008-12-04 22:20:51 +00001081/// FindAllocationOverload - Find an fitting overload for the allocation
1082/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001083bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1084 DeclarationName Name, Expr** Args,
1085 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001086 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001087 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1088 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001089 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001090 if (AllowMissing)
1091 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001092 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001093 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001094 }
1095
John McCallfb6f5262010-03-18 08:19:33 +00001096 if (R.isAmbiguous())
1097 return true;
1098
1099 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001100
John McCallbc077cf2010-02-08 23:07:23 +00001101 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001102 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1103 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001104 // Even member operator new/delete are implicitly treated as
1105 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001106 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001107
John McCalla0296f72010-03-19 07:35:19 +00001108 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1109 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001110 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1111 Candidates,
1112 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001113 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001114 }
1115
John McCalla0296f72010-03-19 07:35:19 +00001116 FunctionDecl *Fn = cast<FunctionDecl>(D);
1117 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001118 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001119 }
1120
1121 // Do the resolution.
1122 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001123 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001124 case OR_Success: {
1125 // Got one!
1126 FunctionDecl *FnDecl = Best->Function;
1127 // The first argument is size_t, and the first parameter must be size_t,
1128 // too. This is checked on declaration and can be assumed. (It can't be
1129 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001130 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001131 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1132 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-03-26 20:35:59 +00001133 OwningExprResult Result
1134 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1135 FnDecl->getParamDecl(i)),
1136 SourceLocation(),
1137 Owned(Args[i]->Retain()));
1138 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001139 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001140
1141 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001142 }
1143 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001144 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001145 return false;
1146 }
1147
1148 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001149 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001150 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001151 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001152 return true;
1153
1154 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001155 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001156 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001157 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001158 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001159
1160 case OR_Deleted:
1161 Diag(StartLoc, diag::err_ovl_deleted_call)
1162 << Best->Function->isDeleted()
1163 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001164 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001165 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001166 }
1167 assert(false && "Unreachable, bad result from BestViableFunction");
1168 return true;
1169}
1170
1171
Sebastian Redlfaf68082008-12-03 20:26:15 +00001172/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1173/// delete. These are:
1174/// @code
1175/// void* operator new(std::size_t) throw(std::bad_alloc);
1176/// void* operator new[](std::size_t) throw(std::bad_alloc);
1177/// void operator delete(void *) throw();
1178/// void operator delete[](void *) throw();
1179/// @endcode
1180/// Note that the placement and nothrow forms of new are *not* implicitly
1181/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001182void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001183 if (GlobalNewDeleteDeclared)
1184 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001185
1186 // C++ [basic.std.dynamic]p2:
1187 // [...] The following allocation and deallocation functions (18.4) are
1188 // implicitly declared in global scope in each translation unit of a
1189 // program
1190 //
1191 // void* operator new(std::size_t) throw(std::bad_alloc);
1192 // void* operator new[](std::size_t) throw(std::bad_alloc);
1193 // void operator delete(void*) throw();
1194 // void operator delete[](void*) throw();
1195 //
1196 // These implicit declarations introduce only the function names operator
1197 // new, operator new[], operator delete, operator delete[].
1198 //
1199 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1200 // "std" or "bad_alloc" as necessary to form the exception specification.
1201 // However, we do not make these implicit declarations visible to name
1202 // lookup.
Douglas Gregor87f54062009-09-15 22:30:29 +00001203 if (!StdBadAlloc) {
1204 // The "std::bad_alloc" class has not yet been declared, so build it
1205 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001206 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00001207 getOrCreateStdNamespace(),
Douglas Gregor87f54062009-09-15 22:30:29 +00001208 SourceLocation(),
1209 &PP.getIdentifierTable().get("bad_alloc"),
1210 SourceLocation(), 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001211 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001212 }
1213
Sebastian Redlfaf68082008-12-03 20:26:15 +00001214 GlobalNewDeleteDeclared = true;
1215
1216 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1217 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001218 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001219
Sebastian Redlfaf68082008-12-03 20:26:15 +00001220 DeclareGlobalAllocationFunction(
1221 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001222 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001223 DeclareGlobalAllocationFunction(
1224 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001225 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001226 DeclareGlobalAllocationFunction(
1227 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1228 Context.VoidTy, VoidPtr);
1229 DeclareGlobalAllocationFunction(
1230 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1231 Context.VoidTy, VoidPtr);
1232}
1233
1234/// DeclareGlobalAllocationFunction - Declares a single implicit global
1235/// allocation function if it doesn't already exist.
1236void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001237 QualType Return, QualType Argument,
1238 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001239 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1240
1241 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001242 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001243 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001244 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001245 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001246 // Only look at non-template functions, as it is the predefined,
1247 // non-templated allocation function we are trying to declare here.
1248 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1249 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001250 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001251 Func->getParamDecl(0)->getType().getUnqualifiedType());
1252 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001253 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1254 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001255 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001256 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001257 }
Chandler Carruth93538422010-02-03 11:02:14 +00001258 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001259 }
1260 }
1261
Douglas Gregor87f54062009-09-15 22:30:29 +00001262 QualType BadAllocType;
1263 bool HasBadAllocExceptionSpec
1264 = (Name.getCXXOverloadedOperator() == OO_New ||
1265 Name.getCXXOverloadedOperator() == OO_Array_New);
1266 if (HasBadAllocExceptionSpec) {
1267 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001268 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001269 }
1270
1271 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1272 true, false,
1273 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001274 &BadAllocType,
1275 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001276 FunctionDecl *Alloc =
1277 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001278 FnType, /*TInfo=*/0, FunctionDecl::None,
1279 FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001280 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001281
1282 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001283 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopes13c88c72009-12-16 16:59:22 +00001284
Sebastian Redlfaf68082008-12-03 20:26:15 +00001285 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001286 0, Argument, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001287 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001288 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001289 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001290
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001291 // FIXME: Also add this declaration to the IdentifierResolver, but
1292 // make sure it is at the end of the chain to coincide with the
1293 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001294 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001295}
1296
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001297bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1298 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001299 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001300 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001301 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001302 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001303
John McCall27b18f82009-11-17 02:14:36 +00001304 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001305 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001306
Chandler Carruthb6f99172010-06-28 00:30:51 +00001307 Found.suppressDiagnostics();
1308
John McCall66a87592010-08-04 00:31:26 +00001309 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001310 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1311 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001312 NamedDecl *ND = (*F)->getUnderlyingDecl();
1313
1314 // Ignore template operator delete members from the check for a usual
1315 // deallocation function.
1316 if (isa<FunctionTemplateDecl>(ND))
1317 continue;
1318
1319 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001320 Matches.push_back(F.getPair());
1321 }
1322
1323 // There's exactly one suitable operator; pick it.
1324 if (Matches.size() == 1) {
1325 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1326 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1327 Matches[0]);
1328 return false;
1329
1330 // We found multiple suitable operators; complain about the ambiguity.
1331 } else if (!Matches.empty()) {
1332 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1333 << Name << RD;
1334
1335 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1336 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1337 Diag((*F)->getUnderlyingDecl()->getLocation(),
1338 diag::note_member_declared_here) << Name;
1339 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001340 }
1341
1342 // We did find operator delete/operator delete[] declarations, but
1343 // none of them were suitable.
1344 if (!Found.empty()) {
1345 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1346 << Name << RD;
1347
1348 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall66a87592010-08-04 00:31:26 +00001349 F != FEnd; ++F)
1350 Diag((*F)->getUnderlyingDecl()->getLocation(),
1351 diag::note_member_declared_here) << Name;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001352
1353 return true;
1354 }
1355
1356 // Look for a global declaration.
1357 DeclareGlobalNewDelete();
1358 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1359
1360 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1361 Expr* DeallocArgs[1];
1362 DeallocArgs[0] = &Null;
1363 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1364 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1365 Operator))
1366 return true;
1367
1368 assert(Operator && "Did not find a deallocation function!");
1369 return false;
1370}
1371
Sebastian Redlbd150f42008-11-21 19:14:01 +00001372/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1373/// @code ::delete ptr; @endcode
1374/// or
1375/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001376Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001377Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCallb268a282010-08-23 23:25:46 +00001378 bool ArrayForm, Expr *Ex) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001379 // C++ [expr.delete]p1:
1380 // The operand shall have a pointer type, or a class type having a single
1381 // conversion function to a pointer type. The result has type void.
1382 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001383 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1384
Anders Carlssona471db02009-08-16 20:29:29 +00001385 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001386
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001387 if (!Ex->isTypeDependent()) {
1388 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001389
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001390 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregorf65f4902010-07-29 14:44:35 +00001391 if (RequireCompleteType(StartLoc, Type,
1392 PDiag(diag::err_delete_incomplete_class_type)))
1393 return ExprError();
1394
John McCallda4458e2010-03-31 01:36:47 +00001395 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1396
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001397 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001398 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001399 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001400 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001401 NamedDecl *D = I.getDecl();
1402 if (isa<UsingShadowDecl>(D))
1403 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1404
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001405 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001406 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001407 continue;
1408
John McCallda4458e2010-03-31 01:36:47 +00001409 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001410
1411 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1412 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001413 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001414 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001415 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001416 if (ObjectPtrConversions.size() == 1) {
1417 // We have a single conversion to a pointer-to-object type. Perform
1418 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001419 // TODO: don't redo the conversion calculation.
John McCallda4458e2010-03-31 01:36:47 +00001420 if (!PerformImplicitConversion(Ex,
1421 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001422 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001423 Type = Ex->getType();
1424 }
1425 }
1426 else if (ObjectPtrConversions.size() > 1) {
1427 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1428 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001429 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1430 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001431 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001432 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001433 }
1434
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001435 if (!Type->isPointerType())
1436 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1437 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001438
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001439 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001440 if (Pointee->isVoidType() && !isSFINAEContext()) {
1441 // The C++ standard bans deleting a pointer to a non-object type, which
1442 // effectively bans deletion of "void*". However, most compilers support
1443 // this, so we treat it as a warning unless we're in a SFINAE context.
1444 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1445 << Type << Ex->getSourceRange();
1446 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001447 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1448 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001449 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001450 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001451 PDiag(diag::warn_delete_incomplete)
1452 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001453 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001454
Douglas Gregor98496dc2009-09-29 21:38:53 +00001455 // C++ [expr.delete]p2:
1456 // [Note: a pointer to a const type can be the operand of a
1457 // delete-expression; it is not necessary to cast away the constness
1458 // (5.2.11) of the pointer expression before it is used as the operand
1459 // of the delete-expression. ]
1460 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1461 CastExpr::CK_NoOp);
1462
Anders Carlssona471db02009-08-16 20:29:29 +00001463 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1464 ArrayForm ? OO_Array_Delete : OO_Delete);
1465
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001466 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1467 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1468
1469 if (!UseGlobal &&
1470 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001471 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001472
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001473 if (!RD->hasTrivialDestructor())
Douglas Gregore71edda2010-07-01 22:47:18 +00001474 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump11289f42009-09-09 15:08:12 +00001475 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001476 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001477 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001478
Anders Carlssona471db02009-08-16 20:29:29 +00001479 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001480 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001481 DeclareGlobalNewDelete();
1482 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001483 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001484 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001485 OperatorDelete))
1486 return ExprError();
1487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
John McCall0f55a032010-04-20 02:18:25 +00001489 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1490
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001491 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001492 }
1493
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001494 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001495 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001496}
1497
Douglas Gregor633caca2009-11-23 23:44:04 +00001498/// \brief Check the use of the given variable as a C++ condition in an if,
1499/// while, do-while, or switch statement.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001500Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1501 SourceLocation StmtLoc,
1502 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001503 QualType T = ConditionVar->getType();
1504
1505 // C++ [stmt.select]p2:
1506 // The declarator shall not specify a function or an array.
1507 if (T->isFunctionType())
1508 return ExprError(Diag(ConditionVar->getLocation(),
1509 diag::err_invalid_use_of_function_type)
1510 << ConditionVar->getSourceRange());
1511 else if (T->isArrayType())
1512 return ExprError(Diag(ConditionVar->getLocation(),
1513 diag::err_invalid_use_of_array_type)
1514 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001515
Douglas Gregore60e41a2010-05-06 17:25:47 +00001516 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1517 ConditionVar->getLocation(),
1518 ConditionVar->getType().getNonReferenceType());
Douglas Gregorb412e172010-07-25 18:17:45 +00001519 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00001520 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001521
1522 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001523}
1524
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001525/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1526bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1527 // C++ 6.4p4:
1528 // The value of a condition that is an initialized declaration in a statement
1529 // other than a switch statement is the value of the declared variable
1530 // implicitly converted to type bool. If that conversion is ill-formed, the
1531 // program is ill-formed.
1532 // The value of a condition that is an expression is the value of the
1533 // expression, implicitly converted to bool.
1534 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001535 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001536}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001537
1538/// Helper function to determine whether this is the (deprecated) C++
1539/// conversion from a string literal to a pointer to non-const char or
1540/// non-const wchar_t (for narrow and wide string literals,
1541/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001542bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001543Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1544 // Look inside the implicit cast, if it exists.
1545 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1546 From = Cast->getSubExpr();
1547
1548 // A string literal (2.13.4) that is not a wide string literal can
1549 // be converted to an rvalue of type "pointer to char"; a wide
1550 // string literal can be converted to an rvalue of type "pointer
1551 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001552 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001553 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001554 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001555 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001556 // This conversion is considered only when there is an
1557 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001558 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001559 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1560 (!StrLit->isWide() &&
1561 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1562 ToPointeeType->getKind() == BuiltinType::Char_S))))
1563 return true;
1564 }
1565
1566 return false;
1567}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001568
Douglas Gregora4253922010-04-16 22:17:36 +00001569static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1570 SourceLocation CastLoc,
1571 QualType Ty,
1572 CastExpr::CastKind Kind,
1573 CXXMethodDecl *Method,
John McCallb268a282010-08-23 23:25:46 +00001574 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00001575 switch (Kind) {
1576 default: assert(0 && "Unhandled cast kind!");
1577 case CastExpr::CK_ConstructorConversion: {
John McCall37ad5512010-08-23 06:44:23 +00001578 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregora4253922010-04-16 22:17:36 +00001579
1580 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCall37ad5512010-08-23 06:44:23 +00001581 Sema::MultiExprArg(S, &From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00001582 CastLoc, ConstructorArgs))
1583 return S.ExprError();
1584
1585 Sema::OwningExprResult Result =
1586 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1587 move_arg(ConstructorArgs));
1588 if (Result.isInvalid())
1589 return S.ExprError();
1590
1591 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1592 }
1593
1594 case CastExpr::CK_UserDefinedConversion: {
1595 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1596
1597 // Create an implicit call expr that calls it.
1598 // FIXME: pass the FoundDecl for the user-defined conversion here
1599 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1600 return S.MaybeBindToTemporary(CE);
1601 }
1602 }
1603}
1604
Douglas Gregor5fb53972009-01-14 15:45:31 +00001605/// PerformImplicitConversion - Perform an implicit conversion of the
1606/// expression From to the type ToType using the pre-computed implicit
1607/// conversion sequence ICS. Returns true if there was an error, false
1608/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001609/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001610/// used in the error message.
1611bool
1612Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1613 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001614 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001615 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001616 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001617 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001618 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001619 return true;
1620 break;
1621
Anders Carlsson110b07b2009-09-15 06:28:28 +00001622 case ImplicitConversionSequence::UserDefinedConversion: {
1623
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001624 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1625 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001626 QualType BeforeToType;
1627 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001628 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001629
1630 // If the user-defined conversion is specified by a conversion function,
1631 // the initial standard conversion sequence converts the source type to
1632 // the implicit object parameter of the conversion function.
1633 BeforeToType = Context.getTagDeclType(Conv->getParent());
1634 } else if (const CXXConstructorDecl *Ctor =
1635 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001636 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001637 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001638 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001639 // If the user-defined conversion is specified by a constructor, the
1640 // initial standard conversion sequence converts the source type to the
1641 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001642 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1643 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001644 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001645 else
1646 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001647 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001648 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001649 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001650 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001651 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001652 return true;
1653 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001654
Anders Carlssone9766d52009-09-09 21:33:21 +00001655 OwningExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001656 = BuildCXXCastArgument(*this,
1657 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001658 ToType.getNonReferenceType(),
1659 CastKind, cast<CXXMethodDecl>(FD),
John McCallb268a282010-08-23 23:25:46 +00001660 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00001661
1662 if (CastArg.isInvalid())
1663 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001664
1665 From = CastArg.takeAs<Expr>();
1666
Eli Friedmane96f1d32009-11-27 04:41:50 +00001667 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001668 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001669 }
John McCall0d1da222010-01-12 00:44:57 +00001670
1671 case ImplicitConversionSequence::AmbiguousConversion:
1672 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1673 PDiag(diag::err_typecheck_ambiguous_condition)
1674 << From->getSourceRange());
1675 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001676
Douglas Gregor39c16d42008-10-24 04:54:22 +00001677 case ImplicitConversionSequence::EllipsisConversion:
1678 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001679 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001680
1681 case ImplicitConversionSequence::BadConversion:
1682 return true;
1683 }
1684
1685 // Everything went well.
1686 return false;
1687}
1688
1689/// PerformImplicitConversion - Perform an implicit conversion of the
1690/// expression From to the type ToType by following the standard
1691/// conversion sequence SCS. Returns true if there was an error, false
1692/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001693/// expression. Flavor is the context in which we're performing this
1694/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001695bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001696Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001697 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001698 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001699 // Overall FIXME: we are recomputing too many types here and doing far too
1700 // much extra work. What this means is that we need to keep track of more
1701 // information that is computed when we try the implicit conversion initially,
1702 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001703 QualType FromType = From->getType();
1704
Douglas Gregor2fe98832008-11-03 19:09:14 +00001705 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001706 // FIXME: When can ToType be a reference type?
1707 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001708 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00001709 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001710 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00001711 MultiExprArg(*this, &From, 1),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001712 /*FIXME:ConstructLoc*/SourceLocation(),
1713 ConstructorArgs))
1714 return true;
1715 OwningExprResult FromResult =
1716 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1717 ToType, SCS.CopyConstructor,
1718 move_arg(ConstructorArgs));
1719 if (FromResult.isInvalid())
1720 return true;
1721 From = FromResult.takeAs<Expr>();
1722 return false;
1723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724 OwningExprResult FromResult =
1725 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1726 ToType, SCS.CopyConstructor,
John McCall37ad5512010-08-23 06:44:23 +00001727 MultiExprArg(*this, &From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001728
Anders Carlsson6eb55572009-08-25 05:12:04 +00001729 if (FromResult.isInvalid())
1730 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001731
Anders Carlsson6eb55572009-08-25 05:12:04 +00001732 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001733 return false;
1734 }
1735
Douglas Gregor980fb162010-04-29 18:24:40 +00001736 // Resolve overloaded function references.
1737 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1738 DeclAccessPair Found;
1739 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1740 true, Found);
1741 if (!Fn)
1742 return true;
1743
1744 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1745 return true;
1746
1747 From = FixOverloadedFunctionReference(From, Found, Fn);
1748 FromType = From->getType();
1749 }
1750
Douglas Gregor39c16d42008-10-24 04:54:22 +00001751 // Perform the first implicit conversion.
1752 switch (SCS.First) {
1753 case ICK_Identity:
1754 case ICK_Lvalue_To_Rvalue:
1755 // Nothing to do.
1756 break;
1757
1758 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001759 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001760 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001761 break;
1762
1763 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001764 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001765 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001766 break;
1767
1768 default:
1769 assert(false && "Improper first standard conversion");
1770 break;
1771 }
1772
1773 // Perform the second implicit conversion
1774 switch (SCS.Second) {
1775 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001776 // If both sides are functions (or pointers/references to them), there could
1777 // be incompatible exception declarations.
1778 if (CheckExceptionSpecCompatibility(From, ToType))
1779 return true;
1780 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001781 break;
1782
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001783 case ICK_NoReturn_Adjustment:
1784 // If both sides are functions (or pointers/references to them), there could
1785 // be incompatible exception declarations.
1786 if (CheckExceptionSpecCompatibility(From, ToType))
1787 return true;
1788
1789 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1790 CastExpr::CK_NoOp);
1791 break;
1792
Douglas Gregor39c16d42008-10-24 04:54:22 +00001793 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001794 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001795 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1796 break;
1797
1798 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001799 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001800 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1801 break;
1802
1803 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001804 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001805 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1806 break;
1807
Douglas Gregor39c16d42008-10-24 04:54:22 +00001808 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00001809 if (ToType->isRealFloatingType())
Eli Friedman06ed2a52009-10-20 08:27:19 +00001810 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1811 else
1812 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1813 break;
1814
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001815 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001816 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001817 break;
1818
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001819 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001820 if (SCS.IncompatibleObjC) {
1821 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001822 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001823 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001824 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001825 << From->getSourceRange();
1826 }
1827
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001828
1829 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +00001830 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00001831 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001832 return true;
John McCallcf142162010-08-07 06:22:56 +00001833 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, &BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001834 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001835 }
1836
1837 case ICK_Pointer_Member: {
1838 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +00001839 CXXCastPath BasePath;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001840 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1841 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001842 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001843 if (CheckExceptionSpecCompatibility(From, ToType))
1844 return true;
John McCallcf142162010-08-07 06:22:56 +00001845 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, &BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001846 break;
1847 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001848 case ICK_Boolean_Conversion: {
1849 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1850 if (FromType->isMemberPointerType())
1851 Kind = CastExpr::CK_MemberPointerToBoolean;
1852
1853 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001854 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001855 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001856
Douglas Gregor88d292c2010-05-13 16:44:06 +00001857 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00001858 CXXCastPath BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001859 if (CheckDerivedToBaseConversion(From->getType(),
1860 ToType.getNonReferenceType(),
1861 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001862 From->getSourceRange(),
1863 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001864 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001865 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001866
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001867 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCallcf142162010-08-07 06:22:56 +00001868 CastExpr::CK_DerivedToBase, CastCategory(From),
1869 &BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001870 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001871 }
1872
Douglas Gregor46188682010-05-18 22:42:18 +00001873 case ICK_Vector_Conversion:
1874 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1875 break;
1876
1877 case ICK_Vector_Splat:
1878 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1879 break;
1880
1881 case ICK_Complex_Real:
1882 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1883 break;
1884
1885 case ICK_Lvalue_To_Rvalue:
1886 case ICK_Array_To_Pointer:
1887 case ICK_Function_To_Pointer:
1888 case ICK_Qualification:
1889 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001890 assert(false && "Improper second standard conversion");
1891 break;
1892 }
1893
1894 switch (SCS.Third) {
1895 case ICK_Identity:
1896 // Nothing to do.
1897 break;
1898
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001899 case ICK_Qualification: {
1900 // The qualification keeps the category of the inner expression, unless the
1901 // target type isn't a reference.
1902 ImplicitCastExpr::ResultCategory Category = ToType->isReferenceType() ?
1903 CastCategory(From) : ImplicitCastExpr::RValue;
Douglas Gregora8a089b2010-07-13 18:40:04 +00001904 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001905 CastExpr::CK_NoOp, Category);
Douglas Gregore489a7d2010-02-28 18:30:25 +00001906
1907 if (SCS.DeprecatedStringLiteralToCharPtr)
1908 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1909 << ToType.getNonReferenceType();
1910
Douglas Gregor39c16d42008-10-24 04:54:22 +00001911 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001912 }
1913
Douglas Gregor39c16d42008-10-24 04:54:22 +00001914 default:
Douglas Gregor46188682010-05-18 22:42:18 +00001915 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00001916 break;
1917 }
1918
1919 return false;
1920}
1921
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001922Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1923 SourceLocation KWLoc,
1924 SourceLocation LParen,
1925 TypeTy *Ty,
1926 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001927 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001928
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001929 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1930 // all traits except __is_class, __is_enum and __is_union require a the type
1931 // to be complete.
1932 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001933 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001934 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001935 return ExprError();
1936 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001937
1938 // There is no point in eagerly computing the value. The traits are designed
1939 // to be used from type trait templates, so Ty will be a template parameter
1940 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001941 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1942 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001943}
Sebastian Redl5822f082009-02-07 20:10:22 +00001944
1945QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001946 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001947 const char *OpSpelling = isIndirect ? "->*" : ".*";
1948 // C++ 5.5p2
1949 // The binary operator .* [p3: ->*] binds its second operand, which shall
1950 // be of type "pointer to member of T" (where T is a completely-defined
1951 // class type) [...]
1952 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001953 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001954 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001955 Diag(Loc, diag::err_bad_memptr_rhs)
1956 << OpSpelling << RType << rex->getSourceRange();
1957 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001958 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001959
Sebastian Redl5822f082009-02-07 20:10:22 +00001960 QualType Class(MemPtr->getClass(), 0);
1961
Sebastian Redlc72350e2010-04-10 10:14:54 +00001962 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1963 return QualType();
1964
Sebastian Redl5822f082009-02-07 20:10:22 +00001965 // C++ 5.5p2
1966 // [...] to its first operand, which shall be of class T or of a class of
1967 // which T is an unambiguous and accessible base class. [p3: a pointer to
1968 // such a class]
1969 QualType LType = lex->getType();
1970 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001971 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001972 LType = Ptr->getPointeeType().getNonReferenceType();
1973 else {
1974 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001975 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001976 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001977 return QualType();
1978 }
1979 }
1980
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001981 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00001982 // If we want to check the hierarchy, we need a complete type.
1983 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1984 << OpSpelling << (int)isIndirect)) {
1985 return QualType();
1986 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001987 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001988 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001989 // FIXME: Would it be useful to print full ambiguity paths, or is that
1990 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001991 if (!IsDerivedFrom(LType, Class, Paths) ||
1992 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1993 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001994 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001995 return QualType();
1996 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001997 // Cast LHS to type of use.
1998 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001999 ImplicitCastExpr::ResultCategory Category =
2000 isIndirect ? ImplicitCastExpr::RValue : CastCategory(lex);
2001
John McCallcf142162010-08-07 06:22:56 +00002002 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00002003 BuildBasePathArray(Paths, BasePath);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002004 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, Category,
John McCallcf142162010-08-07 06:22:56 +00002005 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00002006 }
2007
Douglas Gregor747eb782010-07-08 06:14:04 +00002008 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00002009 // Diagnose use of pointer-to-member type which when used as
2010 // the functional cast in a pointer-to-member expression.
2011 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2012 return QualType();
2013 }
Sebastian Redl5822f082009-02-07 20:10:22 +00002014 // C++ 5.5p2
2015 // The result is an object or a function of the type specified by the
2016 // second operand.
2017 // The cv qualifiers are the union of those in the pointer and the left side,
2018 // in accordance with 5.5p5 and 5.2.5.
2019 // FIXME: This returns a dereferenced member function pointer as a normal
2020 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00002021 // calling them. There's also a GCC extension to get a function pointer to the
2022 // thing, which is another complication, because this type - unlike the type
2023 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00002024 // argument.
2025 // We probably need a "MemberFunctionClosureType" or something like that.
2026 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002027 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00002028 return Result;
2029}
Sebastian Redl1a99f442009-04-16 17:51:27 +00002030
Sebastian Redl1a99f442009-04-16 17:51:27 +00002031/// \brief Try to convert a type to another according to C++0x 5.16p3.
2032///
2033/// This is part of the parameter validation for the ? operator. If either
2034/// value operand is a class type, the two operands are attempted to be
2035/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002036/// It returns true if the program is ill-formed and has already been diagnosed
2037/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002038static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2039 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002040 bool &HaveConversion,
2041 QualType &ToType) {
2042 HaveConversion = false;
2043 ToType = To->getType();
2044
2045 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2046 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002047 // C++0x 5.16p3
2048 // The process for determining whether an operand expression E1 of type T1
2049 // can be converted to match an operand expression E2 of type T2 is defined
2050 // as follows:
2051 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00002052 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2053 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002054 // E1 can be converted to match E2 if E1 can be implicitly converted to
2055 // type "lvalue reference to T2", subject to the constraint that in the
2056 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002057 QualType T = Self.Context.getLValueReferenceType(ToType);
2058 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2059
2060 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2061 if (InitSeq.isDirectReferenceBinding()) {
2062 ToType = T;
2063 HaveConversion = true;
2064 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002065 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002066
2067 if (InitSeq.isAmbiguous())
2068 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002069 }
John McCall65eb8792010-02-25 01:37:24 +00002070
Sebastian Redl1a99f442009-04-16 17:51:27 +00002071 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2072 // -- if E1 and E2 have class type, and the underlying class types are
2073 // the same or one is a base class of the other:
2074 QualType FTy = From->getType();
2075 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 const RecordType *FRec = FTy->getAs<RecordType>();
2077 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002078 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2079 Self.IsDerivedFrom(FTy, TTy);
2080 if (FRec && TRec &&
2081 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002082 // E1 can be converted to match E2 if the class of T2 is the
2083 // same type as, or a base class of, the class of T1, and
2084 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002085 if (FRec == TRec || FDerivedFromT) {
2086 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002087 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2088 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2089 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2090 HaveConversion = true;
2091 return false;
2092 }
2093
2094 if (InitSeq.isAmbiguous())
2095 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2096 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002097 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002098
2099 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002100 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002101
2102 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2103 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002104 // if E2 were converted to an rvalue (or the type it has, if E2 is
2105 // an rvalue).
2106 //
2107 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2108 // to the array-to-pointer or function-to-pointer conversions.
2109 if (!TTy->getAs<TagType>())
2110 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002111
2112 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2113 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2114 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2115 ToType = TTy;
2116 if (InitSeq.isAmbiguous())
2117 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2118
Sebastian Redl1a99f442009-04-16 17:51:27 +00002119 return false;
2120}
2121
2122/// \brief Try to find a common type for two according to C++0x 5.16p5.
2123///
2124/// This is part of the parameter validation for the ? operator. If either
2125/// value operand is a class type, overload resolution is used to find a
2126/// conversion to a common type.
2127static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2128 SourceLocation Loc) {
2129 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002130 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002131 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002132
2133 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002134 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002135 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002136 // We found a match. Perform the conversions on the arguments and move on.
2137 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002138 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002139 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002140 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002141 break;
2142 return false;
2143
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002144 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002145 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2146 << LHS->getType() << RHS->getType()
2147 << LHS->getSourceRange() << RHS->getSourceRange();
2148 return true;
2149
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002150 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002151 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2152 << LHS->getType() << RHS->getType()
2153 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002154 // FIXME: Print the possible common types by printing the return types of
2155 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002156 break;
2157
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002158 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002159 assert(false && "Conditional operator has only built-in overloads");
2160 break;
2161 }
2162 return true;
2163}
2164
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002165/// \brief Perform an "extended" implicit conversion as returned by
2166/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002167static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2168 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2169 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2170 SourceLocation());
2171 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2172 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00002173 Sema::MultiExprArg(Self, &E, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00002174 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002175 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002176
2177 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002178 return false;
2179}
2180
Sebastian Redl1a99f442009-04-16 17:51:27 +00002181/// \brief Check the operands of ?: under C++ semantics.
2182///
2183/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2184/// extension. In this case, LHS == Cond. (But they're not aliases.)
2185QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2186 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002187 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2188 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002189
2190 // C++0x 5.16p1
2191 // The first expression is contextually converted to bool.
2192 if (!Cond->isTypeDependent()) {
2193 if (CheckCXXBooleanCondition(Cond))
2194 return QualType();
2195 }
2196
2197 // Either of the arguments dependent?
2198 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2199 return Context.DependentTy;
2200
2201 // C++0x 5.16p2
2202 // If either the second or the third operand has type (cv) void, ...
2203 QualType LTy = LHS->getType();
2204 QualType RTy = RHS->getType();
2205 bool LVoid = LTy->isVoidType();
2206 bool RVoid = RTy->isVoidType();
2207 if (LVoid || RVoid) {
2208 // ... then the [l2r] conversions are performed on the second and third
2209 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002210 DefaultFunctionArrayLvalueConversion(LHS);
2211 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002212 LTy = LHS->getType();
2213 RTy = RHS->getType();
2214
2215 // ... and one of the following shall hold:
2216 // -- The second or the third operand (but not both) is a throw-
2217 // expression; the result is of the type of the other and is an rvalue.
2218 bool LThrow = isa<CXXThrowExpr>(LHS);
2219 bool RThrow = isa<CXXThrowExpr>(RHS);
2220 if (LThrow && !RThrow)
2221 return RTy;
2222 if (RThrow && !LThrow)
2223 return LTy;
2224
2225 // -- Both the second and third operands have type void; the result is of
2226 // type void and is an rvalue.
2227 if (LVoid && RVoid)
2228 return Context.VoidTy;
2229
2230 // Neither holds, error.
2231 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2232 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2233 << LHS->getSourceRange() << RHS->getSourceRange();
2234 return QualType();
2235 }
2236
2237 // Neither is void.
2238
2239 // C++0x 5.16p3
2240 // Otherwise, if the second and third operand have different types, and
2241 // either has (cv) class type, and attempt is made to convert each of those
2242 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002243 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002244 (LTy->isRecordType() || RTy->isRecordType())) {
2245 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2246 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002247 QualType L2RType, R2LType;
2248 bool HaveL2R, HaveR2L;
2249 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002250 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002251 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002252 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002253
Sebastian Redl1a99f442009-04-16 17:51:27 +00002254 // If both can be converted, [...] the program is ill-formed.
2255 if (HaveL2R && HaveR2L) {
2256 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2257 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2258 return QualType();
2259 }
2260
2261 // If exactly one conversion is possible, that conversion is applied to
2262 // the chosen operand and the converted operands are used in place of the
2263 // original operands for the remainder of this section.
2264 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002265 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002266 return QualType();
2267 LTy = LHS->getType();
2268 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002269 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002270 return QualType();
2271 RTy = RHS->getType();
2272 }
2273 }
2274
2275 // C++0x 5.16p4
2276 // If the second and third operands are lvalues and have the same type,
2277 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002278 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002279 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2280 RHS->isLvalue(Context) == Expr::LV_Valid)
2281 return LTy;
2282
2283 // C++0x 5.16p5
2284 // Otherwise, the result is an rvalue. If the second and third operands
2285 // do not have the same type, and either has (cv) class type, ...
2286 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2287 // ... overload resolution is used to determine the conversions (if any)
2288 // to be applied to the operands. If the overload resolution fails, the
2289 // program is ill-formed.
2290 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2291 return QualType();
2292 }
2293
2294 // C++0x 5.16p6
2295 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2296 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002297 DefaultFunctionArrayLvalueConversion(LHS);
2298 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002299 LTy = LHS->getType();
2300 RTy = RHS->getType();
2301
2302 // After those conversions, one of the following shall hold:
2303 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002304 // is of that type. If the operands have class type, the result
2305 // is a prvalue temporary of the result type, which is
2306 // copy-initialized from either the second operand or the third
2307 // operand depending on the value of the first operand.
2308 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2309 if (LTy->isRecordType()) {
2310 // The operands have class type. Make a temporary copy.
2311 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2312 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2313 SourceLocation(),
2314 Owned(LHS));
2315 if (LHSCopy.isInvalid())
2316 return QualType();
2317
2318 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2319 SourceLocation(),
2320 Owned(RHS));
2321 if (RHSCopy.isInvalid())
2322 return QualType();
2323
2324 LHS = LHSCopy.takeAs<Expr>();
2325 RHS = RHSCopy.takeAs<Expr>();
2326 }
2327
Sebastian Redl1a99f442009-04-16 17:51:27 +00002328 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002329 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002330
Douglas Gregor46188682010-05-18 22:42:18 +00002331 // Extension: conditional operator involving vector types.
2332 if (LTy->isVectorType() || RTy->isVectorType())
2333 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2334
Sebastian Redl1a99f442009-04-16 17:51:27 +00002335 // -- The second and third operands have arithmetic or enumeration type;
2336 // the usual arithmetic conversions are performed to bring them to a
2337 // common type, and the result is of that type.
2338 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2339 UsualArithmeticConversions(LHS, RHS);
2340 return LHS->getType();
2341 }
2342
2343 // -- The second and third operands have pointer type, or one has pointer
2344 // type and the other is a null pointer constant; pointer conversions
2345 // and qualification conversions are performed to bring them to their
2346 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002347 // -- The second and third operands have pointer to member type, or one has
2348 // pointer to member type and the other is a null pointer constant;
2349 // pointer to member conversions and qualification conversions are
2350 // performed to bring them to a common type, whose cv-qualification
2351 // shall match the cv-qualification of either the second or the third
2352 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002353 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002354 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002355 isSFINAEContext()? 0 : &NonStandardCompositeType);
2356 if (!Composite.isNull()) {
2357 if (NonStandardCompositeType)
2358 Diag(QuestionLoc,
2359 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2360 << LTy << RTy << Composite
2361 << LHS->getSourceRange() << RHS->getSourceRange();
2362
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002363 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002364 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002365
Douglas Gregor697a3912010-04-01 22:47:07 +00002366 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002367 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2368 if (!Composite.isNull())
2369 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002370
Sebastian Redl1a99f442009-04-16 17:51:27 +00002371 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2372 << LHS->getType() << RHS->getType()
2373 << LHS->getSourceRange() << RHS->getSourceRange();
2374 return QualType();
2375}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002376
2377/// \brief Find a merged pointer type and convert the two expressions to it.
2378///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002379/// This finds the composite pointer type (or member pointer type) for @p E1
2380/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2381/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002382/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002383///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002384/// \param Loc The location of the operator requiring these two expressions to
2385/// be converted to the composite pointer type.
2386///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002387/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2388/// a non-standard (but still sane) composite type to which both expressions
2389/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2390/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002391QualType Sema::FindCompositePointerType(SourceLocation Loc,
2392 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002393 bool *NonStandardCompositeType) {
2394 if (NonStandardCompositeType)
2395 *NonStandardCompositeType = false;
2396
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002397 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2398 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002399
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002400 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2401 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002402 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002403
2404 // C++0x 5.9p2
2405 // Pointer conversions and qualification conversions are performed on
2406 // pointer operands to bring them to their composite pointer type. If
2407 // one operand is a null pointer constant, the composite pointer type is
2408 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002409 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002410 if (T2->isMemberPointerType())
2411 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2412 else
2413 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002414 return T2;
2415 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002416 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002417 if (T1->isMemberPointerType())
2418 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2419 else
2420 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002421 return T1;
2422 }
Mike Stump11289f42009-09-09 15:08:12 +00002423
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002424 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002425 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2426 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002427 return QualType();
2428
2429 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2430 // the other has type "pointer to cv2 T" and the composite pointer type is
2431 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2432 // Otherwise, the composite pointer type is a pointer type similar to the
2433 // type of one of the operands, with a cv-qualification signature that is
2434 // the union of the cv-qualification signatures of the operand types.
2435 // In practice, the first part here is redundant; it's subsumed by the second.
2436 // What we do here is, we build the two possible composite types, and try the
2437 // conversions in both directions. If only one works, or if the two composite
2438 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002439 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002440 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2441 QualifierVector QualifierUnion;
2442 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2443 ContainingClassVector;
2444 ContainingClassVector MemberOfClass;
2445 QualType Composite1 = Context.getCanonicalType(T1),
2446 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002447 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002448 do {
2449 const PointerType *Ptr1, *Ptr2;
2450 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2451 (Ptr2 = Composite2->getAs<PointerType>())) {
2452 Composite1 = Ptr1->getPointeeType();
2453 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002454
2455 // If we're allowed to create a non-standard composite type, keep track
2456 // of where we need to fill in additional 'const' qualifiers.
2457 if (NonStandardCompositeType &&
2458 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2459 NeedConstBefore = QualifierUnion.size();
2460
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002461 QualifierUnion.push_back(
2462 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2463 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2464 continue;
2465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002467 const MemberPointerType *MemPtr1, *MemPtr2;
2468 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2469 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2470 Composite1 = MemPtr1->getPointeeType();
2471 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002472
2473 // If we're allowed to create a non-standard composite type, keep track
2474 // of where we need to fill in additional 'const' qualifiers.
2475 if (NonStandardCompositeType &&
2476 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2477 NeedConstBefore = QualifierUnion.size();
2478
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002479 QualifierUnion.push_back(
2480 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2481 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2482 MemPtr2->getClass()));
2483 continue;
2484 }
Mike Stump11289f42009-09-09 15:08:12 +00002485
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002486 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002487
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002488 // Cannot unwrap any more types.
2489 break;
2490 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002491
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002492 if (NeedConstBefore && NonStandardCompositeType) {
2493 // Extension: Add 'const' to qualifiers that come before the first qualifier
2494 // mismatch, so that our (non-standard!) composite type meets the
2495 // requirements of C++ [conv.qual]p4 bullet 3.
2496 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2497 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2498 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2499 *NonStandardCompositeType = true;
2500 }
2501 }
2502 }
2503
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002504 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002505 ContainingClassVector::reverse_iterator MOC
2506 = MemberOfClass.rbegin();
2507 for (QualifierVector::reverse_iterator
2508 I = QualifierUnion.rbegin(),
2509 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002510 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002511 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002512 if (MOC->first && MOC->second) {
2513 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002514 Composite1 = Context.getMemberPointerType(
2515 Context.getQualifiedType(Composite1, Quals),
2516 MOC->first);
2517 Composite2 = Context.getMemberPointerType(
2518 Context.getQualifiedType(Composite2, Quals),
2519 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002520 } else {
2521 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002522 Composite1
2523 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2524 Composite2
2525 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002526 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002527 }
2528
Douglas Gregor19175ff2010-04-16 23:20:25 +00002529 // Try to convert to the first composite pointer type.
2530 InitializedEntity Entity1
2531 = InitializedEntity::InitializeTemporary(Composite1);
2532 InitializationKind Kind
2533 = InitializationKind::CreateCopy(Loc, SourceLocation());
2534 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2535 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00002536
Douglas Gregor19175ff2010-04-16 23:20:25 +00002537 if (E1ToC1 && E2ToC1) {
2538 // Conversion to Composite1 is viable.
2539 if (!Context.hasSameType(Composite1, Composite2)) {
2540 // Composite2 is a different type from Composite1. Check whether
2541 // Composite2 is also viable.
2542 InitializedEntity Entity2
2543 = InitializedEntity::InitializeTemporary(Composite2);
2544 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2545 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2546 if (E1ToC2 && E2ToC2) {
2547 // Both Composite1 and Composite2 are viable and are different;
2548 // this is an ambiguity.
2549 return QualType();
2550 }
2551 }
2552
2553 // Convert E1 to Composite1
2554 OwningExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00002555 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00002556 if (E1Result.isInvalid())
2557 return QualType();
2558 E1 = E1Result.takeAs<Expr>();
2559
2560 // Convert E2 to Composite1
2561 OwningExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00002562 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00002563 if (E2Result.isInvalid())
2564 return QualType();
2565 E2 = E2Result.takeAs<Expr>();
2566
2567 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002568 }
2569
Douglas Gregor19175ff2010-04-16 23:20:25 +00002570 // Check whether Composite2 is viable.
2571 InitializedEntity Entity2
2572 = InitializedEntity::InitializeTemporary(Composite2);
2573 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2574 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2575 if (!E1ToC2 || !E2ToC2)
2576 return QualType();
2577
2578 // Convert E1 to Composite2
2579 OwningExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00002580 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00002581 if (E1Result.isInvalid())
2582 return QualType();
2583 E1 = E1Result.takeAs<Expr>();
2584
2585 // Convert E2 to Composite2
2586 OwningExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00002587 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00002588 if (E2Result.isInvalid())
2589 return QualType();
2590 E2 = E2Result.takeAs<Expr>();
2591
2592 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002593}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002594
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002595Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002596 if (!Context.getLangOptions().CPlusPlus)
2597 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002598
Douglas Gregor363b1512009-12-24 18:51:59 +00002599 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2600
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002601 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002602 if (!RT)
2603 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002604
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002605 // If this is the result of a call or an Objective-C message send expression,
2606 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002607 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002608 if (CE->getCallReturnType()->isReferenceType())
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002609 return Owned(E);
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002610 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2611 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2612 if (MD->getResultType()->isReferenceType())
2613 return Owned(E);
2614 }
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002615 }
John McCall67da35c2010-02-04 22:26:26 +00002616
2617 // That should be enough to guarantee that this type is complete.
2618 // If it has a trivial destructor, we can avoid the extra copy.
2619 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00002620 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00002621 return Owned(E);
2622
Douglas Gregore71edda2010-07-01 22:47:18 +00002623 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002624 ExprTemporaries.push_back(Temp);
Douglas Gregore71edda2010-07-01 22:47:18 +00002625 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002626 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002627 CheckDestructorAccess(E->getExprLoc(), Destructor,
2628 PDiag(diag::err_access_dtor_temp)
2629 << E->getType());
2630 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002631 // FIXME: Add the temporary to the temporaries vector.
2632 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2633}
2634
Anders Carlsson6e997b22009-12-15 20:51:39 +00002635Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002636 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002637
John McCallcc7e5bf2010-05-06 08:58:33 +00002638 // Check any implicit conversions within the expression.
2639 CheckImplicitConversions(SubExpr);
2640
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002641 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2642 assert(ExprTemporaries.size() >= FirstTemporary);
2643 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002644 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002645
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002646 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002647 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002648 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002649 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2650 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002651
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002652 return E;
2653}
2654
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002655Sema::OwningExprResult
2656Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2657 if (SubExpr.isInvalid())
2658 return ExprError();
2659
2660 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2661}
2662
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002663FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2664 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2665 assert(ExprTemporaries.size() >= FirstTemporary);
2666
2667 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2668 CXXTemporary **Temporaries =
2669 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2670
2671 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2672
2673 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2674 ExprTemporaries.end());
2675
2676 return E;
2677}
2678
Mike Stump11289f42009-09-09 15:08:12 +00002679Sema::OwningExprResult
John McCallb268a282010-08-23 23:25:46 +00002680Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002681 tok::TokenKind OpKind, TypeTy *&ObjectType,
2682 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002683 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCallb268a282010-08-23 23:25:46 +00002684 OwningExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2685 if (Result.isInvalid()) return ExprError();
2686 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00002687
John McCallb268a282010-08-23 23:25:46 +00002688 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002689 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002690 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002691 // If we have a pointer to a dependent type and are using the -> operator,
2692 // the object type is the type that the pointer points to. We might still
2693 // have enough information about that type to do something useful.
2694 if (OpKind == tok::arrow)
2695 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2696 BaseType = Ptr->getPointeeType();
2697
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002698 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002699 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00002700 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002701 }
Mike Stump11289f42009-09-09 15:08:12 +00002702
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002703 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002704 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002705 // returned, with the original second operand.
2706 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002707 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002708 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002709 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002710 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002711
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002712 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00002713 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
2714 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002715 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00002716 Base = Result.get();
2717 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002718 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00002719 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00002720 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002721 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002722 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002723 for (unsigned i = 0; i < Locations.size(); i++)
2724 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002725 return ExprError();
2726 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
Douglas Gregore4f764f2009-11-20 19:58:21 +00002729 if (BaseType->isPointerType())
2730 BaseType = BaseType->getPointeeType();
2731 }
Mike Stump11289f42009-09-09 15:08:12 +00002732
2733 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002734 // vector types or Objective-C interfaces. Just return early and let
2735 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002736 if (!BaseType->isRecordType()) {
2737 // C++ [basic.lookup.classref]p2:
2738 // [...] If the type of the object expression is of pointer to scalar
2739 // type, the unqualified-id is looked up in the context of the complete
2740 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002741 //
2742 // This also indicates that we should be parsing a
2743 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002744 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002745 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00002746 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002747 }
Mike Stump11289f42009-09-09 15:08:12 +00002748
Douglas Gregor3fad6172009-11-17 05:17:33 +00002749 // The object type must be complete (or dependent).
2750 if (!BaseType->isDependentType() &&
2751 RequireCompleteType(OpLoc, BaseType,
2752 PDiag(diag::err_incomplete_member_access)))
2753 return ExprError();
2754
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002755 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002756 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002757 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002758 // type C (or of pointer to a class type C), the unqualified-id is looked
2759 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002760 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002761 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002762}
2763
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002764Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00002765 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002766 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00002767 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
2768 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00002769 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002770
2771 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00002772 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002773 /*LPLoc*/ ExpectedLParenLoc,
2774 Sema::MultiExprArg(*this, 0, 0),
2775 /*CommaLocs*/ 0,
2776 /*RPLoc*/ ExpectedLParenLoc);
2777}
Douglas Gregore610ada2010-02-24 18:44:31 +00002778
John McCallb268a282010-08-23 23:25:46 +00002779Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002780 SourceLocation OpLoc,
2781 tok::TokenKind OpKind,
2782 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002783 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002784 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002785 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002786 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002787 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002788 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002789
2790 // C++ [expr.pseudo]p2:
2791 // The left-hand side of the dot operator shall be of scalar type. The
2792 // left-hand side of the arrow operator shall be of pointer to scalar type.
2793 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00002794 QualType ObjectType = Base->getType();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002795 if (OpKind == tok::arrow) {
2796 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2797 ObjectType = Ptr->getPointeeType();
John McCallb268a282010-08-23 23:25:46 +00002798 } else if (!Base->isTypeDependent()) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002799 // The user wrote "p->" when she probably meant "p."; fix it.
2800 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2801 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002802 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002803 if (isSFINAEContext())
2804 return ExprError();
2805
2806 OpKind = tok::period;
2807 }
2808 }
2809
2810 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2811 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00002812 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002813 return ExprError();
2814 }
2815
2816 // C++ [expr.pseudo]p2:
2817 // [...] The cv-unqualified versions of the object type and of the type
2818 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002819 if (DestructedTypeInfo) {
2820 QualType DestructedType = DestructedTypeInfo->getType();
2821 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002822 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002823 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2824 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2825 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00002826 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002827 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002828
2829 // Recover by setting the destructed type to the object type.
2830 DestructedType = ObjectType;
2831 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2832 DestructedTypeStart);
2833 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2834 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002835 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002836
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002837 // C++ [expr.pseudo]p2:
2838 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2839 // form
2840 //
2841 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2842 //
2843 // shall designate the same scalar type.
2844 if (ScopeTypeInfo) {
2845 QualType ScopeType = ScopeTypeInfo->getType();
2846 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00002847 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002848
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002849 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002850 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00002851 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002852 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002853
2854 ScopeType = QualType();
2855 ScopeTypeInfo = 0;
2856 }
2857 }
2858
John McCallb268a282010-08-23 23:25:46 +00002859 Expr *Result
2860 = new (Context) CXXPseudoDestructorExpr(Context, Base,
2861 OpKind == tok::arrow, OpLoc,
2862 SS.getScopeRep(), SS.getRange(),
2863 ScopeTypeInfo,
2864 CCLoc,
2865 TildeLoc,
2866 Destructed);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002867
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002868 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00002869 return Owned(Result);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002870
John McCallb268a282010-08-23 23:25:46 +00002871 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002872}
2873
John McCallb268a282010-08-23 23:25:46 +00002874Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002875 SourceLocation OpLoc,
2876 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002877 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002878 UnqualifiedId &FirstTypeName,
2879 SourceLocation CCLoc,
2880 SourceLocation TildeLoc,
2881 UnqualifiedId &SecondTypeName,
2882 bool HasTrailingLParen) {
2883 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2884 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2885 "Invalid first type name in pseudo-destructor");
2886 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2887 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2888 "Invalid second type name in pseudo-destructor");
2889
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002890 // C++ [expr.pseudo]p2:
2891 // The left-hand side of the dot operator shall be of scalar type. The
2892 // left-hand side of the arrow operator shall be of pointer to scalar type.
2893 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00002894 QualType ObjectType = Base->getType();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002895 if (OpKind == tok::arrow) {
2896 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2897 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002898 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002899 // The user wrote "p->" when she probably meant "p."; fix it.
2900 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002901 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002902 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002903 if (isSFINAEContext())
2904 return ExprError();
2905
2906 OpKind = tok::period;
2907 }
2908 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002909
2910 // Compute the object type that we should use for name lookup purposes. Only
2911 // record types and dependent types matter.
2912 void *ObjectTypePtrForLookup = 0;
2913 if (!SS.isSet()) {
Gabor Greif2cd6c7b2010-06-17 11:29:31 +00002914 ObjectTypePtrForLookup = const_cast<RecordType*>(
2915 ObjectType->getAs<RecordType>());
Douglas Gregor678f90d2010-02-25 01:56:36 +00002916 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2917 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2918 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002919
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002920 // Convert the name of the type being destructed (following the ~) into a
2921 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002922 QualType DestructedType;
2923 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002924 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002925 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2926 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2927 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002928 S, &SS, true, ObjectTypePtrForLookup);
2929 if (!T &&
2930 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2931 (!SS.isSet() && ObjectType->isDependentType()))) {
2932 // The name of the type being destroyed is a dependent name, and we
2933 // couldn't find anything useful in scope. Just store the identifier and
2934 // it's location, and we'll perform (qualified) name lookup again at
2935 // template instantiation time.
2936 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2937 SecondTypeName.StartLocation);
2938 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002939 Diag(SecondTypeName.StartLocation,
2940 diag::err_pseudo_dtor_destructor_non_type)
2941 << SecondTypeName.Identifier << ObjectType;
2942 if (isSFINAEContext())
2943 return ExprError();
2944
2945 // Recover by assuming we had the right type all along.
2946 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002947 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002948 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002949 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002950 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002951 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002952 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2953 TemplateId->getTemplateArgs(),
2954 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00002955 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002956 TemplateId->TemplateNameLoc,
2957 TemplateId->LAngleLoc,
2958 TemplateArgsPtr,
2959 TemplateId->RAngleLoc);
2960 if (T.isInvalid() || !T.get()) {
2961 // Recover by assuming we had the right type all along.
2962 DestructedType = ObjectType;
2963 } else
2964 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002965 }
2966
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002967 // If we've performed some kind of recovery, (re-)build the type source
2968 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002969 if (!DestructedType.isNull()) {
2970 if (!DestructedTypeInfo)
2971 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002972 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002973 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2974 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002975
2976 // Convert the name of the scope type (the type prior to '::') into a type.
2977 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002978 QualType ScopeType;
2979 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2980 FirstTypeName.Identifier) {
2981 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2982 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2983 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002984 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002985 if (!T) {
2986 Diag(FirstTypeName.StartLocation,
2987 diag::err_pseudo_dtor_destructor_non_type)
2988 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002989
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002990 if (isSFINAEContext())
2991 return ExprError();
2992
2993 // Just drop this type. It's unnecessary anyway.
2994 ScopeType = QualType();
2995 } else
2996 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002997 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002998 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002999 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003000 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3001 TemplateId->getTemplateArgs(),
3002 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00003003 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003004 TemplateId->TemplateNameLoc,
3005 TemplateId->LAngleLoc,
3006 TemplateArgsPtr,
3007 TemplateId->RAngleLoc);
3008 if (T.isInvalid() || !T.get()) {
3009 // Recover by dropping this type.
3010 ScopeType = QualType();
3011 } else
3012 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003013 }
3014 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00003015
3016 if (!ScopeType.isNull() && !ScopeTypeInfo)
3017 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3018 FirstTypeName.StartLocation);
3019
3020
John McCallb268a282010-08-23 23:25:46 +00003021 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003022 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003023 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00003024}
3025
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003026CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00003027 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003028 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00003029 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3030 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00003031 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3032
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003033 MemberExpr *ME =
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003034 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003035 SourceLocation(), Method->getType());
Douglas Gregor603d81b2010-07-13 08:18:22 +00003036 QualType ResultType = Method->getCallResultType();
Douglas Gregor27381f32009-11-23 12:27:39 +00003037 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3038 CXXMemberCallExpr *CE =
3039 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3040 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003041 return CE;
3042}
3043
John McCallb268a282010-08-23 23:25:46 +00003044Sema::OwningExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
3045 if (!FullExpr) return ExprError();
3046 return MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00003047}