blob: de9b59990726c5aaf5003d5acac07293107bb753 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000020#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000027#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000032
John McCallb3d87482010-08-24 05:47:05 +000033ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
34 IdentifierInfo &II,
35 SourceLocation NameLoc,
36 Scope *S, CXXScopeSpec &SS,
37 ParsedType ObjectTypePtr,
38 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000039 // Determine where to perform name lookup.
40
41 // FIXME: This area of the standard is very messy, and the current
42 // wording is rather unclear about which scopes we search for the
43 // destructor name; see core issues 399 and 555. Issue 399 in
44 // particular shows where the current description of destructor name
45 // lookup is completely out of line with existing practice, e.g.,
46 // this appears to be ill-formed:
47 //
48 // namespace N {
49 // template <typename T> struct S {
50 // ~S();
51 // };
52 // }
53 //
54 // void f(N::S<int>* s) {
55 // s->N::S<int>::~S();
56 // }
57 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000058 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000059 // For this reason, we're currently only doing the C++03 version of this
60 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000061 QualType SearchType;
62 DeclContext *LookupCtx = 0;
63 bool isDependent = false;
64 bool LookInScope = false;
65
66 // If we have an object type, it's because we are in a
67 // pseudo-destructor-expression or a member access expression, and
68 // we know what type we're looking for.
69 if (ObjectTypePtr)
70 SearchType = GetTypeFromParser(ObjectTypePtr);
71
72 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000073 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
74
75 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000077 // C++ [basic.lookup.qual]p6:
78 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
79 // the type-names are looked up as types in the scope designated by the
80 // nested-name-specifier. In a qualified-id of the form:
81 //
82 // ::[opt] nested-name-specifier ̃ class-name
83 //
84 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000085 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000086 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000087 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000089 // the class-names are looked up as types in the scope designated by
90 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000092 // Here, we check the first case (completely) and determine whether the
93 // code below is permitted to look at the prefix of the
94 // nested-name-specifier.
95 DeclContext *DC = computeDeclContext(SS, EnteringContext);
96 if (DC && DC->isFileContext()) {
97 AlreadySearched = true;
98 LookupCtx = DC;
99 isDependent = false;
100 } else if (DC && isa<CXXRecordDecl>(DC))
101 LookAtPrefix = false;
102
103 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000104 NestedNameSpecifier *Prefix = 0;
105 if (AlreadySearched) {
106 // Nothing left to do.
107 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
108 CXXScopeSpec PrefixSS;
109 PrefixSS.setScopeRep(Prefix);
110 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
111 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000112 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000113 LookupCtx = computeDeclContext(SearchType);
114 isDependent = SearchType->isDependentType();
115 } else {
116 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000117 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000119
Douglas Gregoredc90502010-02-25 04:46:04 +0000120 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000121 } else if (ObjectTypePtr) {
122 // C++ [basic.lookup.classref]p3:
123 // If the unqualified-id is ~type-name, the type-name is looked up
124 // in the context of the entire postfix-expression. If the type T
125 // of the object expression is of a class type C, the type-name is
126 // also looked up in the scope of class C. At least one of the
127 // lookups shall find a name that refers to (possibly
128 // cv-qualified) T.
129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 assert((isDependent || !SearchType->isIncompleteType()) &&
132 "Caller should have completed object type");
133
134 LookInScope = true;
135 } else {
136 // Perform lookup into the current scope (only).
137 LookInScope = true;
138 }
139
140 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
141 for (unsigned Step = 0; Step != 2; ++Step) {
142 // Look for the name first in the computed lookup context (if we
143 // have one) and, if that fails to find a match, in the sope (if
144 // we're allowed to look there).
145 Found.clear();
146 if (Step == 0 && LookupCtx)
147 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000148 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000149 LookupName(Found, S);
150 else
151 continue;
152
153 // FIXME: Should we be suppressing ambiguities here?
154 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000155 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000156
157 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
158 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000159
160 if (SearchType.isNull() || SearchType->isDependentType() ||
161 Context.hasSameUnqualifiedType(T, SearchType)) {
162 // We found our type!
163
John McCallb3d87482010-08-24 05:47:05 +0000164 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 }
166 }
167
168 // If the name that we found is a class template name, and it is
169 // the same name as the template name in the last part of the
170 // nested-name-specifier (if present) or the object type, then
171 // this is the destructor for that class.
172 // FIXME: This is a workaround until we get real drafting for core
173 // issue 399, for which there isn't even an obvious direction.
174 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
175 QualType MemberOfType;
176 if (SS.isSet()) {
177 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
178 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000179 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
180 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000181 }
182 }
183 if (MemberOfType.isNull())
184 MemberOfType = SearchType;
185
186 if (MemberOfType.isNull())
187 continue;
188
189 // We're referring into a class template specialization. If the
190 // class template we found is the same as the template being
191 // specialized, we found what we are looking for.
192 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
193 if (ClassTemplateSpecializationDecl *Spec
194 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
195 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
196 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000197 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000198 }
199
200 continue;
201 }
202
203 // We're referring to an unresolved class template
204 // specialization. Determine whether we class template we found
205 // is the same as the template being specialized or, if we don't
206 // know which template is being specialized, that it at least
207 // has the same name.
208 if (const TemplateSpecializationType *SpecType
209 = MemberOfType->getAs<TemplateSpecializationType>()) {
210 TemplateName SpecName = SpecType->getTemplateName();
211
212 // The class template we found is the same template being
213 // specialized.
214 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
215 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000216 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000217
218 continue;
219 }
220
221 // The class template we found has the same name as the
222 // (dependent) template name being specialized.
223 if (DependentTemplateName *DepTemplate
224 = SpecName.getAsDependentTemplateName()) {
225 if (DepTemplate->isIdentifier() &&
226 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000227 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000228
229 continue;
230 }
231 }
232 }
233 }
234
235 if (isDependent) {
236 // We didn't find our type, but that's okay: it's dependent
237 // anyway.
238 NestedNameSpecifier *NNS = 0;
239 SourceRange Range;
240 if (SS.isSet()) {
241 NNS = (NestedNameSpecifier *)SS.getScopeRep();
242 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
243 } else {
244 NNS = NestedNameSpecifier::Create(Context, &II);
245 Range = SourceRange(NameLoc);
246 }
247
John McCallb3d87482010-08-24 05:47:05 +0000248 QualType T = CheckTypenameType(ETK_None, NNS, II,
249 SourceLocation(),
250 Range, NameLoc);
251 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000252 }
253
254 if (ObjectTypePtr)
255 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
256 << &II;
257 else
258 Diag(NameLoc, diag::err_destructor_class_name);
259
John McCallb3d87482010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000261}
262
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000263/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000264ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000265 SourceLocation TypeidLoc,
266 TypeSourceInfo *Operand,
267 SourceLocation RParenLoc) {
268 // C++ [expr.typeid]p4:
269 // The top-level cv-qualifiers of the lvalue expression or the type-id
270 // that is the operand of typeid are always ignored.
271 // If the type of the type-id is a class type or a reference to a class
272 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000273 Qualifiers Quals;
274 QualType T
275 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
276 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000277 if (T->getAs<RecordType>() &&
278 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
279 return ExprError();
Daniel Dunbar380c2132010-05-11 21:32:35 +0000280
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000281 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
282 Operand,
283 SourceRange(TypeidLoc, RParenLoc)));
284}
285
286/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000288 SourceLocation TypeidLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000289 Expr *E,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000290 SourceLocation RParenLoc) {
291 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 if (E && !E->isTypeDependent()) {
293 QualType T = E->getType();
294 if (const RecordType *RecordT = T->getAs<RecordType>()) {
295 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
296 // C++ [expr.typeid]p3:
297 // [...] If the type of the expression is a class type, the class
298 // shall be completely-defined.
299 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
300 return ExprError();
301
302 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000303 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 // polymorphic class type [...] [the] expression is an unevaluated
305 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000306 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000308
309 // We require a vtable to query the type at run time.
310 MarkVTableUsed(TypeidLoc, RecordD);
311 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000312 }
313
314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
318 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000319 Qualifiers Quals;
320 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
321 if (!Context.hasSameType(T, UnqualT)) {
322 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000323 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000324 }
325 }
326
327 // If this is an unevaluated operand, clear out the set of
328 // declaration references we have been computing and eliminate any
329 // temporaries introduced in its computation.
330 if (isUnevaluatedOperand)
331 ExprEvalContexts.back().Context = Unevaluated;
332
333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000334 E,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000335 SourceRange(TypeidLoc, RParenLoc)));
336}
337
338/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000339ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000340Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
341 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000342 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000343 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000344 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000345
Chris Lattner572af492008-11-20 05:51:55 +0000346 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000347 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +0000348 LookupQualifiedName(R, getStdNamespace());
John McCall1bcee0a2009-12-02 08:25:40 +0000349 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000350 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000351 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000352
Sebastian Redlc42e1182008-11-11 11:37:55 +0000353 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000354
355 if (isType) {
356 // The operand is a type; handle it as such.
357 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000358 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
359 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000360 if (T.isNull())
361 return ExprError();
362
363 if (!TInfo)
364 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000365
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000367 }
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000370 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000371}
372
Steve Naroff1b273c42007-09-16 14:56:35 +0000373/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000374ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000375Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000376 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000378 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
379 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000380}
Chris Lattner50dd2892008-02-26 00:51:44 +0000381
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000382/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000383ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000384Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
385 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
386}
387
Chris Lattner50dd2892008-02-26 00:51:44 +0000388/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000389ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000390Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000391 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
392 return ExprError();
393 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
394}
395
396/// CheckCXXThrowOperand - Validate the operand of a throw.
397bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
398 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000399 // A throw-expression initializes a temporary object, called the exception
400 // object, the type of which is determined by removing any top-level
401 // cv-qualifiers from the static type of the operand of throw and adjusting
402 // the type from "array of T" or "function returning T" to "pointer to T"
403 // or "pointer to function returning T", [...]
404 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000405 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000406 CastCategory(E));
Douglas Gregor154fe982009-12-23 22:04:40 +0000407
Sebastian Redl972041f2009-04-27 20:27:31 +0000408 DefaultFunctionArrayConversion(E);
409
410 // If the type of the exception would be an incomplete type or a pointer
411 // to an incomplete type other than (cv) void the program is ill-formed.
412 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000413 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000414 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000415 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000416 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000417 }
418 if (!isPointer || !Ty->isVoidType()) {
419 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000420 PDiag(isPointer ? diag::err_throw_incomplete_ptr
421 : diag::err_throw_incomplete)
422 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000423 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000424
Douglas Gregorbf422f92010-04-15 18:05:39 +0000425 if (RequireNonAbstractType(ThrowLoc, E->getType(),
426 PDiag(diag::err_throw_abstract_type)
427 << E->getSourceRange()))
428 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000429 }
430
John McCallac418162010-04-22 01:10:34 +0000431 // Initialize the exception result. This implicitly weeds out
432 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000433 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000434 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000435 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
436 /*NRVO=*/false);
John McCall60d7b3a2010-08-24 06:29:42 +0000437 ExprResult Res = PerformCopyInitialization(Entity,
John McCallac418162010-04-22 01:10:34 +0000438 SourceLocation(),
439 Owned(E));
440 if (Res.isInvalid())
441 return true;
442 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000443
Eli Friedman5ed9b932010-06-03 20:39:03 +0000444 // If the exception has class type, we need additional handling.
445 const RecordType *RecordTy = Ty->getAs<RecordType>();
446 if (!RecordTy)
447 return false;
448 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
449
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000450 // If we are throwing a polymorphic class type or pointer thereof,
451 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000452 MarkVTableUsed(ThrowLoc, RD);
453
454 // If the class has a non-trivial destructor, we must be able to call it.
455 if (RD->hasTrivialDestructor())
456 return false;
457
Douglas Gregor1d110e02010-07-01 14:13:13 +0000458 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000459 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000460 if (!Destructor)
461 return false;
462
463 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
464 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000465 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000466 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000467}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000468
John McCall60d7b3a2010-08-24 06:29:42 +0000469ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000470 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
471 /// is a non-lvalue expression whose value is the address of the object for
472 /// which the function is called.
473
John McCallea1471e2010-05-20 01:18:31 +0000474 DeclContext *DC = getFunctionLevelDeclContext();
475 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000476 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000477 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000478 MD->getThisType(Context),
479 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000480
Sebastian Redlf53597f2009-03-15 17:47:39 +0000481 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000482}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000483
John McCall60d7b3a2010-08-24 06:29:42 +0000484ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000485Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000486 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000487 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000488 SourceLocation *CommaLocs,
489 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000490 if (!TypeRep)
491 return ExprError();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000492
John McCall9d125032010-01-15 18:39:57 +0000493 TypeSourceInfo *TInfo;
494 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
495 if (!TInfo)
496 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000497
498 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
499}
500
501/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
502/// Can be interpreted either as function-style casting ("int(x)")
503/// or class type construction ("ClassType(x,y,z)")
504/// or creation of a value-initialized type ("int()").
505ExprResult
506Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
507 SourceLocation LParenLoc,
508 MultiExprArg exprs,
509 SourceLocation RParenLoc) {
510 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000511 unsigned NumExprs = exprs.size();
512 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000513 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000514 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
515
Sebastian Redlf53597f2009-03-15 17:47:39 +0000516 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000517 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000518 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Douglas Gregorab6677e2010-09-08 00:15:04 +0000520 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000521 LParenLoc,
522 Exprs, NumExprs,
523 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000524 }
525
Anders Carlssonbb60a502009-08-27 03:53:50 +0000526 if (Ty->isArrayType())
527 return ExprError(Diag(TyBeginLoc,
528 diag::err_value_init_for_array_type) << FullRange);
529 if (!Ty->isVoidType() &&
530 RequireCompleteType(TyBeginLoc, Ty,
531 PDiag(diag::err_invalid_incomplete_type_use)
532 << FullRange))
533 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000534
Anders Carlssonbb60a502009-08-27 03:53:50 +0000535 if (RequireNonAbstractType(TyBeginLoc, Ty,
536 diag::err_allocation_of_abstract_type))
537 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000538
539
Douglas Gregor506ae412009-01-16 18:33:17 +0000540 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000541 // If the expression list is a single expression, the type conversion
542 // expression is equivalent (in definedness, and if defined in meaning) to the
543 // corresponding cast expression.
544 //
545 if (NumExprs == 1) {
John McCall2de56d12010-08-25 11:45:40 +0000546 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +0000547 CXXCastPath BasePath;
Douglas Gregorab6677e2010-09-08 00:15:04 +0000548 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
549 Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000550 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000551 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000552
553 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000554
John McCallf871d0c2010-08-07 06:22:56 +0000555 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000556 Ty.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000557 TInfo, TyBeginLoc, Kind,
558 Exprs[0], &BasePath,
559 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000560 }
561
Douglas Gregored8abf12010-07-08 06:14:04 +0000562 if (Ty->isRecordType()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +0000563 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Douglas Gregored8abf12010-07-08 06:14:04 +0000564 InitializationKind Kind
Douglas Gregorab6677e2010-09-08 00:15:04 +0000565 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
Douglas Gregored8abf12010-07-08 06:14:04 +0000566 LParenLoc, RParenLoc)
Douglas Gregorab6677e2010-09-08 00:15:04 +0000567 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregored8abf12010-07-08 06:14:04 +0000568 LParenLoc, RParenLoc);
569 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000570 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000571
Douglas Gregored8abf12010-07-08 06:14:04 +0000572 // FIXME: Improve AST representation?
573 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000574 }
575
576 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000577 // If the expression list specifies more than a single value, the type shall
578 // be a class with a suitably declared constructor.
579 //
580 if (NumExprs > 1)
Douglas Gregorab6677e2010-09-08 00:15:04 +0000581 return ExprError(Diag(PP.getLocForEndOfToken(Exprs[0]->getLocEnd()),
Sebastian Redlf53597f2009-03-15 17:47:39 +0000582 diag::err_builtin_func_cast_more_than_one_arg)
583 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000584
585 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregorab6677e2010-09-08 00:15:04 +0000586 // FIXME: Why doesn't this go through the new-initialization code?
587
Douglas Gregor506ae412009-01-16 18:33:17 +0000588 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000589 // The expression T(), where T is a simple-type-specifier for a non-array
590 // complete object type or the (possibly cv-qualified) void type, creates an
591 // rvalue of the specified type, which is value-initialized.
592 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000593 exprs.release();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000594 return Owned(new (Context) CXXScalarValueInitExpr(
595 TInfo->getType().getNonLValueExprType(Context),
596 TInfo, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000597}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000598
599
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000600/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
601/// @code new (memory) int[size][4] @endcode
602/// or
603/// @code ::new Foo(23, "hello") @endcode
604/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000605ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000606Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000607 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000608 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000609 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000610 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000611 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000612 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000613 // If the specified type is an array, unwrap it and save the expression.
614 if (D.getNumTypeObjects() > 0 &&
615 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
616 DeclaratorChunk &Chunk = D.getTypeObject(0);
617 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000618 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
619 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000620 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000621 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
622 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000623
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000624 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000625 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000626 }
627
Douglas Gregor043cad22009-09-11 00:18:58 +0000628 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000629 if (ArraySize) {
630 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000631 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
632 break;
633
634 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
635 if (Expr *NumElts = (Expr *)Array.NumElts) {
636 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
637 !NumElts->isIntegerConstantExpr(Context)) {
638 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
639 << NumElts->getSourceRange();
640 return ExprError();
641 }
642 }
643 }
644 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000645
John McCallbf1a0282010-06-04 23:28:52 +0000646 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
647 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000648 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000649 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000650
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000651 if (!TInfo)
652 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
653
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000654 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000655 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000656 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000657 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000658 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000659 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000660 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000661 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000662 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000663 ConstructorLParen,
664 move(ConstructorArgs),
665 ConstructorRParen);
666}
667
John McCall60d7b3a2010-08-24 06:29:42 +0000668ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000669Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
670 SourceLocation PlacementLParen,
671 MultiExprArg PlacementArgs,
672 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000673 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000674 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000675 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000676 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000677 SourceLocation ConstructorLParen,
678 MultiExprArg ConstructorArgs,
679 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000680 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
681 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000682 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000683
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000684 // Per C++0x [expr.new]p5, the type being constructed may be a
685 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000686 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000687 if (const ConstantArrayType *Array
688 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000689 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
690 Context.getSizeType(),
691 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000692 AllocType = Array->getElementType();
693 }
694 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000695
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000696 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000697
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000698 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
699 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000700 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000701
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000702 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000703
John McCall60d7b3a2010-08-24 06:29:42 +0000704 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000705 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000706 PDiag(diag::err_array_size_not_integral),
707 PDiag(diag::err_array_size_incomplete_type)
708 << ArraySize->getSourceRange(),
709 PDiag(diag::err_array_size_explicit_conversion),
710 PDiag(diag::note_array_size_conversion),
711 PDiag(diag::err_array_size_ambiguous_conversion),
712 PDiag(diag::note_array_size_conversion),
713 PDiag(getLangOptions().CPlusPlus0x? 0
714 : diag::ext_array_size_conversion));
715 if (ConvertedSize.isInvalid())
716 return ExprError();
717
John McCall9ae2f072010-08-23 23:25:46 +0000718 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000719 SizeType = ArraySize->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000720 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000721 return ExprError();
722
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000723 // Let's see if this is a constant < 0. If so, we reject it out of hand.
724 // We don't care about special rules, so we tell the machinery it's not
725 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000726 if (!ArraySize->isValueDependent()) {
727 llvm::APSInt Value;
728 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
729 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000730 llvm::APInt::getNullValue(Value.getBitWidth()),
731 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000732 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000733 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000734 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +0000735
736 if (!AllocType->isDependentType()) {
737 unsigned ActiveSizeBits
738 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
739 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
740 Diag(ArraySize->getSourceRange().getBegin(),
741 diag::err_array_too_large)
742 << Value.toString(10)
743 << ArraySize->getSourceRange();
744 return ExprError();
745 }
746 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000747 } else if (TypeIdParens.isValid()) {
748 // Can't have dynamic array size when the type-id is in parentheses.
749 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
750 << ArraySize->getSourceRange()
751 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
752 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
753
754 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000755 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000756 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000757
Eli Friedman73c39ab2009-10-20 08:27:19 +0000758 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000759 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000760 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000761
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000762 FunctionDecl *OperatorNew = 0;
763 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000764 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
765 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000766
Sebastian Redl28507842009-02-26 14:39:58 +0000767 if (!AllocType->isDependentType() &&
768 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
769 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000770 SourceRange(PlacementLParen, PlacementRParen),
771 UseGlobal, AllocType, ArraySize, PlaceArgs,
772 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000773 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000774 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000775 if (OperatorNew) {
776 // Add default arguments, if any.
777 const FunctionProtoType *Proto =
778 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000779 VariadicCallType CallType =
780 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000781
782 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
783 Proto, 1, PlaceArgs, NumPlaceArgs,
784 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000785 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000786
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000787 NumPlaceArgs = AllPlaceArgs.size();
788 if (NumPlaceArgs > 0)
789 PlaceArgs = &AllPlaceArgs[0];
790 }
791
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000792 bool Init = ConstructorLParen.isValid();
793 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000794 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000795 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
796 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000797 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000798
Anders Carlsson48c95012010-05-03 15:45:23 +0000799 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000800 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000801 SourceRange InitRange(ConsArgs[0]->getLocStart(),
802 ConsArgs[NumConsArgs - 1]->getLocEnd());
803
804 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
805 return ExprError();
806 }
807
Douglas Gregor99a2e602009-12-16 01:38:02 +0000808 if (!AllocType->isDependentType() &&
809 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
810 // C++0x [expr.new]p15:
811 // A new-expression that creates an object of type T initializes that
812 // object as follows:
813 InitializationKind Kind
814 // - If the new-initializer is omitted, the object is default-
815 // initialized (8.5); if no initialization is performed,
816 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000817 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
Douglas Gregor99a2e602009-12-16 01:38:02 +0000818 // - Otherwise, the new-initializer is interpreted according to the
819 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000820 : InitializationKind::CreateDirect(TypeRange.getBegin(),
Douglas Gregor99a2e602009-12-16 01:38:02 +0000821 ConstructorLParen,
822 ConstructorRParen);
823
Douglas Gregor99a2e602009-12-16 01:38:02 +0000824 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000825 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000826 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCall60d7b3a2010-08-24 06:29:42 +0000827 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000828 move(ConstructorArgs));
829 if (FullInit.isInvalid())
830 return ExprError();
831
832 // FullInit is our initializer; walk through it to determine if it's a
833 // constructor call, which CXXNewExpr handles directly.
834 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
835 if (CXXBindTemporaryExpr *Binder
836 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
837 FullInitExpr = Binder->getSubExpr();
838 if (CXXConstructExpr *Construct
839 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
840 Constructor = Construct->getConstructor();
841 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
842 AEnd = Construct->arg_end();
843 A != AEnd; ++A)
844 ConvertedConstructorArgs.push_back(A->Retain());
845 } else {
846 // Take the converted initializer.
847 ConvertedConstructorArgs.push_back(FullInit.release());
848 }
849 } else {
850 // No initialization required.
851 }
852
853 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000854 NumConsArgs = ConvertedConstructorArgs.size();
855 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000856 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000857
Douglas Gregor6d908702010-02-26 05:06:18 +0000858 // Mark the new and delete operators as referenced.
859 if (OperatorNew)
860 MarkDeclarationReferenced(StartLoc, OperatorNew);
861 if (OperatorDelete)
862 MarkDeclarationReferenced(StartLoc, OperatorDelete);
863
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000864 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000865
Sebastian Redlf53597f2009-03-15 17:47:39 +0000866 PlacementArgs.release();
867 ConstructorArgs.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000868
Ted Kremenekad7fe862010-02-11 22:51:03 +0000869 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000870 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000871 ArraySize, Constructor, Init,
872 ConsArgs, NumConsArgs, OperatorDelete,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000873 ResultType, AllocTypeInfo,
874 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000875 Init ? ConstructorRParen :
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000876 TypeRange.getEnd()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000877}
878
879/// CheckAllocatedType - Checks that a type is suitable as the allocated type
880/// in a new-expression.
881/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000882bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000883 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000884 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
885 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000886 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000887 return Diag(Loc, diag::err_bad_new_type)
888 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000889 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000890 return Diag(Loc, diag::err_bad_new_type)
891 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000892 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000893 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000894 PDiag(diag::err_new_incomplete_type)
895 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000896 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000897 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000898 diag::err_allocation_of_abstract_type))
899 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000900
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000901 return false;
902}
903
Douglas Gregor6d908702010-02-26 05:06:18 +0000904/// \brief Determine whether the given function is a non-placement
905/// deallocation function.
906static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
907 if (FD->isInvalidDecl())
908 return false;
909
910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
911 return Method->isUsualDeallocationFunction();
912
913 return ((FD->getOverloadedOperator() == OO_Delete ||
914 FD->getOverloadedOperator() == OO_Array_Delete) &&
915 FD->getNumParams() == 1);
916}
917
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000918/// FindAllocationFunctions - Finds the overloads of operator new and delete
919/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000920bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
921 bool UseGlobal, QualType AllocType,
922 bool IsArray, Expr **PlaceArgs,
923 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000924 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000925 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000926 // --- Choosing an allocation function ---
927 // C++ 5.3.4p8 - 14 & 18
928 // 1) If UseGlobal is true, only look in the global scope. Else, also look
929 // in the scope of the allocated class.
930 // 2) If an array size is given, look for operator new[], else look for
931 // operator new.
932 // 3) The first argument is always size_t. Append the arguments from the
933 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000934
935 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
936 // We don't care about the actual value of this argument.
937 // FIXME: Should the Sema create the expression and embed it in the syntax
938 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000939 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +0000940 Context.Target.getPointerWidth(0)),
941 Context.getSizeType(),
942 SourceLocation());
943 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000944 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
945
Douglas Gregor6d908702010-02-26 05:06:18 +0000946 // C++ [expr.new]p8:
947 // If the allocated type is a non-array type, the allocation
948 // function’s name is operator new and the deallocation function’s
949 // name is operator delete. If the allocated type is an array
950 // type, the allocation function’s name is operator new[] and the
951 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000952 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
953 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000954 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
955 IsArray ? OO_Array_Delete : OO_Delete);
956
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +0000957 QualType AllocElemType = Context.getBaseElementType(AllocType);
958
959 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000960 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +0000961 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000962 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000963 AllocArgs.size(), Record, /*AllowMissing=*/true,
964 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000965 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000966 }
967 if (!OperatorNew) {
968 // Didn't find a member overload. Look for a global one.
969 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000970 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000971 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000972 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
973 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000974 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000975 }
976
John McCall9c82afc2010-04-20 02:18:25 +0000977 // We don't need an operator delete if we're running under
978 // -fno-exceptions.
979 if (!getLangOptions().Exceptions) {
980 OperatorDelete = 0;
981 return false;
982 }
983
Anders Carlssond9583892009-05-31 20:26:12 +0000984 // FindAllocationOverload can change the passed in arguments, so we need to
985 // copy them back.
986 if (NumPlaceArgs > 0)
987 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregor6d908702010-02-26 05:06:18 +0000989 // C++ [expr.new]p19:
990 //
991 // If the new-expression begins with a unary :: operator, the
992 // deallocation function’s name is looked up in the global
993 // scope. Otherwise, if the allocated type is a class type T or an
994 // array thereof, the deallocation function’s name is looked up in
995 // the scope of T. If this lookup fails to find the name, or if
996 // the allocated type is not a class type or array thereof, the
997 // deallocation function’s name is looked up in the global scope.
998 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +0000999 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001000 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001001 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001002 LookupQualifiedName(FoundDelete, RD);
1003 }
John McCall90c8c572010-03-18 08:19:33 +00001004 if (FoundDelete.isAmbiguous())
1005 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001006
1007 if (FoundDelete.empty()) {
1008 DeclareGlobalNewDelete();
1009 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1010 }
1011
1012 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001013
1014 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1015
John McCall90c8c572010-03-18 08:19:33 +00001016 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001017 // C++ [expr.new]p20:
1018 // A declaration of a placement deallocation function matches the
1019 // declaration of a placement allocation function if it has the
1020 // same number of parameters and, after parameter transformations
1021 // (8.3.5), all parameter types except the first are
1022 // identical. [...]
1023 //
1024 // To perform this comparison, we compute the function type that
1025 // the deallocation function should have, and use that type both
1026 // for template argument deduction and for comparison purposes.
1027 QualType ExpectedFunctionType;
1028 {
1029 const FunctionProtoType *Proto
1030 = OperatorNew->getType()->getAs<FunctionProtoType>();
1031 llvm::SmallVector<QualType, 4> ArgTypes;
1032 ArgTypes.push_back(Context.VoidPtrTy);
1033 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1034 ArgTypes.push_back(Proto->getArgType(I));
1035
1036 ExpectedFunctionType
1037 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1038 ArgTypes.size(),
1039 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001040 0, false, false, 0, 0,
1041 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001042 }
1043
1044 for (LookupResult::iterator D = FoundDelete.begin(),
1045 DEnd = FoundDelete.end();
1046 D != DEnd; ++D) {
1047 FunctionDecl *Fn = 0;
1048 if (FunctionTemplateDecl *FnTmpl
1049 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1050 // Perform template argument deduction to try to match the
1051 // expected function type.
1052 TemplateDeductionInfo Info(Context, StartLoc);
1053 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1054 continue;
1055 } else
1056 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1057
1058 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001059 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001060 }
1061 } else {
1062 // C++ [expr.new]p20:
1063 // [...] Any non-placement deallocation function matches a
1064 // non-placement allocation function. [...]
1065 for (LookupResult::iterator D = FoundDelete.begin(),
1066 DEnd = FoundDelete.end();
1067 D != DEnd; ++D) {
1068 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1069 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001070 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001071 }
1072 }
1073
1074 // C++ [expr.new]p20:
1075 // [...] If the lookup finds a single matching deallocation
1076 // function, that function will be called; otherwise, no
1077 // deallocation function will be called.
1078 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001079 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001080
1081 // C++0x [expr.new]p20:
1082 // If the lookup finds the two-parameter form of a usual
1083 // deallocation function (3.7.4.2) and that function, considered
1084 // as a placement deallocation function, would have been
1085 // selected as a match for the allocation function, the program
1086 // is ill-formed.
1087 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1088 isNonPlacementDeallocationFunction(OperatorDelete)) {
1089 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1090 << SourceRange(PlaceArgs[0]->getLocStart(),
1091 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1092 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1093 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001094 } else {
1095 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001096 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001097 }
1098 }
1099
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001100 return false;
1101}
1102
Sebastian Redl7f662392008-12-04 22:20:51 +00001103/// FindAllocationOverload - Find an fitting overload for the allocation
1104/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001105bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1106 DeclarationName Name, Expr** Args,
1107 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001108 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001109 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1110 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001111 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001112 if (AllowMissing)
1113 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001114 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001115 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001116 }
1117
John McCall90c8c572010-03-18 08:19:33 +00001118 if (R.isAmbiguous())
1119 return true;
1120
1121 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001122
John McCall5769d612010-02-08 23:07:23 +00001123 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001124 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1125 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001126 // Even member operator new/delete are implicitly treated as
1127 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001128 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001129
John McCall9aa472c2010-03-19 07:35:19 +00001130 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1131 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001132 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1133 Candidates,
1134 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001135 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001136 }
1137
John McCall9aa472c2010-03-19 07:35:19 +00001138 FunctionDecl *Fn = cast<FunctionDecl>(D);
1139 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001140 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001141 }
1142
1143 // Do the resolution.
1144 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001145 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001146 case OR_Success: {
1147 // Got one!
1148 FunctionDecl *FnDecl = Best->Function;
1149 // The first argument is size_t, and the first parameter must be size_t,
1150 // too. This is checked on declaration and can be assumed. (It can't be
1151 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001152 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001153 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1154 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001155 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001156 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1157 FnDecl->getParamDecl(i)),
1158 SourceLocation(),
1159 Owned(Args[i]->Retain()));
1160 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001161 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001162
1163 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001164 }
1165 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001166 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001167 return false;
1168 }
1169
1170 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001171 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001172 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001173 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001174 return true;
1175
1176 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001177 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001178 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001179 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001180 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001181
1182 case OR_Deleted:
1183 Diag(StartLoc, diag::err_ovl_deleted_call)
1184 << Best->Function->isDeleted()
1185 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001186 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001187 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001188 }
1189 assert(false && "Unreachable, bad result from BestViableFunction");
1190 return true;
1191}
1192
1193
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001194/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1195/// delete. These are:
1196/// @code
1197/// void* operator new(std::size_t) throw(std::bad_alloc);
1198/// void* operator new[](std::size_t) throw(std::bad_alloc);
1199/// void operator delete(void *) throw();
1200/// void operator delete[](void *) throw();
1201/// @endcode
1202/// Note that the placement and nothrow forms of new are *not* implicitly
1203/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001204void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001205 if (GlobalNewDeleteDeclared)
1206 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001207
1208 // C++ [basic.std.dynamic]p2:
1209 // [...] The following allocation and deallocation functions (18.4) are
1210 // implicitly declared in global scope in each translation unit of a
1211 // program
1212 //
1213 // void* operator new(std::size_t) throw(std::bad_alloc);
1214 // void* operator new[](std::size_t) throw(std::bad_alloc);
1215 // void operator delete(void*) throw();
1216 // void operator delete[](void*) throw();
1217 //
1218 // These implicit declarations introduce only the function names operator
1219 // new, operator new[], operator delete, operator delete[].
1220 //
1221 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1222 // "std" or "bad_alloc" as necessary to form the exception specification.
1223 // However, we do not make these implicit declarations visible to name
1224 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001225 if (!StdBadAlloc) {
1226 // The "std::bad_alloc" class has not yet been declared, so build it
1227 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001228 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00001229 getOrCreateStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001230 SourceLocation(),
1231 &PP.getIdentifierTable().get("bad_alloc"),
1232 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001233 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001234 }
1235
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001236 GlobalNewDeleteDeclared = true;
1237
1238 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1239 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001240 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001241
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001242 DeclareGlobalAllocationFunction(
1243 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001244 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001245 DeclareGlobalAllocationFunction(
1246 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001247 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001248 DeclareGlobalAllocationFunction(
1249 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1250 Context.VoidTy, VoidPtr);
1251 DeclareGlobalAllocationFunction(
1252 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1253 Context.VoidTy, VoidPtr);
1254}
1255
1256/// DeclareGlobalAllocationFunction - Declares a single implicit global
1257/// allocation function if it doesn't already exist.
1258void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001259 QualType Return, QualType Argument,
1260 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001261 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1262
1263 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001264 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001265 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001266 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001267 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001268 // Only look at non-template functions, as it is the predefined,
1269 // non-templated allocation function we are trying to declare here.
1270 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1271 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001272 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001273 Func->getParamDecl(0)->getType().getUnqualifiedType());
1274 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001275 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1276 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001277 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001278 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001279 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001280 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001281 }
1282 }
1283
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001284 QualType BadAllocType;
1285 bool HasBadAllocExceptionSpec
1286 = (Name.getCXXOverloadedOperator() == OO_New ||
1287 Name.getCXXOverloadedOperator() == OO_Array_New);
1288 if (HasBadAllocExceptionSpec) {
1289 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001290 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001291 }
1292
1293 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1294 true, false,
1295 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001296 &BadAllocType,
1297 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001298 FunctionDecl *Alloc =
1299 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001300 FnType, /*TInfo=*/0, SC_None,
1301 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001302 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001303
1304 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001305 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopesfc284482009-12-16 16:59:22 +00001306
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001307 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001308 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001309 SC_None,
1310 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001311 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001312
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001313 // FIXME: Also add this declaration to the IdentifierResolver, but
1314 // make sure it is at the end of the chain to coincide with the
1315 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001316 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001317}
1318
Anders Carlsson78f74552009-11-15 18:45:20 +00001319bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1320 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001321 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001322 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001323 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001324 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001325
John McCalla24dc2e2009-11-17 02:14:36 +00001326 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001327 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001328
Chandler Carruth23893242010-06-28 00:30:51 +00001329 Found.suppressDiagnostics();
1330
John McCall046a7462010-08-04 00:31:26 +00001331 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001332 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1333 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001334 NamedDecl *ND = (*F)->getUnderlyingDecl();
1335
1336 // Ignore template operator delete members from the check for a usual
1337 // deallocation function.
1338 if (isa<FunctionTemplateDecl>(ND))
1339 continue;
1340
1341 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001342 Matches.push_back(F.getPair());
1343 }
1344
1345 // There's exactly one suitable operator; pick it.
1346 if (Matches.size() == 1) {
1347 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1348 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1349 Matches[0]);
1350 return false;
1351
1352 // We found multiple suitable operators; complain about the ambiguity.
1353 } else if (!Matches.empty()) {
1354 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1355 << Name << RD;
1356
1357 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1358 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1359 Diag((*F)->getUnderlyingDecl()->getLocation(),
1360 diag::note_member_declared_here) << Name;
1361 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001362 }
1363
1364 // We did find operator delete/operator delete[] declarations, but
1365 // none of them were suitable.
1366 if (!Found.empty()) {
1367 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1368 << Name << RD;
1369
1370 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001371 F != FEnd; ++F)
1372 Diag((*F)->getUnderlyingDecl()->getLocation(),
1373 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001374
1375 return true;
1376 }
1377
1378 // Look for a global declaration.
1379 DeclareGlobalNewDelete();
1380 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1381
1382 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1383 Expr* DeallocArgs[1];
1384 DeallocArgs[0] = &Null;
1385 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1386 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1387 Operator))
1388 return true;
1389
1390 assert(Operator && "Did not find a deallocation function!");
1391 return false;
1392}
1393
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001394/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1395/// @code ::delete ptr; @endcode
1396/// or
1397/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001398ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001399Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001400 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001401 // C++ [expr.delete]p1:
1402 // The operand shall have a pointer type, or a class type having a single
1403 // conversion function to a pointer type. The result has type void.
1404 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001405 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1406
Anders Carlssond67c4c32009-08-16 20:29:29 +00001407 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Sebastian Redl28507842009-02-26 14:39:58 +00001409 if (!Ex->isTypeDependent()) {
1410 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001411
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001412 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor254a9422010-07-29 14:44:35 +00001413 if (RequireCompleteType(StartLoc, Type,
1414 PDiag(diag::err_delete_incomplete_class_type)))
1415 return ExprError();
1416
John McCall32daa422010-03-31 01:36:47 +00001417 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1418
Fariborz Jahanian53462782009-09-11 21:44:33 +00001419 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001420 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001421 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001422 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001423 NamedDecl *D = I.getDecl();
1424 if (isa<UsingShadowDecl>(D))
1425 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1426
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001427 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001428 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001429 continue;
1430
John McCall32daa422010-03-31 01:36:47 +00001431 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001432
1433 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1434 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001435 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001436 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001437 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001438 if (ObjectPtrConversions.size() == 1) {
1439 // We have a single conversion to a pointer-to-object type. Perform
1440 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001441 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001442 if (!PerformImplicitConversion(Ex,
1443 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001444 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001445 Type = Ex->getType();
1446 }
1447 }
1448 else if (ObjectPtrConversions.size() > 1) {
1449 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1450 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001451 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1452 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001453 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001454 }
Sebastian Redl28507842009-02-26 14:39:58 +00001455 }
1456
Sebastian Redlf53597f2009-03-15 17:47:39 +00001457 if (!Type->isPointerType())
1458 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1459 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001460
Ted Kremenek6217b802009-07-29 21:53:49 +00001461 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001462 if (Pointee->isVoidType() && !isSFINAEContext()) {
1463 // The C++ standard bans deleting a pointer to a non-object type, which
1464 // effectively bans deletion of "void*". However, most compilers support
1465 // this, so we treat it as a warning unless we're in a SFINAE context.
1466 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1467 << Type << Ex->getSourceRange();
1468 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001469 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1470 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001471 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001472 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001473 PDiag(diag::warn_delete_incomplete)
1474 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001475 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001476
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001477 // C++ [expr.delete]p2:
1478 // [Note: a pointer to a const type can be the operand of a
1479 // delete-expression; it is not necessary to cast away the constness
1480 // (5.2.11) of the pointer expression before it is used as the operand
1481 // of the delete-expression. ]
1482 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001483 CK_NoOp);
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001484
Anders Carlssond67c4c32009-08-16 20:29:29 +00001485 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1486 ArrayForm ? OO_Array_Delete : OO_Delete);
1487
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001488 QualType PointeeElem = Context.getBaseElementType(Pointee);
1489 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001490 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1491
1492 if (!UseGlobal &&
1493 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001494 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001495
Anders Carlsson78f74552009-11-15 18:45:20 +00001496 if (!RD->hasTrivialDestructor())
Douglas Gregordb89f282010-07-01 22:47:18 +00001497 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump1eb44332009-09-09 15:08:12 +00001498 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001499 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001500 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001501
Anders Carlssond67c4c32009-08-16 20:29:29 +00001502 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001503 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001504 DeclareGlobalNewDelete();
1505 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001506 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001507 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001508 OperatorDelete))
1509 return ExprError();
1510 }
Mike Stump1eb44332009-09-09 15:08:12 +00001511
John McCall9c82afc2010-04-20 02:18:25 +00001512 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1513
Sebastian Redl28507842009-02-26 14:39:58 +00001514 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001515 }
1516
Sebastian Redlf53597f2009-03-15 17:47:39 +00001517 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001518 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001519}
1520
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001521/// \brief Check the use of the given variable as a C++ condition in an if,
1522/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001523ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
Douglas Gregor586596f2010-05-06 17:25:47 +00001524 SourceLocation StmtLoc,
1525 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001526 QualType T = ConditionVar->getType();
1527
1528 // C++ [stmt.select]p2:
1529 // The declarator shall not specify a function or an array.
1530 if (T->isFunctionType())
1531 return ExprError(Diag(ConditionVar->getLocation(),
1532 diag::err_invalid_use_of_function_type)
1533 << ConditionVar->getSourceRange());
1534 else if (T->isArrayType())
1535 return ExprError(Diag(ConditionVar->getLocation(),
1536 diag::err_invalid_use_of_array_type)
1537 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001538
Douglas Gregor586596f2010-05-06 17:25:47 +00001539 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1540 ConditionVar->getLocation(),
1541 ConditionVar->getType().getNonReferenceType());
Douglas Gregorff331c12010-07-25 18:17:45 +00001542 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001543 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00001544
1545 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001546}
1547
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001548/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1549bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1550 // C++ 6.4p4:
1551 // The value of a condition that is an initialized declaration in a statement
1552 // other than a switch statement is the value of the declared variable
1553 // implicitly converted to type bool. If that conversion is ill-formed, the
1554 // program is ill-formed.
1555 // The value of a condition that is an expression is the value of the
1556 // expression, implicitly converted to bool.
1557 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001558 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001559}
Douglas Gregor77a52232008-09-12 00:47:35 +00001560
1561/// Helper function to determine whether this is the (deprecated) C++
1562/// conversion from a string literal to a pointer to non-const char or
1563/// non-const wchar_t (for narrow and wide string literals,
1564/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001565bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001566Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1567 // Look inside the implicit cast, if it exists.
1568 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1569 From = Cast->getSubExpr();
1570
1571 // A string literal (2.13.4) that is not a wide string literal can
1572 // be converted to an rvalue of type "pointer to char"; a wide
1573 // string literal can be converted to an rvalue of type "pointer
1574 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001575 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001576 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001577 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001578 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001579 // This conversion is considered only when there is an
1580 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001581 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001582 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1583 (!StrLit->isWide() &&
1584 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1585 ToPointeeType->getKind() == BuiltinType::Char_S))))
1586 return true;
1587 }
1588
1589 return false;
1590}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001591
John McCall60d7b3a2010-08-24 06:29:42 +00001592static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001593 SourceLocation CastLoc,
1594 QualType Ty,
1595 CastKind Kind,
1596 CXXMethodDecl *Method,
1597 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001598 switch (Kind) {
1599 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001600 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001601 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001602
1603 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001604 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001605 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001606 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001607
John McCall60d7b3a2010-08-24 06:29:42 +00001608 ExprResult Result =
Douglas Gregorba70ab62010-04-16 22:17:36 +00001609 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001610 move_arg(ConstructorArgs),
1611 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001612 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001613 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001614
1615 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1616 }
1617
John McCall2de56d12010-08-25 11:45:40 +00001618 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001619 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1620
1621 // Create an implicit call expr that calls it.
1622 // FIXME: pass the FoundDecl for the user-defined conversion here
1623 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1624 return S.MaybeBindToTemporary(CE);
1625 }
1626 }
1627}
1628
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001629/// PerformImplicitConversion - Perform an implicit conversion of the
1630/// expression From to the type ToType using the pre-computed implicit
1631/// conversion sequence ICS. Returns true if there was an error, false
1632/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001633/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001634/// used in the error message.
1635bool
1636Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1637 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001638 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001639 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001640 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001641 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001642 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001643 return true;
1644 break;
1645
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001646 case ImplicitConversionSequence::UserDefinedConversion: {
1647
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001648 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall2de56d12010-08-25 11:45:40 +00001649 CastKind CastKind = CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001650 QualType BeforeToType;
1651 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001652 CastKind = CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001653
1654 // If the user-defined conversion is specified by a conversion function,
1655 // the initial standard conversion sequence converts the source type to
1656 // the implicit object parameter of the conversion function.
1657 BeforeToType = Context.getTagDeclType(Conv->getParent());
1658 } else if (const CXXConstructorDecl *Ctor =
1659 dyn_cast<CXXConstructorDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001660 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001661 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001662 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001663 // If the user-defined conversion is specified by a constructor, the
1664 // initial standard conversion sequence converts the source type to the
1665 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001666 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1667 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001668 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001669 else
1670 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001671 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001672 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001673 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001674 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001675 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001676 return true;
1677 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001678
John McCall60d7b3a2010-08-24 06:29:42 +00001679 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001680 = BuildCXXCastArgument(*this,
1681 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001682 ToType.getNonReferenceType(),
1683 CastKind, cast<CXXMethodDecl>(FD),
John McCall9ae2f072010-08-23 23:25:46 +00001684 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001685
1686 if (CastArg.isInvalid())
1687 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001688
1689 From = CastArg.takeAs<Expr>();
1690
Eli Friedmand8889622009-11-27 04:41:50 +00001691 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001692 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001693 }
John McCall1d318332010-01-12 00:44:57 +00001694
1695 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001696 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001697 PDiag(diag::err_typecheck_ambiguous_condition)
1698 << From->getSourceRange());
1699 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001700
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001701 case ImplicitConversionSequence::EllipsisConversion:
1702 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001703 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001704
1705 case ImplicitConversionSequence::BadConversion:
1706 return true;
1707 }
1708
1709 // Everything went well.
1710 return false;
1711}
1712
1713/// PerformImplicitConversion - Perform an implicit conversion of the
1714/// expression From to the type ToType by following the standard
1715/// conversion sequence SCS. Returns true if there was an error, false
1716/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001717/// expression. Flavor is the context in which we're performing this
1718/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001719bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001720Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001721 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001722 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001723 // Overall FIXME: we are recomputing too many types here and doing far too
1724 // much extra work. What this means is that we need to keep track of more
1725 // information that is computed when we try the implicit conversion initially,
1726 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001727 QualType FromType = From->getType();
1728
Douglas Gregor225c41e2008-11-03 19:09:14 +00001729 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001730 // FIXME: When can ToType be a reference type?
1731 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001732 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001733 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001734 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001735 MultiExprArg(*this, &From, 1),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001736 /*FIXME:ConstructLoc*/SourceLocation(),
1737 ConstructorArgs))
1738 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001739 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001740 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1741 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001742 move_arg(ConstructorArgs),
1743 /*ZeroInit*/ false,
1744 CXXConstructExpr::CK_Complete);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001745 if (FromResult.isInvalid())
1746 return true;
1747 From = FromResult.takeAs<Expr>();
1748 return false;
1749 }
John McCall60d7b3a2010-08-24 06:29:42 +00001750 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001751 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1752 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001753 MultiExprArg(*this, &From, 1),
1754 /*ZeroInit*/ false,
1755 CXXConstructExpr::CK_Complete);
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001757 if (FromResult.isInvalid())
1758 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001760 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001761 return false;
1762 }
1763
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001764 // Resolve overloaded function references.
1765 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1766 DeclAccessPair Found;
1767 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1768 true, Found);
1769 if (!Fn)
1770 return true;
1771
1772 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1773 return true;
1774
1775 From = FixOverloadedFunctionReference(From, Found, Fn);
1776 FromType = From->getType();
1777 }
1778
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001779 // Perform the first implicit conversion.
1780 switch (SCS.First) {
1781 case ICK_Identity:
1782 case ICK_Lvalue_To_Rvalue:
1783 // Nothing to do.
1784 break;
1785
1786 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001787 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001788 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001789 break;
1790
1791 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001792 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001793 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001794 break;
1795
1796 default:
1797 assert(false && "Improper first standard conversion");
1798 break;
1799 }
1800
1801 // Perform the second implicit conversion
1802 switch (SCS.Second) {
1803 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001804 // If both sides are functions (or pointers/references to them), there could
1805 // be incompatible exception declarations.
1806 if (CheckExceptionSpecCompatibility(From, ToType))
1807 return true;
1808 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001809 break;
1810
Douglas Gregor43c79c22009-12-09 00:47:37 +00001811 case ICK_NoReturn_Adjustment:
1812 // If both sides are functions (or pointers/references to them), there could
1813 // be incompatible exception declarations.
1814 if (CheckExceptionSpecCompatibility(From, ToType))
1815 return true;
1816
1817 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
John McCall2de56d12010-08-25 11:45:40 +00001818 CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001819 break;
1820
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001821 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001822 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001823 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001824 break;
1825
1826 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001827 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001828 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001829 break;
1830
1831 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001832 case ICK_Complex_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001833 ImpCastExprToType(From, ToType, CK_Unknown);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001834 break;
1835
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001836 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001837 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00001838 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001839 else
John McCall2de56d12010-08-25 11:45:40 +00001840 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001841 break;
1842
Douglas Gregorf9201e02009-02-11 23:02:49 +00001843 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001844 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001845 break;
1846
Anders Carlsson61faec12009-09-12 04:46:44 +00001847 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001848 if (SCS.IncompatibleObjC) {
1849 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001850 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001851 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001852 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001853 << From->getSourceRange();
1854 }
1855
Anders Carlsson61faec12009-09-12 04:46:44 +00001856
John McCall2de56d12010-08-25 11:45:40 +00001857 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00001858 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001859 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001860 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001861 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001862 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001863 }
1864
1865 case ICK_Pointer_Member: {
John McCall2de56d12010-08-25 11:45:40 +00001866 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00001867 CXXCastPath BasePath;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001868 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1869 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001870 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001871 if (CheckExceptionSpecCompatibility(From, ToType))
1872 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001873 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001874 break;
1875 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001876 case ICK_Boolean_Conversion: {
John McCall2de56d12010-08-25 11:45:40 +00001877 CastKind Kind = CK_Unknown;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001878 if (FromType->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00001879 Kind = CK_MemberPointerToBoolean;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001880
1881 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001882 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001883 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001884
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001885 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00001886 CXXCastPath BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001887 if (CheckDerivedToBaseConversion(From->getType(),
1888 ToType.getNonReferenceType(),
1889 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001890 From->getSourceRange(),
1891 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001892 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001893 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001894
Sebastian Redl906082e2010-07-20 04:20:21 +00001895 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00001896 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00001897 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001898 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001899 }
1900
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001901 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001902 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001903 break;
1904
1905 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00001906 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001907 break;
1908
1909 case ICK_Complex_Real:
John McCall2de56d12010-08-25 11:45:40 +00001910 ImpCastExprToType(From, ToType, CK_Unknown);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001911 break;
1912
1913 case ICK_Lvalue_To_Rvalue:
1914 case ICK_Array_To_Pointer:
1915 case ICK_Function_To_Pointer:
1916 case ICK_Qualification:
1917 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001918 assert(false && "Improper second standard conversion");
1919 break;
1920 }
1921
1922 switch (SCS.Third) {
1923 case ICK_Identity:
1924 // Nothing to do.
1925 break;
1926
Sebastian Redl906082e2010-07-20 04:20:21 +00001927 case ICK_Qualification: {
1928 // The qualification keeps the category of the inner expression, unless the
1929 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00001930 ExprValueKind VK = ToType->isReferenceType() ?
1931 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00001932 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00001933 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00001934
1935 if (SCS.DeprecatedStringLiteralToCharPtr)
1936 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1937 << ToType.getNonReferenceType();
1938
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001939 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00001940 }
1941
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001942 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001943 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001944 break;
1945 }
1946
1947 return false;
1948}
1949
John McCall60d7b3a2010-08-24 06:29:42 +00001950ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +00001951 SourceLocation KWLoc,
1952 SourceLocation LParen,
John McCallb3d87482010-08-24 05:47:05 +00001953 ParsedType Ty,
Sebastian Redl64b45f72009-01-05 20:52:13 +00001954 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001955 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001957 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1958 // all traits except __is_class, __is_enum and __is_union require a the type
1959 // to be complete.
1960 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001961 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001962 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001963 return ExprError();
1964 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001965
1966 // There is no point in eagerly computing the value. The traits are designed
1967 // to be used from type trait templates, so Ty will be a template parameter
1968 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001969 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1970 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001971}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001972
1973QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001974 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001975 const char *OpSpelling = isIndirect ? "->*" : ".*";
1976 // C++ 5.5p2
1977 // The binary operator .* [p3: ->*] binds its second operand, which shall
1978 // be of type "pointer to member of T" (where T is a completely-defined
1979 // class type) [...]
1980 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001981 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001982 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001983 Diag(Loc, diag::err_bad_memptr_rhs)
1984 << OpSpelling << RType << rex->getSourceRange();
1985 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001986 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001987
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001988 QualType Class(MemPtr->getClass(), 0);
1989
Sebastian Redl59fc2692010-04-10 10:14:54 +00001990 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1991 return QualType();
1992
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001993 // C++ 5.5p2
1994 // [...] to its first operand, which shall be of class T or of a class of
1995 // which T is an unambiguous and accessible base class. [p3: a pointer to
1996 // such a class]
1997 QualType LType = lex->getType();
1998 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001999 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002000 LType = Ptr->getPointeeType().getNonReferenceType();
2001 else {
2002 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002003 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002004 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002005 return QualType();
2006 }
2007 }
2008
Douglas Gregora4923eb2009-11-16 21:35:15 +00002009 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002010 // If we want to check the hierarchy, we need a complete type.
2011 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2012 << OpSpelling << (int)isIndirect)) {
2013 return QualType();
2014 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002015 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002016 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002017 // FIXME: Would it be useful to print full ambiguity paths, or is that
2018 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002019 if (!IsDerivedFrom(LType, Class, Paths) ||
2020 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2021 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002022 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002023 return QualType();
2024 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002025 // Cast LHS to type of use.
2026 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002027 ExprValueKind VK =
2028 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002029
John McCallf871d0c2010-08-07 06:22:56 +00002030 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002031 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002032 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002033 }
2034
Douglas Gregored8abf12010-07-08 06:14:04 +00002035 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002036 // Diagnose use of pointer-to-member type which when used as
2037 // the functional cast in a pointer-to-member expression.
2038 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2039 return QualType();
2040 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002041 // C++ 5.5p2
2042 // The result is an object or a function of the type specified by the
2043 // second operand.
2044 // The cv qualifiers are the union of those in the pointer and the left side,
2045 // in accordance with 5.5p5 and 5.2.5.
2046 // FIXME: This returns a dereferenced member function pointer as a normal
2047 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002048 // calling them. There's also a GCC extension to get a function pointer to the
2049 // thing, which is another complication, because this type - unlike the type
2050 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002051 // argument.
2052 // We probably need a "MemberFunctionClosureType" or something like that.
2053 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002054 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002055 return Result;
2056}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002057
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002058/// \brief Try to convert a type to another according to C++0x 5.16p3.
2059///
2060/// This is part of the parameter validation for the ? operator. If either
2061/// value operand is a class type, the two operands are attempted to be
2062/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002063/// It returns true if the program is ill-formed and has already been diagnosed
2064/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002065static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2066 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002067 bool &HaveConversion,
2068 QualType &ToType) {
2069 HaveConversion = false;
2070 ToType = To->getType();
2071
2072 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2073 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002074 // C++0x 5.16p3
2075 // The process for determining whether an operand expression E1 of type T1
2076 // can be converted to match an operand expression E2 of type T2 is defined
2077 // as follows:
2078 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002079 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2080 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002081 // E1 can be converted to match E2 if E1 can be implicitly converted to
2082 // type "lvalue reference to T2", subject to the constraint that in the
2083 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002084 QualType T = Self.Context.getLValueReferenceType(ToType);
2085 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2086
2087 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2088 if (InitSeq.isDirectReferenceBinding()) {
2089 ToType = T;
2090 HaveConversion = true;
2091 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002092 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002093
2094 if (InitSeq.isAmbiguous())
2095 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002096 }
John McCallb1bdc622010-02-25 01:37:24 +00002097
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002098 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2099 // -- if E1 and E2 have class type, and the underlying class types are
2100 // the same or one is a base class of the other:
2101 QualType FTy = From->getType();
2102 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002103 const RecordType *FRec = FTy->getAs<RecordType>();
2104 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002105 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2106 Self.IsDerivedFrom(FTy, TTy);
2107 if (FRec && TRec &&
2108 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002109 // E1 can be converted to match E2 if the class of T2 is the
2110 // same type as, or a base class of, the class of T1, and
2111 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002112 if (FRec == TRec || FDerivedFromT) {
2113 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002114 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2115 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2116 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2117 HaveConversion = true;
2118 return false;
2119 }
2120
2121 if (InitSeq.isAmbiguous())
2122 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2123 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002124 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002125
2126 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002127 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002128
2129 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2130 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002131 // if E2 were converted to an rvalue (or the type it has, if E2 is
2132 // an rvalue).
2133 //
2134 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2135 // to the array-to-pointer or function-to-pointer conversions.
2136 if (!TTy->getAs<TagType>())
2137 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002138
2139 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2140 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2141 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2142 ToType = TTy;
2143 if (InitSeq.isAmbiguous())
2144 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2145
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002146 return false;
2147}
2148
2149/// \brief Try to find a common type for two according to C++0x 5.16p5.
2150///
2151/// This is part of the parameter validation for the ? operator. If either
2152/// value operand is a class type, overload resolution is used to find a
2153/// conversion to a common type.
2154static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2155 SourceLocation Loc) {
2156 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002157 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002158 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002159
2160 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002161 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002162 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002163 // We found a match. Perform the conversions on the arguments and move on.
2164 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002165 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002166 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002167 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002168 break;
2169 return false;
2170
Douglas Gregor20093b42009-12-09 23:02:17 +00002171 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002172 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2173 << LHS->getType() << RHS->getType()
2174 << LHS->getSourceRange() << RHS->getSourceRange();
2175 return true;
2176
Douglas Gregor20093b42009-12-09 23:02:17 +00002177 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002178 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2179 << LHS->getType() << RHS->getType()
2180 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002181 // FIXME: Print the possible common types by printing the return types of
2182 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002183 break;
2184
Douglas Gregor20093b42009-12-09 23:02:17 +00002185 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002186 assert(false && "Conditional operator has only built-in overloads");
2187 break;
2188 }
2189 return true;
2190}
2191
Sebastian Redl76458502009-04-17 16:30:52 +00002192/// \brief Perform an "extended" implicit conversion as returned by
2193/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002194static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2195 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2196 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2197 SourceLocation());
2198 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002199 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002200 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002201 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002202
2203 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002204 return false;
2205}
2206
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002207/// \brief Check the operands of ?: under C++ semantics.
2208///
2209/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2210/// extension. In this case, LHS == Cond. (But they're not aliases.)
2211QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2212 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002213 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2214 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002215
2216 // C++0x 5.16p1
2217 // The first expression is contextually converted to bool.
2218 if (!Cond->isTypeDependent()) {
2219 if (CheckCXXBooleanCondition(Cond))
2220 return QualType();
2221 }
2222
2223 // Either of the arguments dependent?
2224 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2225 return Context.DependentTy;
2226
2227 // C++0x 5.16p2
2228 // If either the second or the third operand has type (cv) void, ...
2229 QualType LTy = LHS->getType();
2230 QualType RTy = RHS->getType();
2231 bool LVoid = LTy->isVoidType();
2232 bool RVoid = RTy->isVoidType();
2233 if (LVoid || RVoid) {
2234 // ... then the [l2r] conversions are performed on the second and third
2235 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002236 DefaultFunctionArrayLvalueConversion(LHS);
2237 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002238 LTy = LHS->getType();
2239 RTy = RHS->getType();
2240
2241 // ... and one of the following shall hold:
2242 // -- The second or the third operand (but not both) is a throw-
2243 // expression; the result is of the type of the other and is an rvalue.
2244 bool LThrow = isa<CXXThrowExpr>(LHS);
2245 bool RThrow = isa<CXXThrowExpr>(RHS);
2246 if (LThrow && !RThrow)
2247 return RTy;
2248 if (RThrow && !LThrow)
2249 return LTy;
2250
2251 // -- Both the second and third operands have type void; the result is of
2252 // type void and is an rvalue.
2253 if (LVoid && RVoid)
2254 return Context.VoidTy;
2255
2256 // Neither holds, error.
2257 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2258 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2259 << LHS->getSourceRange() << RHS->getSourceRange();
2260 return QualType();
2261 }
2262
2263 // Neither is void.
2264
2265 // C++0x 5.16p3
2266 // Otherwise, if the second and third operand have different types, and
2267 // either has (cv) class type, and attempt is made to convert each of those
2268 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002269 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002270 (LTy->isRecordType() || RTy->isRecordType())) {
2271 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2272 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002273 QualType L2RType, R2LType;
2274 bool HaveL2R, HaveR2L;
2275 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002276 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002277 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002278 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002279
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002280 // If both can be converted, [...] the program is ill-formed.
2281 if (HaveL2R && HaveR2L) {
2282 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2283 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2284 return QualType();
2285 }
2286
2287 // If exactly one conversion is possible, that conversion is applied to
2288 // the chosen operand and the converted operands are used in place of the
2289 // original operands for the remainder of this section.
2290 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002291 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002292 return QualType();
2293 LTy = LHS->getType();
2294 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002295 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002296 return QualType();
2297 RTy = RHS->getType();
2298 }
2299 }
2300
2301 // C++0x 5.16p4
2302 // If the second and third operands are lvalues and have the same type,
2303 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002304 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002305 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2306 RHS->isLvalue(Context) == Expr::LV_Valid)
2307 return LTy;
2308
2309 // C++0x 5.16p5
2310 // Otherwise, the result is an rvalue. If the second and third operands
2311 // do not have the same type, and either has (cv) class type, ...
2312 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2313 // ... overload resolution is used to determine the conversions (if any)
2314 // to be applied to the operands. If the overload resolution fails, the
2315 // program is ill-formed.
2316 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2317 return QualType();
2318 }
2319
2320 // C++0x 5.16p6
2321 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2322 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002323 DefaultFunctionArrayLvalueConversion(LHS);
2324 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002325 LTy = LHS->getType();
2326 RTy = RHS->getType();
2327
2328 // After those conversions, one of the following shall hold:
2329 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002330 // is of that type. If the operands have class type, the result
2331 // is a prvalue temporary of the result type, which is
2332 // copy-initialized from either the second operand or the third
2333 // operand depending on the value of the first operand.
2334 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2335 if (LTy->isRecordType()) {
2336 // The operands have class type. Make a temporary copy.
2337 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCall60d7b3a2010-08-24 06:29:42 +00002338 ExprResult LHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorb65a4582010-05-19 23:40:50 +00002339 SourceLocation(),
2340 Owned(LHS));
2341 if (LHSCopy.isInvalid())
2342 return QualType();
2343
John McCall60d7b3a2010-08-24 06:29:42 +00002344 ExprResult RHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorb65a4582010-05-19 23:40:50 +00002345 SourceLocation(),
2346 Owned(RHS));
2347 if (RHSCopy.isInvalid())
2348 return QualType();
2349
2350 LHS = LHSCopy.takeAs<Expr>();
2351 RHS = RHSCopy.takeAs<Expr>();
2352 }
2353
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002354 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002355 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002356
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002357 // Extension: conditional operator involving vector types.
2358 if (LTy->isVectorType() || RTy->isVectorType())
2359 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2360
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002361 // -- The second and third operands have arithmetic or enumeration type;
2362 // the usual arithmetic conversions are performed to bring them to a
2363 // common type, and the result is of that type.
2364 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2365 UsualArithmeticConversions(LHS, RHS);
2366 return LHS->getType();
2367 }
2368
2369 // -- The second and third operands have pointer type, or one has pointer
2370 // type and the other is a null pointer constant; pointer conversions
2371 // and qualification conversions are performed to bring them to their
2372 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002373 // -- The second and third operands have pointer to member type, or one has
2374 // pointer to member type and the other is a null pointer constant;
2375 // pointer to member conversions and qualification conversions are
2376 // performed to bring them to a common type, whose cv-qualification
2377 // shall match the cv-qualification of either the second or the third
2378 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002379 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002380 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002381 isSFINAEContext()? 0 : &NonStandardCompositeType);
2382 if (!Composite.isNull()) {
2383 if (NonStandardCompositeType)
2384 Diag(QuestionLoc,
2385 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2386 << LTy << RTy << Composite
2387 << LHS->getSourceRange() << RHS->getSourceRange();
2388
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002389 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002390 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002391
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002392 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002393 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2394 if (!Composite.isNull())
2395 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002396
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002397 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2398 << LHS->getType() << RHS->getType()
2399 << LHS->getSourceRange() << RHS->getSourceRange();
2400 return QualType();
2401}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002402
2403/// \brief Find a merged pointer type and convert the two expressions to it.
2404///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002405/// This finds the composite pointer type (or member pointer type) for @p E1
2406/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2407/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002408/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002409///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002410/// \param Loc The location of the operator requiring these two expressions to
2411/// be converted to the composite pointer type.
2412///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002413/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2414/// a non-standard (but still sane) composite type to which both expressions
2415/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2416/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002417QualType Sema::FindCompositePointerType(SourceLocation Loc,
2418 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002419 bool *NonStandardCompositeType) {
2420 if (NonStandardCompositeType)
2421 *NonStandardCompositeType = false;
2422
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002423 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2424 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002425
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002426 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2427 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002428 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002429
2430 // C++0x 5.9p2
2431 // Pointer conversions and qualification conversions are performed on
2432 // pointer operands to bring them to their composite pointer type. If
2433 // one operand is a null pointer constant, the composite pointer type is
2434 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002435 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002436 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002437 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002438 else
John McCall2de56d12010-08-25 11:45:40 +00002439 ImpCastExprToType(E1, T2, CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002440 return T2;
2441 }
Douglas Gregorce940492009-09-25 04:25:58 +00002442 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002443 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002444 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002445 else
John McCall2de56d12010-08-25 11:45:40 +00002446 ImpCastExprToType(E2, T1, CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002447 return T1;
2448 }
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor20b3e992009-08-24 17:42:35 +00002450 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002451 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2452 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002453 return QualType();
2454
2455 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2456 // the other has type "pointer to cv2 T" and the composite pointer type is
2457 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2458 // Otherwise, the composite pointer type is a pointer type similar to the
2459 // type of one of the operands, with a cv-qualification signature that is
2460 // the union of the cv-qualification signatures of the operand types.
2461 // In practice, the first part here is redundant; it's subsumed by the second.
2462 // What we do here is, we build the two possible composite types, and try the
2463 // conversions in both directions. If only one works, or if the two composite
2464 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002465 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002466 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2467 QualifierVector QualifierUnion;
2468 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2469 ContainingClassVector;
2470 ContainingClassVector MemberOfClass;
2471 QualType Composite1 = Context.getCanonicalType(T1),
2472 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002473 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002474 do {
2475 const PointerType *Ptr1, *Ptr2;
2476 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2477 (Ptr2 = Composite2->getAs<PointerType>())) {
2478 Composite1 = Ptr1->getPointeeType();
2479 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002480
2481 // If we're allowed to create a non-standard composite type, keep track
2482 // of where we need to fill in additional 'const' qualifiers.
2483 if (NonStandardCompositeType &&
2484 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2485 NeedConstBefore = QualifierUnion.size();
2486
Douglas Gregor20b3e992009-08-24 17:42:35 +00002487 QualifierUnion.push_back(
2488 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2489 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2490 continue;
2491 }
Mike Stump1eb44332009-09-09 15:08:12 +00002492
Douglas Gregor20b3e992009-08-24 17:42:35 +00002493 const MemberPointerType *MemPtr1, *MemPtr2;
2494 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2495 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2496 Composite1 = MemPtr1->getPointeeType();
2497 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002498
2499 // If we're allowed to create a non-standard composite type, keep track
2500 // of where we need to fill in additional 'const' qualifiers.
2501 if (NonStandardCompositeType &&
2502 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2503 NeedConstBefore = QualifierUnion.size();
2504
Douglas Gregor20b3e992009-08-24 17:42:35 +00002505 QualifierUnion.push_back(
2506 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2507 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2508 MemPtr2->getClass()));
2509 continue;
2510 }
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Douglas Gregor20b3e992009-08-24 17:42:35 +00002512 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Douglas Gregor20b3e992009-08-24 17:42:35 +00002514 // Cannot unwrap any more types.
2515 break;
2516 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002517
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002518 if (NeedConstBefore && NonStandardCompositeType) {
2519 // Extension: Add 'const' to qualifiers that come before the first qualifier
2520 // mismatch, so that our (non-standard!) composite type meets the
2521 // requirements of C++ [conv.qual]p4 bullet 3.
2522 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2523 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2524 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2525 *NonStandardCompositeType = true;
2526 }
2527 }
2528 }
2529
Douglas Gregor20b3e992009-08-24 17:42:35 +00002530 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002531 ContainingClassVector::reverse_iterator MOC
2532 = MemberOfClass.rbegin();
2533 for (QualifierVector::reverse_iterator
2534 I = QualifierUnion.rbegin(),
2535 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002536 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002537 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002538 if (MOC->first && MOC->second) {
2539 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002540 Composite1 = Context.getMemberPointerType(
2541 Context.getQualifiedType(Composite1, Quals),
2542 MOC->first);
2543 Composite2 = Context.getMemberPointerType(
2544 Context.getQualifiedType(Composite2, Quals),
2545 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002546 } else {
2547 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002548 Composite1
2549 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2550 Composite2
2551 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002552 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002553 }
2554
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002555 // Try to convert to the first composite pointer type.
2556 InitializedEntity Entity1
2557 = InitializedEntity::InitializeTemporary(Composite1);
2558 InitializationKind Kind
2559 = InitializationKind::CreateCopy(Loc, SourceLocation());
2560 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2561 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002563 if (E1ToC1 && E2ToC1) {
2564 // Conversion to Composite1 is viable.
2565 if (!Context.hasSameType(Composite1, Composite2)) {
2566 // Composite2 is a different type from Composite1. Check whether
2567 // Composite2 is also viable.
2568 InitializedEntity Entity2
2569 = InitializedEntity::InitializeTemporary(Composite2);
2570 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2571 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2572 if (E1ToC2 && E2ToC2) {
2573 // Both Composite1 and Composite2 are viable and are different;
2574 // this is an ambiguity.
2575 return QualType();
2576 }
2577 }
2578
2579 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002580 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002581 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002582 if (E1Result.isInvalid())
2583 return QualType();
2584 E1 = E1Result.takeAs<Expr>();
2585
2586 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002587 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002588 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002589 if (E2Result.isInvalid())
2590 return QualType();
2591 E2 = E2Result.takeAs<Expr>();
2592
2593 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002594 }
2595
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002596 // Check whether Composite2 is viable.
2597 InitializedEntity Entity2
2598 = InitializedEntity::InitializeTemporary(Composite2);
2599 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2600 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2601 if (!E1ToC2 || !E2ToC2)
2602 return QualType();
2603
2604 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00002605 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002606 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002607 if (E1Result.isInvalid())
2608 return QualType();
2609 E1 = E1Result.takeAs<Expr>();
2610
2611 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00002612 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002613 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002614 if (E2Result.isInvalid())
2615 return QualType();
2616 E2 = E2Result.takeAs<Expr>();
2617
2618 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002619}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002620
John McCall60d7b3a2010-08-24 06:29:42 +00002621ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002622 if (!Context.getLangOptions().CPlusPlus)
2623 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Douglas Gregor51326552009-12-24 18:51:59 +00002625 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2626
Ted Kremenek6217b802009-07-29 21:53:49 +00002627 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002628 if (!RT)
2629 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002630
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002631 // If this is the result of a call or an Objective-C message send expression,
2632 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002633 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002634 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00002635 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002636 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2637 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2638 if (MD->getResultType()->isReferenceType())
2639 return Owned(E);
2640 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00002641 }
John McCall86ff3082010-02-04 22:26:26 +00002642
2643 // That should be enough to guarantee that this type is complete.
2644 // If it has a trivial destructor, we can avoid the extra copy.
2645 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00002646 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00002647 return Owned(E);
2648
Douglas Gregordb89f282010-07-01 22:47:18 +00002649 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00002650 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00002651 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002652 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002653 CheckDestructorAccess(E->getExprLoc(), Destructor,
2654 PDiag(diag::err_access_dtor_temp)
2655 << E->getType());
2656 }
Anders Carlssondef11992009-05-30 20:36:53 +00002657 // FIXME: Add the temporary to the temporaries vector.
2658 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2659}
2660
Anders Carlsson0ece4912009-12-15 20:51:39 +00002661Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002662 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002663
John McCall323ed742010-05-06 08:58:33 +00002664 // Check any implicit conversions within the expression.
2665 CheckImplicitConversions(SubExpr);
2666
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002667 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2668 assert(ExprTemporaries.size() >= FirstTemporary);
2669 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002670 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002672 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002673 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002674 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002675 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2676 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002677
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002678 return E;
2679}
2680
John McCall60d7b3a2010-08-24 06:29:42 +00002681ExprResult
2682Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00002683 if (SubExpr.isInvalid())
2684 return ExprError();
2685
2686 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2687}
2688
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002689FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2690 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2691 assert(ExprTemporaries.size() >= FirstTemporary);
2692
2693 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2694 CXXTemporary **Temporaries =
2695 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2696
2697 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2698
2699 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2700 ExprTemporaries.end());
2701
2702 return E;
2703}
2704
John McCall60d7b3a2010-08-24 06:29:42 +00002705ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002706Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00002707 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00002708 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002709 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002710 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002711 if (Result.isInvalid()) return ExprError();
2712 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002713
John McCall9ae2f072010-08-23 23:25:46 +00002714 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002715 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002716 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002717 // If we have a pointer to a dependent type and are using the -> operator,
2718 // the object type is the type that the pointer points to. We might still
2719 // have enough information about that type to do something useful.
2720 if (OpKind == tok::arrow)
2721 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2722 BaseType = Ptr->getPointeeType();
2723
John McCallb3d87482010-08-24 05:47:05 +00002724 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00002725 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00002726 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002727 }
Mike Stump1eb44332009-09-09 15:08:12 +00002728
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002729 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002730 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002731 // returned, with the original second operand.
2732 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002733 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002734 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002735 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002736 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002737
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002738 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00002739 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
2740 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002741 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00002742 Base = Result.get();
2743 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00002744 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00002745 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00002746 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002747 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002748 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002749 for (unsigned i = 0; i < Locations.size(); i++)
2750 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002751 return ExprError();
2752 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Douglas Gregor31658df2009-11-20 19:58:21 +00002755 if (BaseType->isPointerType())
2756 BaseType = BaseType->getPointeeType();
2757 }
Mike Stump1eb44332009-09-09 15:08:12 +00002758
2759 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002760 // vector types or Objective-C interfaces. Just return early and let
2761 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002762 if (!BaseType->isRecordType()) {
2763 // C++ [basic.lookup.classref]p2:
2764 // [...] If the type of the object expression is of pointer to scalar
2765 // type, the unqualified-id is looked up in the context of the complete
2766 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002767 //
2768 // This also indicates that we should be parsing a
2769 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00002770 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002771 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00002772 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002773 }
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Douglas Gregor03c57052009-11-17 05:17:33 +00002775 // The object type must be complete (or dependent).
2776 if (!BaseType->isDependentType() &&
2777 RequireCompleteType(OpLoc, BaseType,
2778 PDiag(diag::err_incomplete_member_access)))
2779 return ExprError();
2780
Douglas Gregorc68afe22009-09-03 21:38:09 +00002781 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002782 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002783 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002784 // type C (or of pointer to a class type C), the unqualified-id is looked
2785 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00002786 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00002787 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002788}
2789
John McCall60d7b3a2010-08-24 06:29:42 +00002790ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002791 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00002792 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00002793 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
2794 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00002795 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002796
2797 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00002798 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00002799 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00002800 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00002801 /*CommaLocs*/ 0,
2802 /*RPLoc*/ ExpectedLParenLoc);
2803}
Douglas Gregord4dca082010-02-24 18:44:31 +00002804
John McCall60d7b3a2010-08-24 06:29:42 +00002805ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002806 SourceLocation OpLoc,
2807 tok::TokenKind OpKind,
2808 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002809 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002810 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002811 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002812 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002813 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002814 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002815
2816 // C++ [expr.pseudo]p2:
2817 // The left-hand side of the dot operator shall be of scalar type. The
2818 // left-hand side of the arrow operator shall be of pointer to scalar type.
2819 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00002820 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002821 if (OpKind == tok::arrow) {
2822 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2823 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00002824 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002825 // The user wrote "p->" when she probably meant "p."; fix it.
2826 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2827 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002828 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002829 if (isSFINAEContext())
2830 return ExprError();
2831
2832 OpKind = tok::period;
2833 }
2834 }
2835
2836 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2837 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00002838 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002839 return ExprError();
2840 }
2841
2842 // C++ [expr.pseudo]p2:
2843 // [...] The cv-unqualified versions of the object type and of the type
2844 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002845 if (DestructedTypeInfo) {
2846 QualType DestructedType = DestructedTypeInfo->getType();
2847 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002848 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002849 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2850 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2851 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00002852 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002853 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002854
2855 // Recover by setting the destructed type to the object type.
2856 DestructedType = ObjectType;
2857 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2858 DestructedTypeStart);
2859 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2860 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002861 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002862
Douglas Gregorb57fb492010-02-24 22:38:50 +00002863 // C++ [expr.pseudo]p2:
2864 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2865 // form
2866 //
2867 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2868 //
2869 // shall designate the same scalar type.
2870 if (ScopeTypeInfo) {
2871 QualType ScopeType = ScopeTypeInfo->getType();
2872 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00002873 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002874
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002875 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00002876 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00002877 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002878 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002879
2880 ScopeType = QualType();
2881 ScopeTypeInfo = 0;
2882 }
2883 }
2884
John McCall9ae2f072010-08-23 23:25:46 +00002885 Expr *Result
2886 = new (Context) CXXPseudoDestructorExpr(Context, Base,
2887 OpKind == tok::arrow, OpLoc,
2888 SS.getScopeRep(), SS.getRange(),
2889 ScopeTypeInfo,
2890 CCLoc,
2891 TildeLoc,
2892 Destructed);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002893
Douglas Gregorb57fb492010-02-24 22:38:50 +00002894 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00002895 return Owned(Result);
Douglas Gregorb57fb492010-02-24 22:38:50 +00002896
John McCall9ae2f072010-08-23 23:25:46 +00002897 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00002898}
2899
John McCall60d7b3a2010-08-24 06:29:42 +00002900ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00002901 SourceLocation OpLoc,
2902 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002903 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002904 UnqualifiedId &FirstTypeName,
2905 SourceLocation CCLoc,
2906 SourceLocation TildeLoc,
2907 UnqualifiedId &SecondTypeName,
2908 bool HasTrailingLParen) {
2909 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2910 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2911 "Invalid first type name in pseudo-destructor");
2912 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2913 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2914 "Invalid second type name in pseudo-destructor");
2915
Douglas Gregor77549082010-02-24 21:29:12 +00002916 // C++ [expr.pseudo]p2:
2917 // The left-hand side of the dot operator shall be of scalar type. The
2918 // left-hand side of the arrow operator shall be of pointer to scalar type.
2919 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00002920 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00002921 if (OpKind == tok::arrow) {
2922 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2923 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002924 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002925 // The user wrote "p->" when she probably meant "p."; fix it.
2926 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002927 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002928 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002929 if (isSFINAEContext())
2930 return ExprError();
2931
2932 OpKind = tok::period;
2933 }
2934 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002935
2936 // Compute the object type that we should use for name lookup purposes. Only
2937 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00002938 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002939 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00002940 if (const Type *T = ObjectType->getAs<RecordType>())
2941 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
2942 else if (ObjectType->isDependentType())
2943 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002944 }
Douglas Gregor77549082010-02-24 21:29:12 +00002945
Douglas Gregorb57fb492010-02-24 22:38:50 +00002946 // Convert the name of the type being destructed (following the ~) into a
2947 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002948 QualType DestructedType;
2949 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002950 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002951 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00002952 ParsedType T = getTypeName(*SecondTypeName.Identifier,
2953 SecondTypeName.StartLocation,
2954 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002955 if (!T &&
2956 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2957 (!SS.isSet() && ObjectType->isDependentType()))) {
2958 // The name of the type being destroyed is a dependent name, and we
2959 // couldn't find anything useful in scope. Just store the identifier and
2960 // it's location, and we'll perform (qualified) name lookup again at
2961 // template instantiation time.
2962 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2963 SecondTypeName.StartLocation);
2964 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002965 Diag(SecondTypeName.StartLocation,
2966 diag::err_pseudo_dtor_destructor_non_type)
2967 << SecondTypeName.Identifier << ObjectType;
2968 if (isSFINAEContext())
2969 return ExprError();
2970
2971 // Recover by assuming we had the right type all along.
2972 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002973 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002974 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002975 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002976 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002977 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002978 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2979 TemplateId->getTemplateArgs(),
2980 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00002981 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002982 TemplateId->TemplateNameLoc,
2983 TemplateId->LAngleLoc,
2984 TemplateArgsPtr,
2985 TemplateId->RAngleLoc);
2986 if (T.isInvalid() || !T.get()) {
2987 // Recover by assuming we had the right type all along.
2988 DestructedType = ObjectType;
2989 } else
2990 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002991 }
2992
Douglas Gregorb57fb492010-02-24 22:38:50 +00002993 // If we've performed some kind of recovery, (re-)build the type source
2994 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002995 if (!DestructedType.isNull()) {
2996 if (!DestructedTypeInfo)
2997 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002998 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002999 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3000 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003001
3002 // Convert the name of the scope type (the type prior to '::') into a type.
3003 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003004 QualType ScopeType;
3005 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3006 FirstTypeName.Identifier) {
3007 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003008 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3009 FirstTypeName.StartLocation,
3010 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003011 if (!T) {
3012 Diag(FirstTypeName.StartLocation,
3013 diag::err_pseudo_dtor_destructor_non_type)
3014 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00003015
Douglas Gregorb57fb492010-02-24 22:38:50 +00003016 if (isSFINAEContext())
3017 return ExprError();
3018
3019 // Just drop this type. It's unnecessary anyway.
3020 ScopeType = QualType();
3021 } else
3022 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003023 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003024 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003025 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003026 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3027 TemplateId->getTemplateArgs(),
3028 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003029 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003030 TemplateId->TemplateNameLoc,
3031 TemplateId->LAngleLoc,
3032 TemplateArgsPtr,
3033 TemplateId->RAngleLoc);
3034 if (T.isInvalid() || !T.get()) {
3035 // Recover by dropping this type.
3036 ScopeType = QualType();
3037 } else
3038 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003039 }
3040 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003041
3042 if (!ScopeType.isNull() && !ScopeTypeInfo)
3043 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3044 FirstTypeName.StartLocation);
3045
3046
John McCall9ae2f072010-08-23 23:25:46 +00003047 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003048 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003049 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003050}
3051
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003052CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003053 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003054 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003055 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3056 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003057 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3058
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003059 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003060 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003061 SourceLocation(), Method->getType());
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003062 QualType ResultType = Method->getCallResultType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003063 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3064 CXXMemberCallExpr *CE =
3065 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3066 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003067 return CE;
3068}
3069
John McCall60d7b3a2010-08-24 06:29:42 +00003070ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
John McCall9ae2f072010-08-23 23:25:46 +00003071 if (!FullExpr) return ExprError();
3072 return MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003073}