blob: e9fb26942c9b612521f2f70058e3b0e496ace40c [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"
John McCallde6836a2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000021#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000022#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000024#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000028#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000029using namespace clang;
30
John McCallba7bf592010-08-24 05:47:05 +000031ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
32 IdentifierInfo &II,
33 SourceLocation NameLoc,
34 Scope *S, CXXScopeSpec &SS,
35 ParsedType ObjectTypePtr,
36 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000037 // Determine where to perform name lookup.
38
39 // FIXME: This area of the standard is very messy, and the current
40 // wording is rather unclear about which scopes we search for the
41 // destructor name; see core issues 399 and 555. Issue 399 in
42 // particular shows where the current description of destructor name
43 // lookup is completely out of line with existing practice, e.g.,
44 // this appears to be ill-formed:
45 //
46 // namespace N {
47 // template <typename T> struct S {
48 // ~S();
49 // };
50 // }
51 //
52 // void f(N::S<int>* s) {
53 // s->N::S<int>::~S();
54 // }
55 //
Douglas Gregor46841e12010-02-23 00:15:22 +000056 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +000057 // For this reason, we're currently only doing the C++03 version of this
58 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +000059 QualType SearchType;
60 DeclContext *LookupCtx = 0;
61 bool isDependent = false;
62 bool LookInScope = false;
63
64 // If we have an object type, it's because we are in a
65 // pseudo-destructor-expression or a member access expression, and
66 // we know what type we're looking for.
67 if (ObjectTypePtr)
68 SearchType = GetTypeFromParser(ObjectTypePtr);
69
70 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000071 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
72
73 bool AlreadySearched = false;
74 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000075 // C++ [basic.lookup.qual]p6:
76 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
77 // the type-names are looked up as types in the scope designated by the
78 // nested-name-specifier. In a qualified-id of the form:
79 //
80 // ::[opt] nested-name-specifier ̃ class-name
81 //
82 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000083 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000084 //
Sebastian Redla771d222010-07-07 23:17:38 +000085 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000086 //
Sebastian Redla771d222010-07-07 23:17:38 +000087 // the class-names are looked up as types in the scope designated by
88 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000089 //
Sebastian Redla771d222010-07-07 23:17:38 +000090 // Here, we check the first case (completely) and determine whether the
91 // code below is permitted to look at the prefix of the
92 // nested-name-specifier.
93 DeclContext *DC = computeDeclContext(SS, EnteringContext);
94 if (DC && DC->isFileContext()) {
95 AlreadySearched = true;
96 LookupCtx = DC;
97 isDependent = false;
98 } else if (DC && isa<CXXRecordDecl>(DC))
99 LookAtPrefix = false;
100
101 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000102 NestedNameSpecifier *Prefix = 0;
103 if (AlreadySearched) {
104 // Nothing left to do.
105 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
106 CXXScopeSpec PrefixSS;
107 PrefixSS.setScopeRep(Prefix);
108 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
109 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000110 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000111 LookupCtx = computeDeclContext(SearchType);
112 isDependent = SearchType->isDependentType();
113 } else {
114 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000115 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000116 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000117
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000118 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000119 } else if (ObjectTypePtr) {
120 // C++ [basic.lookup.classref]p3:
121 // If the unqualified-id is ~type-name, the type-name is looked up
122 // in the context of the entire postfix-expression. If the type T
123 // of the object expression is of a class type C, the type-name is
124 // also looked up in the scope of class C. At least one of the
125 // lookups shall find a name that refers to (possibly
126 // cv-qualified) T.
127 LookupCtx = computeDeclContext(SearchType);
128 isDependent = SearchType->isDependentType();
129 assert((isDependent || !SearchType->isIncompleteType()) &&
130 "Caller should have completed object type");
131
132 LookInScope = true;
133 } else {
134 // Perform lookup into the current scope (only).
135 LookInScope = true;
136 }
137
138 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
139 for (unsigned Step = 0; Step != 2; ++Step) {
140 // Look for the name first in the computed lookup context (if we
141 // have one) and, if that fails to find a match, in the sope (if
142 // we're allowed to look there).
143 Found.clear();
144 if (Step == 0 && LookupCtx)
145 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000146 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000147 LookupName(Found, S);
148 else
149 continue;
150
151 // FIXME: Should we be suppressing ambiguities here?
152 if (Found.isAmbiguous())
John McCallba7bf592010-08-24 05:47:05 +0000153 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000154
155 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
156 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000157
158 if (SearchType.isNull() || SearchType->isDependentType() ||
159 Context.hasSameUnqualifiedType(T, SearchType)) {
160 // We found our type!
161
John McCallba7bf592010-08-24 05:47:05 +0000162 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000163 }
164 }
165
166 // If the name that we found is a class template name, and it is
167 // the same name as the template name in the last part of the
168 // nested-name-specifier (if present) or the object type, then
169 // this is the destructor for that class.
170 // FIXME: This is a workaround until we get real drafting for core
171 // issue 399, for which there isn't even an obvious direction.
172 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
173 QualType MemberOfType;
174 if (SS.isSet()) {
175 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
176 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000177 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
178 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000179 }
180 }
181 if (MemberOfType.isNull())
182 MemberOfType = SearchType;
183
184 if (MemberOfType.isNull())
185 continue;
186
187 // We're referring into a class template specialization. If the
188 // class template we found is the same as the template being
189 // specialized, we found what we are looking for.
190 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
191 if (ClassTemplateSpecializationDecl *Spec
192 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
193 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
194 Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000195 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000196 }
197
198 continue;
199 }
200
201 // We're referring to an unresolved class template
202 // specialization. Determine whether we class template we found
203 // is the same as the template being specialized or, if we don't
204 // know which template is being specialized, that it at least
205 // has the same name.
206 if (const TemplateSpecializationType *SpecType
207 = MemberOfType->getAs<TemplateSpecializationType>()) {
208 TemplateName SpecName = SpecType->getTemplateName();
209
210 // The class template we found is the same template being
211 // specialized.
212 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
213 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000214 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000215
216 continue;
217 }
218
219 // The class template we found has the same name as the
220 // (dependent) template name being specialized.
221 if (DependentTemplateName *DepTemplate
222 = SpecName.getAsDependentTemplateName()) {
223 if (DepTemplate->isIdentifier() &&
224 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000225 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000226
227 continue;
228 }
229 }
230 }
231 }
232
233 if (isDependent) {
234 // We didn't find our type, but that's okay: it's dependent
235 // anyway.
236 NestedNameSpecifier *NNS = 0;
237 SourceRange Range;
238 if (SS.isSet()) {
239 NNS = (NestedNameSpecifier *)SS.getScopeRep();
240 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
241 } else {
242 NNS = NestedNameSpecifier::Create(Context, &II);
243 Range = SourceRange(NameLoc);
244 }
245
John McCallba7bf592010-08-24 05:47:05 +0000246 QualType T = CheckTypenameType(ETK_None, NNS, II,
247 SourceLocation(),
248 Range, NameLoc);
249 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000250 }
251
252 if (ObjectTypePtr)
253 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
254 << &II;
255 else
256 Diag(NameLoc, diag::err_destructor_class_name);
257
John McCallba7bf592010-08-24 05:47:05 +0000258 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000259}
260
Douglas Gregor9da64192010-04-26 22:37:10 +0000261/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000262ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor9da64192010-04-26 22:37:10 +0000263 SourceLocation TypeidLoc,
264 TypeSourceInfo *Operand,
265 SourceLocation RParenLoc) {
266 // C++ [expr.typeid]p4:
267 // The top-level cv-qualifiers of the lvalue expression or the type-id
268 // that is the operand of typeid are always ignored.
269 // If the type of the type-id is a class type or a reference to a class
270 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000271 Qualifiers Quals;
272 QualType T
273 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
274 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000275 if (T->getAs<RecordType>() &&
276 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
277 return ExprError();
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000278
Douglas Gregor9da64192010-04-26 22:37:10 +0000279 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
280 Operand,
281 SourceRange(TypeidLoc, RParenLoc)));
282}
283
284/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000285ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor9da64192010-04-26 22:37:10 +0000286 SourceLocation TypeidLoc,
John McCallb268a282010-08-23 23:25:46 +0000287 Expr *E,
Douglas Gregor9da64192010-04-26 22:37:10 +0000288 SourceLocation RParenLoc) {
289 bool isUnevaluatedOperand = true;
Douglas Gregor9da64192010-04-26 22:37:10 +0000290 if (E && !E->isTypeDependent()) {
291 QualType T = E->getType();
292 if (const RecordType *RecordT = T->getAs<RecordType>()) {
293 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
294 // C++ [expr.typeid]p3:
295 // [...] If the type of the expression is a class type, the class
296 // shall be completely-defined.
297 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
298 return ExprError();
299
300 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000301 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000302 // polymorphic class type [...] [the] expression is an unevaluated
303 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000304 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000305 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000306
307 // We require a vtable to query the type at run time.
308 MarkVTableUsed(TypeidLoc, RecordD);
309 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000310 }
311
312 // C++ [expr.typeid]p4:
313 // [...] If the type of the type-id is a reference to a possibly
314 // cv-qualified type, the result of the typeid expression refers to a
315 // std::type_info object representing the cv-unqualified referenced
316 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000317 Qualifiers Quals;
318 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
319 if (!Context.hasSameType(T, UnqualT)) {
320 T = UnqualT;
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000321 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, CastCategory(E));
Douglas Gregor9da64192010-04-26 22:37:10 +0000322 }
323 }
324
325 // If this is an unevaluated operand, clear out the set of
326 // declaration references we have been computing and eliminate any
327 // temporaries introduced in its computation.
328 if (isUnevaluatedOperand)
329 ExprEvalContexts.back().Context = Unevaluated;
330
331 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000332 E,
Douglas Gregor9da64192010-04-26 22:37:10 +0000333 SourceRange(TypeidLoc, RParenLoc)));
334}
335
336/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000337ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000338Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
339 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000340 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000341 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000342 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000343
Chris Lattnerec7f7732008-11-20 05:51:55 +0000344 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000345 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +0000346 LookupQualifiedName(R, getStdNamespace());
John McCall67c00872009-12-02 08:25:40 +0000347 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000348 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor9da64192010-04-26 22:37:10 +0000350
Sebastian Redlc4704762008-11-11 11:37:55 +0000351 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor9da64192010-04-26 22:37:10 +0000352
353 if (isType) {
354 // The operand is a type; handle it as such.
355 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000356 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
357 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000358 if (T.isNull())
359 return ExprError();
360
361 if (!TInfo)
362 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000363
Douglas Gregor9da64192010-04-26 22:37:10 +0000364 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000365 }
Mike Stump11289f42009-09-09 15:08:12 +0000366
Douglas Gregor9da64192010-04-26 22:37:10 +0000367 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000368 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000369}
370
Steve Naroff66356bd2007-09-16 14:56:35 +0000371/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000372ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000373Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000374 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000375 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000376 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
377 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000378}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000379
Sebastian Redl576fd422009-05-10 18:38:11 +0000380/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000381ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000382Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
383 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
384}
385
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000386/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000387ExprResult
John McCallb268a282010-08-23 23:25:46 +0000388Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000389 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
390 return ExprError();
391 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
392}
393
394/// CheckCXXThrowOperand - Validate the operand of a throw.
395bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
396 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000397 // A throw-expression initializes a temporary object, called the exception
398 // object, the type of which is determined by removing any top-level
399 // cv-qualifiers from the static type of the operand of throw and adjusting
400 // the type from "array of T" or "function returning T" to "pointer to T"
401 // or "pointer to function returning T", [...]
402 if (E->getType().hasQualifiers())
403 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000404 CastCategory(E));
Douglas Gregor247894b2009-12-23 22:04:40 +0000405
Sebastian Redl4de47b42009-04-27 20:27:31 +0000406 DefaultFunctionArrayConversion(E);
407
408 // If the type of the exception would be an incomplete type or a pointer
409 // to an incomplete type other than (cv) void the program is ill-formed.
410 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000411 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000412 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000413 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000414 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000415 }
416 if (!isPointer || !Ty->isVoidType()) {
417 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000418 PDiag(isPointer ? diag::err_throw_incomplete_ptr
419 : diag::err_throw_incomplete)
420 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000421 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000422
Douglas Gregore8154332010-04-15 18:05:39 +0000423 if (RequireNonAbstractType(ThrowLoc, E->getType(),
424 PDiag(diag::err_throw_abstract_type)
425 << E->getSourceRange()))
426 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000427 }
428
John McCall2e6567a2010-04-22 01:10:34 +0000429 // Initialize the exception result. This implicitly weeds out
430 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000431 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000432 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000433 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
434 /*NRVO=*/false);
John McCalldadc5752010-08-24 06:29:42 +0000435 ExprResult Res = PerformCopyInitialization(Entity,
John McCall2e6567a2010-04-22 01:10:34 +0000436 SourceLocation(),
437 Owned(E));
438 if (Res.isInvalid())
439 return true;
440 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000441
Eli Friedman91a3d272010-06-03 20:39:03 +0000442 // If the exception has class type, we need additional handling.
443 const RecordType *RecordTy = Ty->getAs<RecordType>();
444 if (!RecordTy)
445 return false;
446 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
447
Douglas Gregor88d292c2010-05-13 16:44:06 +0000448 // If we are throwing a polymorphic class type or pointer thereof,
449 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000450 MarkVTableUsed(ThrowLoc, RD);
451
452 // If the class has a non-trivial destructor, we must be able to call it.
453 if (RD->hasTrivialDestructor())
454 return false;
455
Douglas Gregorbac74902010-07-01 14:13:13 +0000456 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000457 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000458 if (!Destructor)
459 return false;
460
461 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
462 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000463 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000464 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000465}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000466
John McCalldadc5752010-08-24 06:29:42 +0000467ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000468 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
469 /// is a non-lvalue expression whose value is the address of the object for
470 /// which the function is called.
471
John McCall87fe5d52010-05-20 01:18:31 +0000472 DeclContext *DC = getFunctionLevelDeclContext();
473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000474 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000475 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000476 MD->getThisType(Context),
477 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000478
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000479 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000480}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000481
482/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
483/// Can be interpreted either as function-style casting ("int(x)")
484/// or class type construction ("ClassType(x,y,z)")
485/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +0000486ExprResult
John McCallba7bf592010-08-24 05:47:05 +0000487Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000488 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000489 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000490 SourceLocation *CommaLocs,
491 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000492 if (!TypeRep)
493 return ExprError();
494
John McCall97513962010-01-15 18:39:57 +0000495 TypeSourceInfo *TInfo;
496 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
497 if (!TInfo)
498 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000499 unsigned NumExprs = exprs.size();
500 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000501 SourceLocation TyBeginLoc = TypeRange.getBegin();
502 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
503
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000504 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000505 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000506 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000507
508 return Owned(CXXUnresolvedConstructExpr::Create(Context,
509 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000510 LParenLoc,
511 Exprs, NumExprs,
512 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000513 }
514
Anders Carlsson55243162009-08-27 03:53:50 +0000515 if (Ty->isArrayType())
516 return ExprError(Diag(TyBeginLoc,
517 diag::err_value_init_for_array_type) << FullRange);
518 if (!Ty->isVoidType() &&
519 RequireCompleteType(TyBeginLoc, Ty,
520 PDiag(diag::err_invalid_incomplete_type_use)
521 << FullRange))
522 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000523
Anders Carlsson55243162009-08-27 03:53:50 +0000524 if (RequireNonAbstractType(TyBeginLoc, Ty,
525 diag::err_allocation_of_abstract_type))
526 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000527
528
Douglas Gregordd04d332009-01-16 18:33:17 +0000529 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000530 // If the expression list is a single expression, the type conversion
531 // expression is equivalent (in definedness, and if defined in meaning) to the
532 // corresponding cast expression.
533 //
534 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000535 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000536 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +0000537 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
538 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000539 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000540
541 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000542
John McCallcf142162010-08-07 06:22:56 +0000543 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000544 Ty.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000545 TInfo, TyBeginLoc, Kind,
546 Exprs[0], &BasePath,
547 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000548 }
549
Douglas Gregor747eb782010-07-08 06:14:04 +0000550 if (Ty->isRecordType()) {
551 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
552 InitializationKind Kind
553 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
554 LParenLoc, RParenLoc)
555 : InitializationKind::CreateValue(TypeRange.getBegin(),
556 LParenLoc, RParenLoc);
557 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
John McCalldadc5752010-08-24 06:29:42 +0000558 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor747eb782010-07-08 06:14:04 +0000559 move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000560
Douglas Gregor747eb782010-07-08 06:14:04 +0000561 // FIXME: Improve AST representation?
562 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000563 }
564
565 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000566 // If the expression list specifies more than a single value, the type shall
567 // be a class with a suitably declared constructor.
568 //
569 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000570 return ExprError(Diag(CommaLocs[0],
571 diag::err_builtin_func_cast_more_than_one_arg)
572 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000573
574 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000575 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000576 // The expression T(), where T is a simple-type-specifier for a non-array
577 // complete object type or the (possibly cv-qualified) void type, creates an
578 // rvalue of the specified type, which is value-initialized.
579 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000580 exprs.release();
Douglas Gregor747eb782010-07-08 06:14:04 +0000581 return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000582}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000583
584
Sebastian Redlbd150f42008-11-21 19:14:01 +0000585/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
586/// @code new (memory) int[size][4] @endcode
587/// or
588/// @code ::new Foo(23, "hello") @endcode
589/// For the interpretation of this heap of arguments, consult the base version.
John McCalldadc5752010-08-24 06:29:42 +0000590ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000591Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000592 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000593 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000594 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000595 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000596 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000597 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000598 // If the specified type is an array, unwrap it and save the expression.
599 if (D.getNumTypeObjects() > 0 &&
600 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
601 DeclaratorChunk &Chunk = D.getTypeObject(0);
602 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000603 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
604 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000605 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000606 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
607 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000608
Sebastian Redl351bb782008-12-02 14:43:59 +0000609 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000610 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000611 }
612
Douglas Gregor73341c42009-09-11 00:18:58 +0000613 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000614 if (ArraySize) {
615 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000616 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
617 break;
618
619 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
620 if (Expr *NumElts = (Expr *)Array.NumElts) {
621 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
622 !NumElts->isIntegerConstantExpr(Context)) {
623 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
624 << NumElts->getSourceRange();
625 return ExprError();
626 }
627 }
628 }
629 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000630
John McCallbcd03502009-12-07 02:54:59 +0000631 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCall8cb7bdf2010-06-04 23:28:52 +0000632 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
633 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000634 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000635 return ExprError();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000636
637 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000638 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000639 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000640 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000641 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000642 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000643 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000644 D.getSourceRange().getBegin(),
Ted Kremenekabb1f912010-06-25 22:48:49 +0000645 R,
John McCallb268a282010-08-23 23:25:46 +0000646 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000647 ConstructorLParen,
648 move(ConstructorArgs),
649 ConstructorRParen);
650}
651
John McCalldadc5752010-08-24 06:29:42 +0000652ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000653Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
654 SourceLocation PlacementLParen,
655 MultiExprArg PlacementArgs,
656 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000657 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000658 QualType AllocType,
659 SourceLocation TypeLoc,
660 SourceRange TypeRange,
John McCallb268a282010-08-23 23:25:46 +0000661 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000662 SourceLocation ConstructorLParen,
663 MultiExprArg ConstructorArgs,
664 SourceLocation ConstructorRParen) {
665 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000666 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000667
Douglas Gregorcda95f42010-05-16 16:01:03 +0000668 // Per C++0x [expr.new]p5, the type being constructed may be a
669 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000670 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000671 if (const ConstantArrayType *Array
672 = Context.getAsConstantArrayType(AllocType)) {
John McCallb268a282010-08-23 23:25:46 +0000673 ArraySize = new (Context) IntegerLiteral(Array->getSize(),
674 Context.getSizeType(),
675 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000676 AllocType = Array->getElementType();
677 }
678 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000679
Douglas Gregorcda95f42010-05-16 16:01:03 +0000680 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000681
Sebastian Redlbd150f42008-11-21 19:14:01 +0000682 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
683 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000684 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor4799d032010-06-30 00:20:43 +0000685
Sebastian Redl351bb782008-12-02 14:43:59 +0000686 QualType SizeType = ArraySize->getType();
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000687
John McCalldadc5752010-08-24 06:29:42 +0000688 ExprResult ConvertedSize
John McCallb268a282010-08-23 23:25:46 +0000689 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor4799d032010-06-30 00:20:43 +0000690 PDiag(diag::err_array_size_not_integral),
691 PDiag(diag::err_array_size_incomplete_type)
692 << ArraySize->getSourceRange(),
693 PDiag(diag::err_array_size_explicit_conversion),
694 PDiag(diag::note_array_size_conversion),
695 PDiag(diag::err_array_size_ambiguous_conversion),
696 PDiag(diag::note_array_size_conversion),
697 PDiag(getLangOptions().CPlusPlus0x? 0
698 : diag::ext_array_size_conversion));
699 if (ConvertedSize.isInvalid())
700 return ExprError();
701
John McCallb268a282010-08-23 23:25:46 +0000702 ArraySize = ConvertedSize.take();
Douglas Gregor4799d032010-06-30 00:20:43 +0000703 SizeType = ArraySize->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000704 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000705 return ExprError();
706
Sebastian Redl351bb782008-12-02 14:43:59 +0000707 // Let's see if this is a constant < 0. If so, we reject it out of hand.
708 // We don't care about special rules, so we tell the machinery it's not
709 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000710 if (!ArraySize->isValueDependent()) {
711 llvm::APSInt Value;
712 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
713 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000714 llvm::APInt::getNullValue(Value.getBitWidth()),
715 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000716 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000717 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000718 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000719
720 if (!AllocType->isDependentType()) {
721 unsigned ActiveSizeBits
722 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
723 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
724 Diag(ArraySize->getSourceRange().getBegin(),
725 diag::err_array_too_large)
726 << Value.toString(10)
727 << ArraySize->getSourceRange();
728 return ExprError();
729 }
730 }
Douglas Gregorf2753b32010-07-13 15:54:32 +0000731 } else if (TypeIdParens.isValid()) {
732 // Can't have dynamic array size when the type-id is in parentheses.
733 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
734 << ArraySize->getSourceRange()
735 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
736 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
737
738 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000739 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000740 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000741
Eli Friedman06ed2a52009-10-20 08:27:19 +0000742 ImpCastExprToType(ArraySize, Context.getSizeType(),
743 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000744 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000745
Sebastian Redlbd150f42008-11-21 19:14:01 +0000746 FunctionDecl *OperatorNew = 0;
747 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000748 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
749 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000750
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000751 if (!AllocType->isDependentType() &&
752 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
753 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000754 SourceRange(PlacementLParen, PlacementRParen),
755 UseGlobal, AllocType, ArraySize, PlaceArgs,
756 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000757 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000758 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000759 if (OperatorNew) {
760 // Add default arguments, if any.
761 const FunctionProtoType *Proto =
762 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000763 VariadicCallType CallType =
764 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000765
766 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
767 Proto, 1, PlaceArgs, NumPlaceArgs,
768 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000769 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000770
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000771 NumPlaceArgs = AllPlaceArgs.size();
772 if (NumPlaceArgs > 0)
773 PlaceArgs = &AllPlaceArgs[0];
774 }
775
Sebastian Redlbd150f42008-11-21 19:14:01 +0000776 bool Init = ConstructorLParen.isValid();
777 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000778 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000779 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
780 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +0000781 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000782
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000783 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000784 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000785 SourceRange InitRange(ConsArgs[0]->getLocStart(),
786 ConsArgs[NumConsArgs - 1]->getLocEnd());
787
788 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
789 return ExprError();
790 }
791
Douglas Gregor85dabae2009-12-16 01:38:02 +0000792 if (!AllocType->isDependentType() &&
793 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
794 // C++0x [expr.new]p15:
795 // A new-expression that creates an object of type T initializes that
796 // object as follows:
797 InitializationKind Kind
798 // - If the new-initializer is omitted, the object is default-
799 // initialized (8.5); if no initialization is performed,
800 // the object has indeterminate value
801 = !Init? InitializationKind::CreateDefault(TypeLoc)
802 // - Otherwise, the new-initializer is interpreted according to the
803 // initialization rules of 8.5 for direct-initialization.
804 : InitializationKind::CreateDirect(TypeLoc,
805 ConstructorLParen,
806 ConstructorRParen);
807
Douglas Gregor85dabae2009-12-16 01:38:02 +0000808 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000809 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000810 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCalldadc5752010-08-24 06:29:42 +0000811 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +0000812 move(ConstructorArgs));
813 if (FullInit.isInvalid())
814 return ExprError();
815
816 // FullInit is our initializer; walk through it to determine if it's a
817 // constructor call, which CXXNewExpr handles directly.
818 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
819 if (CXXBindTemporaryExpr *Binder
820 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
821 FullInitExpr = Binder->getSubExpr();
822 if (CXXConstructExpr *Construct
823 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
824 Constructor = Construct->getConstructor();
825 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
826 AEnd = Construct->arg_end();
827 A != AEnd; ++A)
828 ConvertedConstructorArgs.push_back(A->Retain());
829 } else {
830 // Take the converted initializer.
831 ConvertedConstructorArgs.push_back(FullInit.release());
832 }
833 } else {
834 // No initialization required.
835 }
836
837 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000838 NumConsArgs = ConvertedConstructorArgs.size();
839 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000840 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000841
Douglas Gregor6642ca22010-02-26 05:06:18 +0000842 // Mark the new and delete operators as referenced.
843 if (OperatorNew)
844 MarkDeclarationReferenced(StartLoc, OperatorNew);
845 if (OperatorDelete)
846 MarkDeclarationReferenced(StartLoc, OperatorDelete);
847
Sebastian Redlbd150f42008-11-21 19:14:01 +0000848 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000849
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000850 PlacementArgs.release();
851 ConstructorArgs.release();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000852
853 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000854 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000855 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000856 ArraySize, Constructor, Init,
857 ConsArgs, NumConsArgs, OperatorDelete,
858 ResultType, StartLoc,
859 Init ? ConstructorRParen :
Ted Kremenekabb1f912010-06-25 22:48:49 +0000860 TypeRange.getEnd()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000861}
862
863/// CheckAllocatedType - Checks that a type is suitable as the allocated type
864/// in a new-expression.
865/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000866bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000867 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000868 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
869 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000870 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000871 return Diag(Loc, diag::err_bad_new_type)
872 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000873 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000874 return Diag(Loc, diag::err_bad_new_type)
875 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000876 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000877 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000878 PDiag(diag::err_new_incomplete_type)
879 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000880 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000881 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000882 diag::err_allocation_of_abstract_type))
883 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000884
Sebastian Redlbd150f42008-11-21 19:14:01 +0000885 return false;
886}
887
Douglas Gregor6642ca22010-02-26 05:06:18 +0000888/// \brief Determine whether the given function is a non-placement
889/// deallocation function.
890static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
891 if (FD->isInvalidDecl())
892 return false;
893
894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
895 return Method->isUsualDeallocationFunction();
896
897 return ((FD->getOverloadedOperator() == OO_Delete ||
898 FD->getOverloadedOperator() == OO_Array_Delete) &&
899 FD->getNumParams() == 1);
900}
901
Sebastian Redlfaf68082008-12-03 20:26:15 +0000902/// FindAllocationFunctions - Finds the overloads of operator new and delete
903/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000904bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
905 bool UseGlobal, QualType AllocType,
906 bool IsArray, Expr **PlaceArgs,
907 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000908 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000909 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000910 // --- Choosing an allocation function ---
911 // C++ 5.3.4p8 - 14 & 18
912 // 1) If UseGlobal is true, only look in the global scope. Else, also look
913 // in the scope of the allocated class.
914 // 2) If an array size is given, look for operator new[], else look for
915 // operator new.
916 // 3) The first argument is always size_t. Append the arguments from the
917 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000918
919 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
920 // We don't care about the actual value of this argument.
921 // FIXME: Should the Sema create the expression and embed it in the syntax
922 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000923 IntegerLiteral Size(llvm::APInt::getNullValue(
924 Context.Target.getPointerWidth(0)),
925 Context.getSizeType(),
926 SourceLocation());
927 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000928 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
929
Douglas Gregor6642ca22010-02-26 05:06:18 +0000930 // C++ [expr.new]p8:
931 // If the allocated type is a non-array type, the allocation
932 // function’s name is operator new and the deallocation function’s
933 // name is operator delete. If the allocated type is an array
934 // type, the allocation function’s name is operator new[] and the
935 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000936 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
937 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000938 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
939 IsArray ? OO_Array_Delete : OO_Delete);
940
Sebastian Redlfaf68082008-12-03 20:26:15 +0000941 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000942 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000943 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000944 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000945 AllocArgs.size(), Record, /*AllowMissing=*/true,
946 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000947 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000948 }
949 if (!OperatorNew) {
950 // Didn't find a member overload. Look for a global one.
951 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000952 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000953 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000954 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
955 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000956 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000957 }
958
John McCall0f55a032010-04-20 02:18:25 +0000959 // We don't need an operator delete if we're running under
960 // -fno-exceptions.
961 if (!getLangOptions().Exceptions) {
962 OperatorDelete = 0;
963 return false;
964 }
965
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000966 // FindAllocationOverload can change the passed in arguments, so we need to
967 // copy them back.
968 if (NumPlaceArgs > 0)
969 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000970
Douglas Gregor6642ca22010-02-26 05:06:18 +0000971 // C++ [expr.new]p19:
972 //
973 // If the new-expression begins with a unary :: operator, the
974 // deallocation function’s name is looked up in the global
975 // scope. Otherwise, if the allocated type is a class type T or an
976 // array thereof, the deallocation function’s name is looked up in
977 // the scope of T. If this lookup fails to find the name, or if
978 // the allocated type is not a class type or array thereof, the
979 // deallocation function’s name is looked up in the global scope.
980 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
981 if (AllocType->isRecordType() && !UseGlobal) {
982 CXXRecordDecl *RD
983 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
984 LookupQualifiedName(FoundDelete, RD);
985 }
John McCallfb6f5262010-03-18 08:19:33 +0000986 if (FoundDelete.isAmbiguous())
987 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000988
989 if (FoundDelete.empty()) {
990 DeclareGlobalNewDelete();
991 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
992 }
993
994 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000995
996 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
997
John McCallfb6f5262010-03-18 08:19:33 +0000998 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +0000999 // C++ [expr.new]p20:
1000 // A declaration of a placement deallocation function matches the
1001 // declaration of a placement allocation function if it has the
1002 // same number of parameters and, after parameter transformations
1003 // (8.3.5), all parameter types except the first are
1004 // identical. [...]
1005 //
1006 // To perform this comparison, we compute the function type that
1007 // the deallocation function should have, and use that type both
1008 // for template argument deduction and for comparison purposes.
1009 QualType ExpectedFunctionType;
1010 {
1011 const FunctionProtoType *Proto
1012 = OperatorNew->getType()->getAs<FunctionProtoType>();
1013 llvm::SmallVector<QualType, 4> ArgTypes;
1014 ArgTypes.push_back(Context.VoidPtrTy);
1015 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1016 ArgTypes.push_back(Proto->getArgType(I));
1017
1018 ExpectedFunctionType
1019 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1020 ArgTypes.size(),
1021 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001022 0, false, false, 0, 0,
1023 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001024 }
1025
1026 for (LookupResult::iterator D = FoundDelete.begin(),
1027 DEnd = FoundDelete.end();
1028 D != DEnd; ++D) {
1029 FunctionDecl *Fn = 0;
1030 if (FunctionTemplateDecl *FnTmpl
1031 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1032 // Perform template argument deduction to try to match the
1033 // expected function type.
1034 TemplateDeductionInfo Info(Context, StartLoc);
1035 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1036 continue;
1037 } else
1038 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1039
1040 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001041 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001042 }
1043 } else {
1044 // C++ [expr.new]p20:
1045 // [...] Any non-placement deallocation function matches a
1046 // non-placement allocation function. [...]
1047 for (LookupResult::iterator D = FoundDelete.begin(),
1048 DEnd = FoundDelete.end();
1049 D != DEnd; ++D) {
1050 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1051 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001052 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001053 }
1054 }
1055
1056 // C++ [expr.new]p20:
1057 // [...] If the lookup finds a single matching deallocation
1058 // function, that function will be called; otherwise, no
1059 // deallocation function will be called.
1060 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001061 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001062
1063 // C++0x [expr.new]p20:
1064 // If the lookup finds the two-parameter form of a usual
1065 // deallocation function (3.7.4.2) and that function, considered
1066 // as a placement deallocation function, would have been
1067 // selected as a match for the allocation function, the program
1068 // is ill-formed.
1069 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1070 isNonPlacementDeallocationFunction(OperatorDelete)) {
1071 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1072 << SourceRange(PlaceArgs[0]->getLocStart(),
1073 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1074 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1075 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001076 } else {
1077 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001078 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001079 }
1080 }
1081
Sebastian Redlfaf68082008-12-03 20:26:15 +00001082 return false;
1083}
1084
Sebastian Redl33a31012008-12-04 22:20:51 +00001085/// FindAllocationOverload - Find an fitting overload for the allocation
1086/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001087bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1088 DeclarationName Name, Expr** Args,
1089 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001090 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001091 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1092 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001093 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001094 if (AllowMissing)
1095 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001096 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001097 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001098 }
1099
John McCallfb6f5262010-03-18 08:19:33 +00001100 if (R.isAmbiguous())
1101 return true;
1102
1103 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001104
John McCallbc077cf2010-02-08 23:07:23 +00001105 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001106 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1107 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001108 // Even member operator new/delete are implicitly treated as
1109 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001110 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001111
John McCalla0296f72010-03-19 07:35:19 +00001112 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1113 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001114 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1115 Candidates,
1116 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001117 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001118 }
1119
John McCalla0296f72010-03-19 07:35:19 +00001120 FunctionDecl *Fn = cast<FunctionDecl>(D);
1121 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001122 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001123 }
1124
1125 // Do the resolution.
1126 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001127 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001128 case OR_Success: {
1129 // Got one!
1130 FunctionDecl *FnDecl = Best->Function;
1131 // The first argument is size_t, and the first parameter must be size_t,
1132 // too. This is checked on declaration and can be assumed. (It can't be
1133 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001134 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001135 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1136 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCalldadc5752010-08-24 06:29:42 +00001137 ExprResult Result
Douglas Gregor34147272010-03-26 20:35:59 +00001138 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1139 FnDecl->getParamDecl(i)),
1140 SourceLocation(),
1141 Owned(Args[i]->Retain()));
1142 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001143 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001144
1145 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001146 }
1147 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001148 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001149 return false;
1150 }
1151
1152 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001153 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001154 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001155 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001156 return true;
1157
1158 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001159 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001160 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001161 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001162 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001163
1164 case OR_Deleted:
1165 Diag(StartLoc, diag::err_ovl_deleted_call)
1166 << Best->Function->isDeleted()
1167 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001168 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001169 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001170 }
1171 assert(false && "Unreachable, bad result from BestViableFunction");
1172 return true;
1173}
1174
1175
Sebastian Redlfaf68082008-12-03 20:26:15 +00001176/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1177/// delete. These are:
1178/// @code
1179/// void* operator new(std::size_t) throw(std::bad_alloc);
1180/// void* operator new[](std::size_t) throw(std::bad_alloc);
1181/// void operator delete(void *) throw();
1182/// void operator delete[](void *) throw();
1183/// @endcode
1184/// Note that the placement and nothrow forms of new are *not* implicitly
1185/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001186void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001187 if (GlobalNewDeleteDeclared)
1188 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001189
1190 // C++ [basic.std.dynamic]p2:
1191 // [...] The following allocation and deallocation functions (18.4) are
1192 // implicitly declared in global scope in each translation unit of a
1193 // program
1194 //
1195 // void* operator new(std::size_t) throw(std::bad_alloc);
1196 // void* operator new[](std::size_t) throw(std::bad_alloc);
1197 // void operator delete(void*) throw();
1198 // void operator delete[](void*) throw();
1199 //
1200 // These implicit declarations introduce only the function names operator
1201 // new, operator new[], operator delete, operator delete[].
1202 //
1203 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1204 // "std" or "bad_alloc" as necessary to form the exception specification.
1205 // However, we do not make these implicit declarations visible to name
1206 // lookup.
Douglas Gregor87f54062009-09-15 22:30:29 +00001207 if (!StdBadAlloc) {
1208 // The "std::bad_alloc" class has not yet been declared, so build it
1209 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001210 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00001211 getOrCreateStdNamespace(),
Douglas Gregor87f54062009-09-15 22:30:29 +00001212 SourceLocation(),
1213 &PP.getIdentifierTable().get("bad_alloc"),
1214 SourceLocation(), 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001215 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001216 }
1217
Sebastian Redlfaf68082008-12-03 20:26:15 +00001218 GlobalNewDeleteDeclared = true;
1219
1220 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1221 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001222 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001223
Sebastian Redlfaf68082008-12-03 20:26:15 +00001224 DeclareGlobalAllocationFunction(
1225 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001226 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001227 DeclareGlobalAllocationFunction(
1228 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001229 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001230 DeclareGlobalAllocationFunction(
1231 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1232 Context.VoidTy, VoidPtr);
1233 DeclareGlobalAllocationFunction(
1234 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1235 Context.VoidTy, VoidPtr);
1236}
1237
1238/// DeclareGlobalAllocationFunction - Declares a single implicit global
1239/// allocation function if it doesn't already exist.
1240void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001241 QualType Return, QualType Argument,
1242 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001243 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1244
1245 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001246 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001247 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001248 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001249 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001250 // Only look at non-template functions, as it is the predefined,
1251 // non-templated allocation function we are trying to declare here.
1252 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1253 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001254 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001255 Func->getParamDecl(0)->getType().getUnqualifiedType());
1256 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001257 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1258 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001259 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001260 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001261 }
Chandler Carruth93538422010-02-03 11:02:14 +00001262 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001263 }
1264 }
1265
Douglas Gregor87f54062009-09-15 22:30:29 +00001266 QualType BadAllocType;
1267 bool HasBadAllocExceptionSpec
1268 = (Name.getCXXOverloadedOperator() == OO_New ||
1269 Name.getCXXOverloadedOperator() == OO_Array_New);
1270 if (HasBadAllocExceptionSpec) {
1271 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001272 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001273 }
1274
1275 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1276 true, false,
1277 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001278 &BadAllocType,
1279 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001280 FunctionDecl *Alloc =
1281 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001282 FnType, /*TInfo=*/0, FunctionDecl::None,
1283 FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001284 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001285
1286 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001287 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopes13c88c72009-12-16 16:59:22 +00001288
Sebastian Redlfaf68082008-12-03 20:26:15 +00001289 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001290 0, Argument, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001291 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001292 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001293 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001294
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001295 // FIXME: Also add this declaration to the IdentifierResolver, but
1296 // make sure it is at the end of the chain to coincide with the
1297 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001298 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001299}
1300
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001301bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1302 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001303 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001304 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001305 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001306 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001307
John McCall27b18f82009-11-17 02:14:36 +00001308 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001309 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001310
Chandler Carruthb6f99172010-06-28 00:30:51 +00001311 Found.suppressDiagnostics();
1312
John McCall66a87592010-08-04 00:31:26 +00001313 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001314 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1315 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001316 NamedDecl *ND = (*F)->getUnderlyingDecl();
1317
1318 // Ignore template operator delete members from the check for a usual
1319 // deallocation function.
1320 if (isa<FunctionTemplateDecl>(ND))
1321 continue;
1322
1323 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001324 Matches.push_back(F.getPair());
1325 }
1326
1327 // There's exactly one suitable operator; pick it.
1328 if (Matches.size() == 1) {
1329 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1330 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1331 Matches[0]);
1332 return false;
1333
1334 // We found multiple suitable operators; complain about the ambiguity.
1335 } else if (!Matches.empty()) {
1336 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1337 << Name << RD;
1338
1339 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1340 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1341 Diag((*F)->getUnderlyingDecl()->getLocation(),
1342 diag::note_member_declared_here) << Name;
1343 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001344 }
1345
1346 // We did find operator delete/operator delete[] declarations, but
1347 // none of them were suitable.
1348 if (!Found.empty()) {
1349 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1350 << Name << RD;
1351
1352 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall66a87592010-08-04 00:31:26 +00001353 F != FEnd; ++F)
1354 Diag((*F)->getUnderlyingDecl()->getLocation(),
1355 diag::note_member_declared_here) << Name;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001356
1357 return true;
1358 }
1359
1360 // Look for a global declaration.
1361 DeclareGlobalNewDelete();
1362 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1363
1364 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1365 Expr* DeallocArgs[1];
1366 DeallocArgs[0] = &Null;
1367 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1368 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1369 Operator))
1370 return true;
1371
1372 assert(Operator && "Did not find a deallocation function!");
1373 return false;
1374}
1375
Sebastian Redlbd150f42008-11-21 19:14:01 +00001376/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1377/// @code ::delete ptr; @endcode
1378/// or
1379/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001380ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001381Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCallb268a282010-08-23 23:25:46 +00001382 bool ArrayForm, Expr *Ex) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001383 // C++ [expr.delete]p1:
1384 // The operand shall have a pointer type, or a class type having a single
1385 // conversion function to a pointer type. The result has type void.
1386 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001387 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1388
Anders Carlssona471db02009-08-16 20:29:29 +00001389 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001390
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001391 if (!Ex->isTypeDependent()) {
1392 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001393
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001394 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregorf65f4902010-07-29 14:44:35 +00001395 if (RequireCompleteType(StartLoc, Type,
1396 PDiag(diag::err_delete_incomplete_class_type)))
1397 return ExprError();
1398
John McCallda4458e2010-03-31 01:36:47 +00001399 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1400
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001401 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001402 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001403 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001404 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001405 NamedDecl *D = I.getDecl();
1406 if (isa<UsingShadowDecl>(D))
1407 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1408
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001409 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001410 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001411 continue;
1412
John McCallda4458e2010-03-31 01:36:47 +00001413 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001414
1415 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1416 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001417 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001418 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001419 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001420 if (ObjectPtrConversions.size() == 1) {
1421 // We have a single conversion to a pointer-to-object type. Perform
1422 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001423 // TODO: don't redo the conversion calculation.
John McCallda4458e2010-03-31 01:36:47 +00001424 if (!PerformImplicitConversion(Ex,
1425 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001426 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001427 Type = Ex->getType();
1428 }
1429 }
1430 else if (ObjectPtrConversions.size() > 1) {
1431 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1432 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001433 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1434 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001435 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001436 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001437 }
1438
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001439 if (!Type->isPointerType())
1440 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1441 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001442
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001443 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001444 if (Pointee->isVoidType() && !isSFINAEContext()) {
1445 // The C++ standard bans deleting a pointer to a non-object type, which
1446 // effectively bans deletion of "void*". However, most compilers support
1447 // this, so we treat it as a warning unless we're in a SFINAE context.
1448 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1449 << Type << Ex->getSourceRange();
1450 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001451 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1452 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001453 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001454 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001455 PDiag(diag::warn_delete_incomplete)
1456 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001457 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001458
Douglas Gregor98496dc2009-09-29 21:38:53 +00001459 // C++ [expr.delete]p2:
1460 // [Note: a pointer to a const type can be the operand of a
1461 // delete-expression; it is not necessary to cast away the constness
1462 // (5.2.11) of the pointer expression before it is used as the operand
1463 // of the delete-expression. ]
1464 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1465 CastExpr::CK_NoOp);
1466
Anders Carlssona471db02009-08-16 20:29:29 +00001467 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1468 ArrayForm ? OO_Array_Delete : OO_Delete);
1469
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001470 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1471 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1472
1473 if (!UseGlobal &&
1474 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001475 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001476
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001477 if (!RD->hasTrivialDestructor())
Douglas Gregore71edda2010-07-01 22:47:18 +00001478 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump11289f42009-09-09 15:08:12 +00001479 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001480 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001481 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001482
Anders Carlssona471db02009-08-16 20:29:29 +00001483 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001484 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001485 DeclareGlobalNewDelete();
1486 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001487 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001488 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001489 OperatorDelete))
1490 return ExprError();
1491 }
Mike Stump11289f42009-09-09 15:08:12 +00001492
John McCall0f55a032010-04-20 02:18:25 +00001493 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1494
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001495 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001496 }
1497
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001498 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001499 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001500}
1501
Douglas Gregor633caca2009-11-23 23:44:04 +00001502/// \brief Check the use of the given variable as a C++ condition in an if,
1503/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00001504ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001505 SourceLocation StmtLoc,
1506 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001507 QualType T = ConditionVar->getType();
1508
1509 // C++ [stmt.select]p2:
1510 // The declarator shall not specify a function or an array.
1511 if (T->isFunctionType())
1512 return ExprError(Diag(ConditionVar->getLocation(),
1513 diag::err_invalid_use_of_function_type)
1514 << ConditionVar->getSourceRange());
1515 else if (T->isArrayType())
1516 return ExprError(Diag(ConditionVar->getLocation(),
1517 diag::err_invalid_use_of_array_type)
1518 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001519
Douglas Gregore60e41a2010-05-06 17:25:47 +00001520 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1521 ConditionVar->getLocation(),
1522 ConditionVar->getType().getNonReferenceType());
Douglas Gregorb412e172010-07-25 18:17:45 +00001523 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00001524 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001525
1526 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001527}
1528
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001529/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1530bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1531 // C++ 6.4p4:
1532 // The value of a condition that is an initialized declaration in a statement
1533 // other than a switch statement is the value of the declared variable
1534 // implicitly converted to type bool. If that conversion is ill-formed, the
1535 // program is ill-formed.
1536 // The value of a condition that is an expression is the value of the
1537 // expression, implicitly converted to bool.
1538 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001539 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001540}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001541
1542/// Helper function to determine whether this is the (deprecated) C++
1543/// conversion from a string literal to a pointer to non-const char or
1544/// non-const wchar_t (for narrow and wide string literals,
1545/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001546bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001547Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1548 // Look inside the implicit cast, if it exists.
1549 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1550 From = Cast->getSubExpr();
1551
1552 // A string literal (2.13.4) that is not a wide string literal can
1553 // be converted to an rvalue of type "pointer to char"; a wide
1554 // string literal can be converted to an rvalue of type "pointer
1555 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001556 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001557 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001558 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001559 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001560 // This conversion is considered only when there is an
1561 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001562 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001563 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1564 (!StrLit->isWide() &&
1565 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1566 ToPointeeType->getKind() == BuiltinType::Char_S))))
1567 return true;
1568 }
1569
1570 return false;
1571}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001572
John McCalldadc5752010-08-24 06:29:42 +00001573static ExprResult BuildCXXCastArgument(Sema &S,
Douglas Gregora4253922010-04-16 22:17:36 +00001574 SourceLocation CastLoc,
1575 QualType Ty,
1576 CastExpr::CastKind Kind,
1577 CXXMethodDecl *Method,
John McCallb268a282010-08-23 23:25:46 +00001578 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00001579 switch (Kind) {
1580 default: assert(0 && "Unhandled cast kind!");
1581 case CastExpr::CK_ConstructorConversion: {
John McCall37ad5512010-08-23 06:44:23 +00001582 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregora4253922010-04-16 22:17:36 +00001583
1584 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCall37ad5512010-08-23 06:44:23 +00001585 Sema::MultiExprArg(S, &From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00001586 CastLoc, ConstructorArgs))
1587 return S.ExprError();
1588
John McCalldadc5752010-08-24 06:29:42 +00001589 ExprResult Result =
Douglas Gregora4253922010-04-16 22:17:36 +00001590 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1591 move_arg(ConstructorArgs));
1592 if (Result.isInvalid())
1593 return S.ExprError();
1594
1595 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1596 }
1597
1598 case CastExpr::CK_UserDefinedConversion: {
1599 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1600
1601 // Create an implicit call expr that calls it.
1602 // FIXME: pass the FoundDecl for the user-defined conversion here
1603 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1604 return S.MaybeBindToTemporary(CE);
1605 }
1606 }
1607}
1608
Douglas Gregor5fb53972009-01-14 15:45:31 +00001609/// PerformImplicitConversion - Perform an implicit conversion of the
1610/// expression From to the type ToType using the pre-computed implicit
1611/// conversion sequence ICS. Returns true if there was an error, false
1612/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001613/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001614/// used in the error message.
1615bool
1616Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1617 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001618 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001619 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001620 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001621 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001622 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001623 return true;
1624 break;
1625
Anders Carlsson110b07b2009-09-15 06:28:28 +00001626 case ImplicitConversionSequence::UserDefinedConversion: {
1627
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001628 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1629 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001630 QualType BeforeToType;
1631 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001632 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001633
1634 // If the user-defined conversion is specified by a conversion function,
1635 // the initial standard conversion sequence converts the source type to
1636 // the implicit object parameter of the conversion function.
1637 BeforeToType = Context.getTagDeclType(Conv->getParent());
1638 } else if (const CXXConstructorDecl *Ctor =
1639 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001640 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001641 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001642 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001643 // If the user-defined conversion is specified by a constructor, the
1644 // initial standard conversion sequence converts the source type to the
1645 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001646 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1647 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001648 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001649 else
1650 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001651 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001652 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001653 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001654 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001655 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001656 return true;
1657 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001658
John McCalldadc5752010-08-24 06:29:42 +00001659 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001660 = BuildCXXCastArgument(*this,
1661 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001662 ToType.getNonReferenceType(),
1663 CastKind, cast<CXXMethodDecl>(FD),
John McCallb268a282010-08-23 23:25:46 +00001664 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00001665
1666 if (CastArg.isInvalid())
1667 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001668
1669 From = CastArg.takeAs<Expr>();
1670
Eli Friedmane96f1d32009-11-27 04:41:50 +00001671 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001672 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001673 }
John McCall0d1da222010-01-12 00:44:57 +00001674
1675 case ImplicitConversionSequence::AmbiguousConversion:
1676 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1677 PDiag(diag::err_typecheck_ambiguous_condition)
1678 << From->getSourceRange());
1679 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001680
Douglas Gregor39c16d42008-10-24 04:54:22 +00001681 case ImplicitConversionSequence::EllipsisConversion:
1682 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001683 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001684
1685 case ImplicitConversionSequence::BadConversion:
1686 return true;
1687 }
1688
1689 // Everything went well.
1690 return false;
1691}
1692
1693/// PerformImplicitConversion - Perform an implicit conversion of the
1694/// expression From to the type ToType by following the standard
1695/// conversion sequence SCS. Returns true if there was an error, false
1696/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001697/// expression. Flavor is the context in which we're performing this
1698/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001699bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001700Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001701 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001702 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001703 // Overall FIXME: we are recomputing too many types here and doing far too
1704 // much extra work. What this means is that we need to keep track of more
1705 // information that is computed when we try the implicit conversion initially,
1706 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001707 QualType FromType = From->getType();
1708
Douglas Gregor2fe98832008-11-03 19:09:14 +00001709 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001710 // FIXME: When can ToType be a reference type?
1711 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001712 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00001713 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001714 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00001715 MultiExprArg(*this, &From, 1),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001716 /*FIXME:ConstructLoc*/SourceLocation(),
1717 ConstructorArgs))
1718 return true;
John McCalldadc5752010-08-24 06:29:42 +00001719 ExprResult FromResult =
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001720 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1721 ToType, SCS.CopyConstructor,
1722 move_arg(ConstructorArgs));
1723 if (FromResult.isInvalid())
1724 return true;
1725 From = FromResult.takeAs<Expr>();
1726 return false;
1727 }
John McCalldadc5752010-08-24 06:29:42 +00001728 ExprResult FromResult =
Mike Stump11289f42009-09-09 15:08:12 +00001729 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1730 ToType, SCS.CopyConstructor,
John McCall37ad5512010-08-23 06:44:23 +00001731 MultiExprArg(*this, &From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001732
Anders Carlsson6eb55572009-08-25 05:12:04 +00001733 if (FromResult.isInvalid())
1734 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001735
Anders Carlsson6eb55572009-08-25 05:12:04 +00001736 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001737 return false;
1738 }
1739
Douglas Gregor980fb162010-04-29 18:24:40 +00001740 // Resolve overloaded function references.
1741 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1742 DeclAccessPair Found;
1743 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1744 true, Found);
1745 if (!Fn)
1746 return true;
1747
1748 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1749 return true;
1750
1751 From = FixOverloadedFunctionReference(From, Found, Fn);
1752 FromType = From->getType();
1753 }
1754
Douglas Gregor39c16d42008-10-24 04:54:22 +00001755 // Perform the first implicit conversion.
1756 switch (SCS.First) {
1757 case ICK_Identity:
1758 case ICK_Lvalue_To_Rvalue:
1759 // Nothing to do.
1760 break;
1761
1762 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001763 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001764 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001765 break;
1766
1767 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001768 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001769 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001770 break;
1771
1772 default:
1773 assert(false && "Improper first standard conversion");
1774 break;
1775 }
1776
1777 // Perform the second implicit conversion
1778 switch (SCS.Second) {
1779 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001780 // If both sides are functions (or pointers/references to them), there could
1781 // be incompatible exception declarations.
1782 if (CheckExceptionSpecCompatibility(From, ToType))
1783 return true;
1784 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001785 break;
1786
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001787 case ICK_NoReturn_Adjustment:
1788 // If both sides are functions (or pointers/references to them), there could
1789 // be incompatible exception declarations.
1790 if (CheckExceptionSpecCompatibility(From, ToType))
1791 return true;
1792
1793 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1794 CastExpr::CK_NoOp);
1795 break;
1796
Douglas Gregor39c16d42008-10-24 04:54:22 +00001797 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001798 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001799 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1800 break;
1801
1802 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001803 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001804 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1805 break;
1806
1807 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001808 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001809 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1810 break;
1811
Douglas Gregor39c16d42008-10-24 04:54:22 +00001812 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00001813 if (ToType->isRealFloatingType())
Eli Friedman06ed2a52009-10-20 08:27:19 +00001814 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1815 else
1816 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1817 break;
1818
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001819 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001820 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001821 break;
1822
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001823 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001824 if (SCS.IncompatibleObjC) {
1825 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001826 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001827 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001828 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001829 << From->getSourceRange();
1830 }
1831
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001832
1833 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +00001834 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00001835 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001836 return true;
John McCallcf142162010-08-07 06:22:56 +00001837 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, &BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001838 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001839 }
1840
1841 case ICK_Pointer_Member: {
1842 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +00001843 CXXCastPath BasePath;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001844 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1845 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001846 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001847 if (CheckExceptionSpecCompatibility(From, ToType))
1848 return true;
John McCallcf142162010-08-07 06:22:56 +00001849 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, &BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001850 break;
1851 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001852 case ICK_Boolean_Conversion: {
1853 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1854 if (FromType->isMemberPointerType())
1855 Kind = CastExpr::CK_MemberPointerToBoolean;
1856
1857 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001858 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001859 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001860
Douglas Gregor88d292c2010-05-13 16:44:06 +00001861 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00001862 CXXCastPath BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001863 if (CheckDerivedToBaseConversion(From->getType(),
1864 ToType.getNonReferenceType(),
1865 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001866 From->getSourceRange(),
1867 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001868 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001869 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001870
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001871 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCallcf142162010-08-07 06:22:56 +00001872 CastExpr::CK_DerivedToBase, CastCategory(From),
1873 &BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001874 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001875 }
1876
Douglas Gregor46188682010-05-18 22:42:18 +00001877 case ICK_Vector_Conversion:
1878 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1879 break;
1880
1881 case ICK_Vector_Splat:
1882 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1883 break;
1884
1885 case ICK_Complex_Real:
1886 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1887 break;
1888
1889 case ICK_Lvalue_To_Rvalue:
1890 case ICK_Array_To_Pointer:
1891 case ICK_Function_To_Pointer:
1892 case ICK_Qualification:
1893 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001894 assert(false && "Improper second standard conversion");
1895 break;
1896 }
1897
1898 switch (SCS.Third) {
1899 case ICK_Identity:
1900 // Nothing to do.
1901 break;
1902
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001903 case ICK_Qualification: {
1904 // The qualification keeps the category of the inner expression, unless the
1905 // target type isn't a reference.
1906 ImplicitCastExpr::ResultCategory Category = ToType->isReferenceType() ?
1907 CastCategory(From) : ImplicitCastExpr::RValue;
Douglas Gregora8a089b2010-07-13 18:40:04 +00001908 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001909 CastExpr::CK_NoOp, Category);
Douglas Gregore489a7d2010-02-28 18:30:25 +00001910
1911 if (SCS.DeprecatedStringLiteralToCharPtr)
1912 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1913 << ToType.getNonReferenceType();
1914
Douglas Gregor39c16d42008-10-24 04:54:22 +00001915 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001916 }
1917
Douglas Gregor39c16d42008-10-24 04:54:22 +00001918 default:
Douglas Gregor46188682010-05-18 22:42:18 +00001919 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00001920 break;
1921 }
1922
1923 return false;
1924}
1925
John McCalldadc5752010-08-24 06:29:42 +00001926ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001927 SourceLocation KWLoc,
1928 SourceLocation LParen,
John McCallba7bf592010-08-24 05:47:05 +00001929 ParsedType Ty,
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001930 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001931 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001932
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001933 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1934 // all traits except __is_class, __is_enum and __is_union require a the type
1935 // to be complete.
1936 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001937 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001938 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001939 return ExprError();
1940 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001941
1942 // There is no point in eagerly computing the value. The traits are designed
1943 // to be used from type trait templates, so Ty will be a template parameter
1944 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001945 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1946 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001947}
Sebastian Redl5822f082009-02-07 20:10:22 +00001948
1949QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001950 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001951 const char *OpSpelling = isIndirect ? "->*" : ".*";
1952 // C++ 5.5p2
1953 // The binary operator .* [p3: ->*] binds its second operand, which shall
1954 // be of type "pointer to member of T" (where T is a completely-defined
1955 // class type) [...]
1956 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001957 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001958 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001959 Diag(Loc, diag::err_bad_memptr_rhs)
1960 << OpSpelling << RType << rex->getSourceRange();
1961 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001962 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001963
Sebastian Redl5822f082009-02-07 20:10:22 +00001964 QualType Class(MemPtr->getClass(), 0);
1965
Sebastian Redlc72350e2010-04-10 10:14:54 +00001966 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1967 return QualType();
1968
Sebastian Redl5822f082009-02-07 20:10:22 +00001969 // C++ 5.5p2
1970 // [...] to its first operand, which shall be of class T or of a class of
1971 // which T is an unambiguous and accessible base class. [p3: a pointer to
1972 // such a class]
1973 QualType LType = lex->getType();
1974 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001975 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001976 LType = Ptr->getPointeeType().getNonReferenceType();
1977 else {
1978 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001979 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001980 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001981 return QualType();
1982 }
1983 }
1984
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001985 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00001986 // If we want to check the hierarchy, we need a complete type.
1987 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1988 << OpSpelling << (int)isIndirect)) {
1989 return QualType();
1990 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001991 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001992 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001993 // FIXME: Would it be useful to print full ambiguity paths, or is that
1994 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001995 if (!IsDerivedFrom(LType, Class, Paths) ||
1996 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1997 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001998 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001999 return QualType();
2000 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002001 // Cast LHS to type of use.
2002 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002003 ImplicitCastExpr::ResultCategory Category =
2004 isIndirect ? ImplicitCastExpr::RValue : CastCategory(lex);
2005
John McCallcf142162010-08-07 06:22:56 +00002006 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00002007 BuildBasePathArray(Paths, BasePath);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002008 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, Category,
John McCallcf142162010-08-07 06:22:56 +00002009 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00002010 }
2011
Douglas Gregor747eb782010-07-08 06:14:04 +00002012 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00002013 // Diagnose use of pointer-to-member type which when used as
2014 // the functional cast in a pointer-to-member expression.
2015 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2016 return QualType();
2017 }
Sebastian Redl5822f082009-02-07 20:10:22 +00002018 // C++ 5.5p2
2019 // The result is an object or a function of the type specified by the
2020 // second operand.
2021 // The cv qualifiers are the union of those in the pointer and the left side,
2022 // in accordance with 5.5p5 and 5.2.5.
2023 // FIXME: This returns a dereferenced member function pointer as a normal
2024 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00002025 // calling them. There's also a GCC extension to get a function pointer to the
2026 // thing, which is another complication, because this type - unlike the type
2027 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00002028 // argument.
2029 // We probably need a "MemberFunctionClosureType" or something like that.
2030 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002031 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00002032 return Result;
2033}
Sebastian Redl1a99f442009-04-16 17:51:27 +00002034
Sebastian Redl1a99f442009-04-16 17:51:27 +00002035/// \brief Try to convert a type to another according to C++0x 5.16p3.
2036///
2037/// This is part of the parameter validation for the ? operator. If either
2038/// value operand is a class type, the two operands are attempted to be
2039/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002040/// It returns true if the program is ill-formed and has already been diagnosed
2041/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002042static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2043 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002044 bool &HaveConversion,
2045 QualType &ToType) {
2046 HaveConversion = false;
2047 ToType = To->getType();
2048
2049 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2050 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002051 // C++0x 5.16p3
2052 // The process for determining whether an operand expression E1 of type T1
2053 // can be converted to match an operand expression E2 of type T2 is defined
2054 // as follows:
2055 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00002056 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2057 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002058 // E1 can be converted to match E2 if E1 can be implicitly converted to
2059 // type "lvalue reference to T2", subject to the constraint that in the
2060 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002061 QualType T = Self.Context.getLValueReferenceType(ToType);
2062 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2063
2064 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2065 if (InitSeq.isDirectReferenceBinding()) {
2066 ToType = T;
2067 HaveConversion = true;
2068 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002069 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002070
2071 if (InitSeq.isAmbiguous())
2072 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002073 }
John McCall65eb8792010-02-25 01:37:24 +00002074
Sebastian Redl1a99f442009-04-16 17:51:27 +00002075 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2076 // -- if E1 and E2 have class type, and the underlying class types are
2077 // the same or one is a base class of the other:
2078 QualType FTy = From->getType();
2079 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002080 const RecordType *FRec = FTy->getAs<RecordType>();
2081 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002082 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2083 Self.IsDerivedFrom(FTy, TTy);
2084 if (FRec && TRec &&
2085 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002086 // E1 can be converted to match E2 if the class of T2 is the
2087 // same type as, or a base class of, the class of T1, and
2088 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002089 if (FRec == TRec || FDerivedFromT) {
2090 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002091 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2092 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2093 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2094 HaveConversion = true;
2095 return false;
2096 }
2097
2098 if (InitSeq.isAmbiguous())
2099 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2100 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002101 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002102
2103 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002104 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002105
2106 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2107 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002108 // if E2 were converted to an rvalue (or the type it has, if E2 is
2109 // an rvalue).
2110 //
2111 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2112 // to the array-to-pointer or function-to-pointer conversions.
2113 if (!TTy->getAs<TagType>())
2114 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002115
2116 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2117 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2118 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2119 ToType = TTy;
2120 if (InitSeq.isAmbiguous())
2121 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2122
Sebastian Redl1a99f442009-04-16 17:51:27 +00002123 return false;
2124}
2125
2126/// \brief Try to find a common type for two according to C++0x 5.16p5.
2127///
2128/// This is part of the parameter validation for the ? operator. If either
2129/// value operand is a class type, overload resolution is used to find a
2130/// conversion to a common type.
2131static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2132 SourceLocation Loc) {
2133 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002134 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002135 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002136
2137 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002138 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002139 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002140 // We found a match. Perform the conversions on the arguments and move on.
2141 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002142 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002143 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002144 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002145 break;
2146 return false;
2147
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002148 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002149 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2150 << LHS->getType() << RHS->getType()
2151 << LHS->getSourceRange() << RHS->getSourceRange();
2152 return true;
2153
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002154 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002155 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2156 << LHS->getType() << RHS->getType()
2157 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002158 // FIXME: Print the possible common types by printing the return types of
2159 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002160 break;
2161
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002162 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002163 assert(false && "Conditional operator has only built-in overloads");
2164 break;
2165 }
2166 return true;
2167}
2168
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002169/// \brief Perform an "extended" implicit conversion as returned by
2170/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002171static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2172 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2173 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2174 SourceLocation());
2175 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCalldadc5752010-08-24 06:29:42 +00002176 ExprResult Result = InitSeq.Perform(Self, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00002177 Sema::MultiExprArg(Self, &E, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00002178 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002179 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002180
2181 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002182 return false;
2183}
2184
Sebastian Redl1a99f442009-04-16 17:51:27 +00002185/// \brief Check the operands of ?: under C++ semantics.
2186///
2187/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2188/// extension. In this case, LHS == Cond. (But they're not aliases.)
2189QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2190 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002191 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2192 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002193
2194 // C++0x 5.16p1
2195 // The first expression is contextually converted to bool.
2196 if (!Cond->isTypeDependent()) {
2197 if (CheckCXXBooleanCondition(Cond))
2198 return QualType();
2199 }
2200
2201 // Either of the arguments dependent?
2202 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2203 return Context.DependentTy;
2204
2205 // C++0x 5.16p2
2206 // If either the second or the third operand has type (cv) void, ...
2207 QualType LTy = LHS->getType();
2208 QualType RTy = RHS->getType();
2209 bool LVoid = LTy->isVoidType();
2210 bool RVoid = RTy->isVoidType();
2211 if (LVoid || RVoid) {
2212 // ... then the [l2r] conversions are performed on the second and third
2213 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002214 DefaultFunctionArrayLvalueConversion(LHS);
2215 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002216 LTy = LHS->getType();
2217 RTy = RHS->getType();
2218
2219 // ... and one of the following shall hold:
2220 // -- The second or the third operand (but not both) is a throw-
2221 // expression; the result is of the type of the other and is an rvalue.
2222 bool LThrow = isa<CXXThrowExpr>(LHS);
2223 bool RThrow = isa<CXXThrowExpr>(RHS);
2224 if (LThrow && !RThrow)
2225 return RTy;
2226 if (RThrow && !LThrow)
2227 return LTy;
2228
2229 // -- Both the second and third operands have type void; the result is of
2230 // type void and is an rvalue.
2231 if (LVoid && RVoid)
2232 return Context.VoidTy;
2233
2234 // Neither holds, error.
2235 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2236 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2237 << LHS->getSourceRange() << RHS->getSourceRange();
2238 return QualType();
2239 }
2240
2241 // Neither is void.
2242
2243 // C++0x 5.16p3
2244 // Otherwise, if the second and third operand have different types, and
2245 // either has (cv) class type, and attempt is made to convert each of those
2246 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002247 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002248 (LTy->isRecordType() || RTy->isRecordType())) {
2249 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2250 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002251 QualType L2RType, R2LType;
2252 bool HaveL2R, HaveR2L;
2253 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002254 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002255 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002256 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002257
Sebastian Redl1a99f442009-04-16 17:51:27 +00002258 // If both can be converted, [...] the program is ill-formed.
2259 if (HaveL2R && HaveR2L) {
2260 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2261 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2262 return QualType();
2263 }
2264
2265 // If exactly one conversion is possible, that conversion is applied to
2266 // the chosen operand and the converted operands are used in place of the
2267 // original operands for the remainder of this section.
2268 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002269 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002270 return QualType();
2271 LTy = LHS->getType();
2272 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002273 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002274 return QualType();
2275 RTy = RHS->getType();
2276 }
2277 }
2278
2279 // C++0x 5.16p4
2280 // If the second and third operands are lvalues and have the same type,
2281 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002282 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002283 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2284 RHS->isLvalue(Context) == Expr::LV_Valid)
2285 return LTy;
2286
2287 // C++0x 5.16p5
2288 // Otherwise, the result is an rvalue. If the second and third operands
2289 // do not have the same type, and either has (cv) class type, ...
2290 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2291 // ... overload resolution is used to determine the conversions (if any)
2292 // to be applied to the operands. If the overload resolution fails, the
2293 // program is ill-formed.
2294 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2295 return QualType();
2296 }
2297
2298 // C++0x 5.16p6
2299 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2300 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002301 DefaultFunctionArrayLvalueConversion(LHS);
2302 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002303 LTy = LHS->getType();
2304 RTy = RHS->getType();
2305
2306 // After those conversions, one of the following shall hold:
2307 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002308 // is of that type. If the operands have class type, the result
2309 // is a prvalue temporary of the result type, which is
2310 // copy-initialized from either the second operand or the third
2311 // operand depending on the value of the first operand.
2312 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2313 if (LTy->isRecordType()) {
2314 // The operands have class type. Make a temporary copy.
2315 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCalldadc5752010-08-24 06:29:42 +00002316 ExprResult LHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002317 SourceLocation(),
2318 Owned(LHS));
2319 if (LHSCopy.isInvalid())
2320 return QualType();
2321
John McCalldadc5752010-08-24 06:29:42 +00002322 ExprResult RHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002323 SourceLocation(),
2324 Owned(RHS));
2325 if (RHSCopy.isInvalid())
2326 return QualType();
2327
2328 LHS = LHSCopy.takeAs<Expr>();
2329 RHS = RHSCopy.takeAs<Expr>();
2330 }
2331
Sebastian Redl1a99f442009-04-16 17:51:27 +00002332 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002333 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002334
Douglas Gregor46188682010-05-18 22:42:18 +00002335 // Extension: conditional operator involving vector types.
2336 if (LTy->isVectorType() || RTy->isVectorType())
2337 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2338
Sebastian Redl1a99f442009-04-16 17:51:27 +00002339 // -- The second and third operands have arithmetic or enumeration type;
2340 // the usual arithmetic conversions are performed to bring them to a
2341 // common type, and the result is of that type.
2342 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2343 UsualArithmeticConversions(LHS, RHS);
2344 return LHS->getType();
2345 }
2346
2347 // -- The second and third operands have pointer type, or one has pointer
2348 // type and the other is a null pointer constant; pointer conversions
2349 // and qualification conversions are performed to bring them to their
2350 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002351 // -- The second and third operands have pointer to member type, or one has
2352 // pointer to member type and the other is a null pointer constant;
2353 // pointer to member conversions and qualification conversions are
2354 // performed to bring them to a common type, whose cv-qualification
2355 // shall match the cv-qualification of either the second or the third
2356 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002357 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002358 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002359 isSFINAEContext()? 0 : &NonStandardCompositeType);
2360 if (!Composite.isNull()) {
2361 if (NonStandardCompositeType)
2362 Diag(QuestionLoc,
2363 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2364 << LTy << RTy << Composite
2365 << LHS->getSourceRange() << RHS->getSourceRange();
2366
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002367 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002368 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002369
Douglas Gregor697a3912010-04-01 22:47:07 +00002370 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002371 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2372 if (!Composite.isNull())
2373 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002374
Sebastian Redl1a99f442009-04-16 17:51:27 +00002375 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2376 << LHS->getType() << RHS->getType()
2377 << LHS->getSourceRange() << RHS->getSourceRange();
2378 return QualType();
2379}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002380
2381/// \brief Find a merged pointer type and convert the two expressions to it.
2382///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002383/// This finds the composite pointer type (or member pointer type) for @p E1
2384/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2385/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002386/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002387///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002388/// \param Loc The location of the operator requiring these two expressions to
2389/// be converted to the composite pointer type.
2390///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002391/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2392/// a non-standard (but still sane) composite type to which both expressions
2393/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2394/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002395QualType Sema::FindCompositePointerType(SourceLocation Loc,
2396 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002397 bool *NonStandardCompositeType) {
2398 if (NonStandardCompositeType)
2399 *NonStandardCompositeType = false;
2400
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002401 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2402 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002403
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002404 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2405 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002406 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002407
2408 // C++0x 5.9p2
2409 // Pointer conversions and qualification conversions are performed on
2410 // pointer operands to bring them to their composite pointer type. If
2411 // one operand is a null pointer constant, the composite pointer type is
2412 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002413 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002414 if (T2->isMemberPointerType())
2415 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2416 else
2417 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002418 return T2;
2419 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002420 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002421 if (T1->isMemberPointerType())
2422 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2423 else
2424 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002425 return T1;
2426 }
Mike Stump11289f42009-09-09 15:08:12 +00002427
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002428 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002429 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2430 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002431 return QualType();
2432
2433 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2434 // the other has type "pointer to cv2 T" and the composite pointer type is
2435 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2436 // Otherwise, the composite pointer type is a pointer type similar to the
2437 // type of one of the operands, with a cv-qualification signature that is
2438 // the union of the cv-qualification signatures of the operand types.
2439 // In practice, the first part here is redundant; it's subsumed by the second.
2440 // What we do here is, we build the two possible composite types, and try the
2441 // conversions in both directions. If only one works, or if the two composite
2442 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002443 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002444 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2445 QualifierVector QualifierUnion;
2446 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2447 ContainingClassVector;
2448 ContainingClassVector MemberOfClass;
2449 QualType Composite1 = Context.getCanonicalType(T1),
2450 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002451 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002452 do {
2453 const PointerType *Ptr1, *Ptr2;
2454 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2455 (Ptr2 = Composite2->getAs<PointerType>())) {
2456 Composite1 = Ptr1->getPointeeType();
2457 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002458
2459 // If we're allowed to create a non-standard composite type, keep track
2460 // of where we need to fill in additional 'const' qualifiers.
2461 if (NonStandardCompositeType &&
2462 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2463 NeedConstBefore = QualifierUnion.size();
2464
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002465 QualifierUnion.push_back(
2466 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2467 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2468 continue;
2469 }
Mike Stump11289f42009-09-09 15:08:12 +00002470
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002471 const MemberPointerType *MemPtr1, *MemPtr2;
2472 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2473 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2474 Composite1 = MemPtr1->getPointeeType();
2475 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002476
2477 // If we're allowed to create a non-standard composite type, keep track
2478 // of where we need to fill in additional 'const' qualifiers.
2479 if (NonStandardCompositeType &&
2480 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2481 NeedConstBefore = QualifierUnion.size();
2482
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002483 QualifierUnion.push_back(
2484 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2485 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2486 MemPtr2->getClass()));
2487 continue;
2488 }
Mike Stump11289f42009-09-09 15:08:12 +00002489
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002490 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002491
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002492 // Cannot unwrap any more types.
2493 break;
2494 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002495
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002496 if (NeedConstBefore && NonStandardCompositeType) {
2497 // Extension: Add 'const' to qualifiers that come before the first qualifier
2498 // mismatch, so that our (non-standard!) composite type meets the
2499 // requirements of C++ [conv.qual]p4 bullet 3.
2500 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2501 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2502 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2503 *NonStandardCompositeType = true;
2504 }
2505 }
2506 }
2507
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002508 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002509 ContainingClassVector::reverse_iterator MOC
2510 = MemberOfClass.rbegin();
2511 for (QualifierVector::reverse_iterator
2512 I = QualifierUnion.rbegin(),
2513 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002514 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002515 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002516 if (MOC->first && MOC->second) {
2517 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002518 Composite1 = Context.getMemberPointerType(
2519 Context.getQualifiedType(Composite1, Quals),
2520 MOC->first);
2521 Composite2 = Context.getMemberPointerType(
2522 Context.getQualifiedType(Composite2, Quals),
2523 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002524 } else {
2525 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002526 Composite1
2527 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2528 Composite2
2529 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002530 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002531 }
2532
Douglas Gregor19175ff2010-04-16 23:20:25 +00002533 // Try to convert to the first composite pointer type.
2534 InitializedEntity Entity1
2535 = InitializedEntity::InitializeTemporary(Composite1);
2536 InitializationKind Kind
2537 = InitializationKind::CreateCopy(Loc, SourceLocation());
2538 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2539 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00002540
Douglas Gregor19175ff2010-04-16 23:20:25 +00002541 if (E1ToC1 && E2ToC1) {
2542 // Conversion to Composite1 is viable.
2543 if (!Context.hasSameType(Composite1, Composite2)) {
2544 // Composite2 is a different type from Composite1. Check whether
2545 // Composite2 is also viable.
2546 InitializedEntity Entity2
2547 = InitializedEntity::InitializeTemporary(Composite2);
2548 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2549 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2550 if (E1ToC2 && E2ToC2) {
2551 // Both Composite1 and Composite2 are viable and are different;
2552 // this is an ambiguity.
2553 return QualType();
2554 }
2555 }
2556
2557 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00002558 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00002559 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00002560 if (E1Result.isInvalid())
2561 return QualType();
2562 E1 = E1Result.takeAs<Expr>();
2563
2564 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00002565 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00002566 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00002567 if (E2Result.isInvalid())
2568 return QualType();
2569 E2 = E2Result.takeAs<Expr>();
2570
2571 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002572 }
2573
Douglas Gregor19175ff2010-04-16 23:20:25 +00002574 // Check whether Composite2 is viable.
2575 InitializedEntity Entity2
2576 = InitializedEntity::InitializeTemporary(Composite2);
2577 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2578 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2579 if (!E1ToC2 || !E2ToC2)
2580 return QualType();
2581
2582 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00002583 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00002584 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00002585 if (E1Result.isInvalid())
2586 return QualType();
2587 E1 = E1Result.takeAs<Expr>();
2588
2589 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00002590 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00002591 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00002592 if (E2Result.isInvalid())
2593 return QualType();
2594 E2 = E2Result.takeAs<Expr>();
2595
2596 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002597}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002598
John McCalldadc5752010-08-24 06:29:42 +00002599ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002600 if (!Context.getLangOptions().CPlusPlus)
2601 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002602
Douglas Gregor363b1512009-12-24 18:51:59 +00002603 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2604
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002605 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002606 if (!RT)
2607 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002608
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002609 // If this is the result of a call or an Objective-C message send expression,
2610 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002611 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002612 if (CE->getCallReturnType()->isReferenceType())
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002613 return Owned(E);
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002614 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2615 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2616 if (MD->getResultType()->isReferenceType())
2617 return Owned(E);
2618 }
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002619 }
John McCall67da35c2010-02-04 22:26:26 +00002620
2621 // That should be enough to guarantee that this type is complete.
2622 // If it has a trivial destructor, we can avoid the extra copy.
2623 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00002624 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00002625 return Owned(E);
2626
Douglas Gregore71edda2010-07-01 22:47:18 +00002627 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002628 ExprTemporaries.push_back(Temp);
Douglas Gregore71edda2010-07-01 22:47:18 +00002629 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002630 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002631 CheckDestructorAccess(E->getExprLoc(), Destructor,
2632 PDiag(diag::err_access_dtor_temp)
2633 << E->getType());
2634 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002635 // FIXME: Add the temporary to the temporaries vector.
2636 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2637}
2638
Anders Carlsson6e997b22009-12-15 20:51:39 +00002639Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002640 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002641
John McCallcc7e5bf2010-05-06 08:58:33 +00002642 // Check any implicit conversions within the expression.
2643 CheckImplicitConversions(SubExpr);
2644
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002645 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2646 assert(ExprTemporaries.size() >= FirstTemporary);
2647 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002648 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002649
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002650 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002651 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002652 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002653 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2654 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002655
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002656 return E;
2657}
2658
John McCalldadc5752010-08-24 06:29:42 +00002659ExprResult
2660Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002661 if (SubExpr.isInvalid())
2662 return ExprError();
2663
2664 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2665}
2666
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002667FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2668 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2669 assert(ExprTemporaries.size() >= FirstTemporary);
2670
2671 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2672 CXXTemporary **Temporaries =
2673 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2674
2675 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2676
2677 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2678 ExprTemporaries.end());
2679
2680 return E;
2681}
2682
John McCalldadc5752010-08-24 06:29:42 +00002683ExprResult
John McCallb268a282010-08-23 23:25:46 +00002684Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00002685 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002686 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002687 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002688 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002689 if (Result.isInvalid()) return ExprError();
2690 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00002691
John McCallb268a282010-08-23 23:25:46 +00002692 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002693 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002694 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002695 // If we have a pointer to a dependent type and are using the -> operator,
2696 // the object type is the type that the pointer points to. We might still
2697 // have enough information about that type to do something useful.
2698 if (OpKind == tok::arrow)
2699 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2700 BaseType = Ptr->getPointeeType();
2701
John McCallba7bf592010-08-24 05:47:05 +00002702 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00002703 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00002704 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002705 }
Mike Stump11289f42009-09-09 15:08:12 +00002706
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002707 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002708 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002709 // returned, with the original second operand.
2710 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002711 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002712 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002713 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002714 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002715
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002716 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00002717 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
2718 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002719 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00002720 Base = Result.get();
2721 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002722 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00002723 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00002724 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002725 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002726 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002727 for (unsigned i = 0; i < Locations.size(); i++)
2728 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002729 return ExprError();
2730 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002731 }
Mike Stump11289f42009-09-09 15:08:12 +00002732
Douglas Gregore4f764f2009-11-20 19:58:21 +00002733 if (BaseType->isPointerType())
2734 BaseType = BaseType->getPointeeType();
2735 }
Mike Stump11289f42009-09-09 15:08:12 +00002736
2737 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002738 // vector types or Objective-C interfaces. Just return early and let
2739 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002740 if (!BaseType->isRecordType()) {
2741 // C++ [basic.lookup.classref]p2:
2742 // [...] If the type of the object expression is of pointer to scalar
2743 // type, the unqualified-id is looked up in the context of the complete
2744 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002745 //
2746 // This also indicates that we should be parsing a
2747 // pseudo-destructor-name.
John McCallba7bf592010-08-24 05:47:05 +00002748 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002749 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00002750 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002751 }
Mike Stump11289f42009-09-09 15:08:12 +00002752
Douglas Gregor3fad6172009-11-17 05:17:33 +00002753 // The object type must be complete (or dependent).
2754 if (!BaseType->isDependentType() &&
2755 RequireCompleteType(OpLoc, BaseType,
2756 PDiag(diag::err_incomplete_member_access)))
2757 return ExprError();
2758
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002759 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002760 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002761 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002762 // type C (or of pointer to a class type C), the unqualified-id is looked
2763 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00002764 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00002765 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002766}
2767
John McCalldadc5752010-08-24 06:29:42 +00002768ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00002769 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002770 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00002771 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
2772 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00002773 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002774
2775 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00002776 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002777 /*LPLoc*/ ExpectedLParenLoc,
2778 Sema::MultiExprArg(*this, 0, 0),
2779 /*CommaLocs*/ 0,
2780 /*RPLoc*/ ExpectedLParenLoc);
2781}
Douglas Gregore610ada2010-02-24 18:44:31 +00002782
John McCalldadc5752010-08-24 06:29:42 +00002783ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002784 SourceLocation OpLoc,
2785 tok::TokenKind OpKind,
2786 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002787 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002788 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002789 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002790 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002791 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002792 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002793
2794 // C++ [expr.pseudo]p2:
2795 // The left-hand side of the dot operator shall be of scalar type. The
2796 // left-hand side of the arrow operator shall be of pointer to scalar type.
2797 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00002798 QualType ObjectType = Base->getType();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002799 if (OpKind == tok::arrow) {
2800 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2801 ObjectType = Ptr->getPointeeType();
John McCallb268a282010-08-23 23:25:46 +00002802 } else if (!Base->isTypeDependent()) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002803 // The user wrote "p->" when she probably meant "p."; fix it.
2804 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2805 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002806 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002807 if (isSFINAEContext())
2808 return ExprError();
2809
2810 OpKind = tok::period;
2811 }
2812 }
2813
2814 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2815 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00002816 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002817 return ExprError();
2818 }
2819
2820 // C++ [expr.pseudo]p2:
2821 // [...] The cv-unqualified versions of the object type and of the type
2822 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002823 if (DestructedTypeInfo) {
2824 QualType DestructedType = DestructedTypeInfo->getType();
2825 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002826 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002827 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2828 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2829 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00002830 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002831 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002832
2833 // Recover by setting the destructed type to the object type.
2834 DestructedType = ObjectType;
2835 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2836 DestructedTypeStart);
2837 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2838 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002839 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002840
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002841 // C++ [expr.pseudo]p2:
2842 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2843 // form
2844 //
2845 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2846 //
2847 // shall designate the same scalar type.
2848 if (ScopeTypeInfo) {
2849 QualType ScopeType = ScopeTypeInfo->getType();
2850 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00002851 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002852
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002853 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002854 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00002855 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002856 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002857
2858 ScopeType = QualType();
2859 ScopeTypeInfo = 0;
2860 }
2861 }
2862
John McCallb268a282010-08-23 23:25:46 +00002863 Expr *Result
2864 = new (Context) CXXPseudoDestructorExpr(Context, Base,
2865 OpKind == tok::arrow, OpLoc,
2866 SS.getScopeRep(), SS.getRange(),
2867 ScopeTypeInfo,
2868 CCLoc,
2869 TildeLoc,
2870 Destructed);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002871
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002872 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00002873 return Owned(Result);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002874
John McCallb268a282010-08-23 23:25:46 +00002875 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002876}
2877
John McCalldadc5752010-08-24 06:29:42 +00002878ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002879 SourceLocation OpLoc,
2880 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002881 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002882 UnqualifiedId &FirstTypeName,
2883 SourceLocation CCLoc,
2884 SourceLocation TildeLoc,
2885 UnqualifiedId &SecondTypeName,
2886 bool HasTrailingLParen) {
2887 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2888 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2889 "Invalid first type name in pseudo-destructor");
2890 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2891 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2892 "Invalid second type name in pseudo-destructor");
2893
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002894 // C++ [expr.pseudo]p2:
2895 // The left-hand side of the dot operator shall be of scalar type. The
2896 // left-hand side of the arrow operator shall be of pointer to scalar type.
2897 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00002898 QualType ObjectType = Base->getType();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002899 if (OpKind == tok::arrow) {
2900 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2901 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002902 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002903 // The user wrote "p->" when she probably meant "p."; fix it.
2904 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002905 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002906 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002907 if (isSFINAEContext())
2908 return ExprError();
2909
2910 OpKind = tok::period;
2911 }
2912 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002913
2914 // Compute the object type that we should use for name lookup purposes. Only
2915 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00002916 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002917 if (!SS.isSet()) {
John McCallba7bf592010-08-24 05:47:05 +00002918 if (const Type *T = ObjectType->getAs<RecordType>())
2919 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
2920 else if (ObjectType->isDependentType())
2921 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002922 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002923
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002924 // Convert the name of the type being destructed (following the ~) into a
2925 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002926 QualType DestructedType;
2927 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002928 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002929 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallba7bf592010-08-24 05:47:05 +00002930 ParsedType T = getTypeName(*SecondTypeName.Identifier,
2931 SecondTypeName.StartLocation,
2932 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002933 if (!T &&
2934 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2935 (!SS.isSet() && ObjectType->isDependentType()))) {
2936 // The name of the type being destroyed is a dependent name, and we
2937 // couldn't find anything useful in scope. Just store the identifier and
2938 // it's location, and we'll perform (qualified) name lookup again at
2939 // template instantiation time.
2940 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2941 SecondTypeName.StartLocation);
2942 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002943 Diag(SecondTypeName.StartLocation,
2944 diag::err_pseudo_dtor_destructor_non_type)
2945 << SecondTypeName.Identifier << ObjectType;
2946 if (isSFINAEContext())
2947 return ExprError();
2948
2949 // Recover by assuming we had the right type all along.
2950 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002951 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002952 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002953 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002954 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002955 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002956 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2957 TemplateId->getTemplateArgs(),
2958 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00002959 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002960 TemplateId->TemplateNameLoc,
2961 TemplateId->LAngleLoc,
2962 TemplateArgsPtr,
2963 TemplateId->RAngleLoc);
2964 if (T.isInvalid() || !T.get()) {
2965 // Recover by assuming we had the right type all along.
2966 DestructedType = ObjectType;
2967 } else
2968 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002969 }
2970
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002971 // If we've performed some kind of recovery, (re-)build the type source
2972 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002973 if (!DestructedType.isNull()) {
2974 if (!DestructedTypeInfo)
2975 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002976 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002977 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2978 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002979
2980 // Convert the name of the scope type (the type prior to '::') into a type.
2981 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002982 QualType ScopeType;
2983 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2984 FirstTypeName.Identifier) {
2985 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallba7bf592010-08-24 05:47:05 +00002986 ParsedType T = getTypeName(*FirstTypeName.Identifier,
2987 FirstTypeName.StartLocation,
2988 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002989 if (!T) {
2990 Diag(FirstTypeName.StartLocation,
2991 diag::err_pseudo_dtor_destructor_non_type)
2992 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002993
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002994 if (isSFINAEContext())
2995 return ExprError();
2996
2997 // Just drop this type. It's unnecessary anyway.
2998 ScopeType = QualType();
2999 } else
3000 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003001 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003002 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003003 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003004 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3005 TemplateId->getTemplateArgs(),
3006 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00003007 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003008 TemplateId->TemplateNameLoc,
3009 TemplateId->LAngleLoc,
3010 TemplateArgsPtr,
3011 TemplateId->RAngleLoc);
3012 if (T.isInvalid() || !T.get()) {
3013 // Recover by dropping this type.
3014 ScopeType = QualType();
3015 } else
3016 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003017 }
3018 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00003019
3020 if (!ScopeType.isNull() && !ScopeTypeInfo)
3021 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3022 FirstTypeName.StartLocation);
3023
3024
John McCallb268a282010-08-23 23:25:46 +00003025 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003026 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003027 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00003028}
3029
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003030CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00003031 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003032 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00003033 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3034 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00003035 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3036
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003037 MemberExpr *ME =
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003038 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003039 SourceLocation(), Method->getType());
Douglas Gregor603d81b2010-07-13 08:18:22 +00003040 QualType ResultType = Method->getCallResultType();
Douglas Gregor27381f32009-11-23 12:27:39 +00003041 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3042 CXXMemberCallExpr *CE =
3043 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3044 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003045 return CE;
3046}
3047
John McCalldadc5752010-08-24 06:29:42 +00003048ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
John McCallb268a282010-08-23 23:25:46 +00003049 if (!FullExpr) return ExprError();
3050 return MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00003051}