blob: 7c324235ca838d0d30c0d29c13b268bfbbcdd715 [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
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor124b8782010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000032 Scope *S, CXXScopeSpec &SS,
Douglas Gregor124b8782010-02-16 19:09:40 +000033 TypeTy *ObjectTypePtr,
34 bool EnteringContext) {
35 // Determine where to perform name lookup.
36
37 // FIXME: This area of the standard is very messy, and the current
38 // wording is rather unclear about which scopes we search for the
39 // destructor name; see core issues 399 and 555. Issue 399 in
40 // particular shows where the current description of destructor name
41 // lookup is completely out of line with existing practice, e.g.,
42 // this appears to be ill-formed:
43 //
44 // namespace N {
45 // template <typename T> struct S {
46 // ~S();
47 // };
48 // }
49 //
50 // void f(N::S<int>* s) {
51 // s->N::S<int>::~S();
52 // }
53 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000055 QualType SearchType;
56 DeclContext *LookupCtx = 0;
57 bool isDependent = false;
58 bool LookInScope = false;
59
60 // If we have an object type, it's because we are in a
61 // pseudo-destructor-expression or a member access expression, and
62 // we know what type we're looking for.
63 if (ObjectTypePtr)
64 SearchType = GetTypeFromParser(ObjectTypePtr);
65
66 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000067 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69 bool AlreadySearched = false;
70 bool LookAtPrefix = true;
71 if (!getLangOptions().CPlusPlus0x) {
72 // C++ [basic.lookup.qual]p6:
73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74 // the type-names are looked up as types in the scope designated by the
75 // nested-name-specifier. In a qualified-id of the form:
76 //
77 // ::[opt] nested-name-specifier ̃ class-name
78 //
79 // where the nested-name-specifier designates a namespace scope, and in
80 // a qualified-id of the form:
81 //
82 // ::opt nested-name-specifier class-name :: ̃ class-name
83 //
84 // the class-names are looked up as types in the scope designated by
85 // the nested-name-specifier.
86 //
87 // Here, we check the first case (completely) and determine whether the
88 // code below is permitted to look at the prefix of the
89 // nested-name-specifier (as we do in C++0x).
90 DeclContext *DC = computeDeclContext(SS, EnteringContext);
91 if (DC && DC->isFileContext()) {
92 AlreadySearched = true;
93 LookupCtx = DC;
94 isDependent = false;
95 } else if (DC && isa<CXXRecordDecl>(DC))
96 LookAtPrefix = false;
97 }
98
99 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +0000100 // If a pseudo-destructor-name (5.2.4) contains a
101 // nested-name-specifier, the type-names are looked up as types
102 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000104 //
105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106 //
107 // the second class-name is looked up in the same scope as the first.
108 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 // To implement this, we look at the prefix of the
110 // nested-name-specifier we were given, and determine the lookup
111 // context from that.
112 //
113 // We also fold in the second case from the C++03 rules quoted further
114 // above.
115 NestedNameSpecifier *Prefix = 0;
116 if (AlreadySearched) {
117 // Nothing left to do.
118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119 CXXScopeSpec PrefixSS;
120 PrefixSS.setScopeRep(Prefix);
121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(PrefixSS);
123 } else if (getLangOptions().CPlusPlus0x &&
124 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125 if (!LookupCtx->isTranslationUnit())
126 LookupCtx = LookupCtx->getParent();
127 isDependent = LookupCtx && LookupCtx->isDependentContext();
128 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000134 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000135
Douglas Gregoredc90502010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 } else if (ObjectTypePtr) {
138 // C++ [basic.lookup.classref]p3:
139 // If the unqualified-id is ~type-name, the type-name is looked up
140 // in the context of the entire postfix-expression. If the type T
141 // of the object expression is of a class type C, the type-name is
142 // also looked up in the scope of class C. At least one of the
143 // lookups shall find a name that refers to (possibly
144 // cv-qualified) T.
145 LookupCtx = computeDeclContext(SearchType);
146 isDependent = SearchType->isDependentType();
147 assert((isDependent || !SearchType->isIncompleteType()) &&
148 "Caller should have completed object type");
149
150 LookInScope = true;
151 } else {
152 // Perform lookup into the current scope (only).
153 LookInScope = true;
154 }
155
156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157 for (unsigned Step = 0; Step != 2; ++Step) {
158 // Look for the name first in the computed lookup context (if we
159 // have one) and, if that fails to find a match, in the sope (if
160 // we're allowed to look there).
161 Found.clear();
162 if (Step == 0 && LookupCtx)
163 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 LookupName(Found, S);
166 else
167 continue;
168
169 // FIXME: Should we be suppressing ambiguities here?
170 if (Found.isAmbiguous())
171 return 0;
172
173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000175
176 if (SearchType.isNull() || SearchType->isDependentType() ||
177 Context.hasSameUnqualifiedType(T, SearchType)) {
178 // We found our type!
179
180 return T.getAsOpaquePtr();
181 }
182 }
183
184 // If the name that we found is a class template name, and it is
185 // the same name as the template name in the last part of the
186 // nested-name-specifier (if present) or the object type, then
187 // this is the destructor for that class.
188 // FIXME: This is a workaround until we get real drafting for core
189 // issue 399, for which there isn't even an obvious direction.
190 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191 QualType MemberOfType;
192 if (SS.isSet()) {
193 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000197 }
198 }
199 if (MemberOfType.isNull())
200 MemberOfType = SearchType;
201
202 if (MemberOfType.isNull())
203 continue;
204
205 // We're referring into a class template specialization. If the
206 // class template we found is the same as the template being
207 // specialized, we found what we are looking for.
208 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209 if (ClassTemplateSpecializationDecl *Spec
210 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212 Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214 }
215
216 continue;
217 }
218
219 // We're referring to an unresolved class template
220 // specialization. Determine whether we class template we found
221 // is the same as the template being specialized or, if we don't
222 // know which template is being specialized, that it at least
223 // has the same name.
224 if (const TemplateSpecializationType *SpecType
225 = MemberOfType->getAs<TemplateSpecializationType>()) {
226 TemplateName SpecName = SpecType->getTemplateName();
227
228 // The class template we found is the same template being
229 // specialized.
230 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232 return MemberOfType.getAsOpaquePtr();
233
234 continue;
235 }
236
237 // The class template we found has the same name as the
238 // (dependent) template name being specialized.
239 if (DependentTemplateName *DepTemplate
240 = SpecName.getAsDependentTemplateName()) {
241 if (DepTemplate->isIdentifier() &&
242 DepTemplate->getIdentifier() == Template->getIdentifier())
243 return MemberOfType.getAsOpaquePtr();
244
245 continue;
246 }
247 }
248 }
249 }
250
251 if (isDependent) {
252 // We didn't find our type, but that's okay: it's dependent
253 // anyway.
254 NestedNameSpecifier *NNS = 0;
255 SourceRange Range;
256 if (SS.isSet()) {
257 NNS = (NestedNameSpecifier *)SS.getScopeRep();
258 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259 } else {
260 NNS = NestedNameSpecifier::Create(Context, &II);
261 Range = SourceRange(NameLoc);
262 }
263
Douglas Gregor107de902010-04-24 15:35:55 +0000264 return CheckTypenameType(ETK_None, NNS, II, Range).getAsOpaquePtr();
Douglas Gregor124b8782010-02-16 19:09:40 +0000265 }
266
267 if (ObjectTypePtr)
268 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269 << &II;
270 else
271 Diag(NameLoc, diag::err_destructor_class_name);
272
273 return 0;
274}
275
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000276/// \brief Build a C++ typeid expression with a type operand.
277Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
278 SourceLocation TypeidLoc,
279 TypeSourceInfo *Operand,
280 SourceLocation RParenLoc) {
281 // C++ [expr.typeid]p4:
282 // The top-level cv-qualifiers of the lvalue expression or the type-id
283 // that is the operand of typeid are always ignored.
284 // If the type of the type-id is a class type or a reference to a class
285 // type, the class shall be completely-defined.
286 QualType T = Operand->getType().getNonReferenceType();
287 if (T->getAs<RecordType>() &&
288 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
289 return ExprError();
290
291 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
292 Operand,
293 SourceRange(TypeidLoc, RParenLoc)));
294}
295
296/// \brief Build a C++ typeid expression with an expression operand.
297Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
298 SourceLocation TypeidLoc,
299 ExprArg Operand,
300 SourceLocation RParenLoc) {
301 bool isUnevaluatedOperand = true;
302 Expr *E = static_cast<Expr *>(Operand.get());
303 if (E && !E->isTypeDependent()) {
304 QualType T = E->getType();
305 if (const RecordType *RecordT = T->getAs<RecordType>()) {
306 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
307 // C++ [expr.typeid]p3:
308 // [...] If the type of the expression is a class type, the class
309 // shall be completely-defined.
310 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
311 return ExprError();
312
313 // C++ [expr.typeid]p3:
314 // When typeid is applied to an expression other than an lvalue of a
315 // polymorphic class type [...] [the] expression is an unevaluated
316 // operand. [...]
317 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
318 isUnevaluatedOperand = false;
319 }
320
321 // C++ [expr.typeid]p4:
322 // [...] If the type of the type-id is a reference to a possibly
323 // cv-qualified type, the result of the typeid expression refers to a
324 // std::type_info object representing the cv-unqualified referenced
325 // type.
326 if (T.hasQualifiers()) {
327 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
328 E->isLvalue(Context));
329 Operand.release();
330 Operand = Owned(E);
331 }
332 }
333
334 // If this is an unevaluated operand, clear out the set of
335 // declaration references we have been computing and eliminate any
336 // temporaries introduced in its computation.
337 if (isUnevaluatedOperand)
338 ExprEvalContexts.back().Context = Unevaluated;
339
340 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
341 Operand.takeAs<Expr>(),
342 SourceRange(TypeidLoc, RParenLoc)));
343}
344
345/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000346Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000347Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
348 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000349 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000350 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000351 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000352
Chris Lattner572af492008-11-20 05:51:55 +0000353 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000354 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
355 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000356 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000357 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000358 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000359
Sebastian Redlc42e1182008-11-11 11:37:55 +0000360 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000361
362 if (isType) {
363 // The operand is a type; handle it as such.
364 TypeSourceInfo *TInfo = 0;
365 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
366 if (T.isNull())
367 return ExprError();
368
369 if (!TInfo)
370 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000371
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000375 // The operand is an expression.
376 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000377}
378
Steve Naroff1b273c42007-09-16 14:56:35 +0000379/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000380Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000381Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000382 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000384 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
385 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000386}
Chris Lattner50dd2892008-02-26 00:51:44 +0000387
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000388/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
389Action::OwningExprResult
390Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
391 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
392}
393
Chris Lattner50dd2892008-02-26 00:51:44 +0000394/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395Action::OwningExprResult
396Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000397 Expr *Ex = E.takeAs<Expr>();
398 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
399 return ExprError();
400 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
401}
402
403/// CheckCXXThrowOperand - Validate the operand of a throw.
404bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
405 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000406 // A throw-expression initializes a temporary object, called the exception
407 // object, the type of which is determined by removing any top-level
408 // cv-qualifiers from the static type of the operand of throw and adjusting
409 // the type from "array of T" or "function returning T" to "pointer to T"
410 // or "pointer to function returning T", [...]
411 if (E->getType().hasQualifiers())
412 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
413 E->isLvalue(Context) == Expr::LV_Valid);
414
Sebastian Redl972041f2009-04-27 20:27:31 +0000415 DefaultFunctionArrayConversion(E);
416
417 // If the type of the exception would be an incomplete type or a pointer
418 // to an incomplete type other than (cv) void the program is ill-formed.
419 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000420 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000421 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000422 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000423 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000424 }
425 if (!isPointer || !Ty->isVoidType()) {
426 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000427 PDiag(isPointer ? diag::err_throw_incomplete_ptr
428 : diag::err_throw_incomplete)
429 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000430 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000431
Douglas Gregorbf422f92010-04-15 18:05:39 +0000432 if (RequireNonAbstractType(ThrowLoc, E->getType(),
433 PDiag(diag::err_throw_abstract_type)
434 << E->getSourceRange()))
435 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000436 }
437
John McCallac418162010-04-22 01:10:34 +0000438 // Initialize the exception result. This implicitly weeds out
439 // abstract types or types with inaccessible copy constructors.
440 InitializedEntity Entity =
441 InitializedEntity::InitializeException(ThrowLoc, E->getType());
442 OwningExprResult Res = PerformCopyInitialization(Entity,
443 SourceLocation(),
444 Owned(E));
445 if (Res.isInvalid())
446 return true;
447 E = Res.takeAs<Expr>();
Sebastian Redl972041f2009-04-27 20:27:31 +0000448 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000449}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000450
Sebastian Redlf53597f2009-03-15 17:47:39 +0000451Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000452 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
453 /// is a non-lvalue expression whose value is the address of the object for
454 /// which the function is called.
455
Sebastian Redlf53597f2009-03-15 17:47:39 +0000456 if (!isa<FunctionDecl>(CurContext))
457 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000458
459 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
460 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000461 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000462 MD->getThisType(Context),
463 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000464
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000466}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000467
468/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
469/// Can be interpreted either as function-style casting ("int(x)")
470/// or class type construction ("ClassType(x,y,z)")
471/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000473Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
474 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000476 SourceLocation *CommaLocs,
477 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000478 if (!TypeRep)
479 return ExprError();
480
John McCall9d125032010-01-15 18:39:57 +0000481 TypeSourceInfo *TInfo;
482 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
483 if (!TInfo)
484 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000485 unsigned NumExprs = exprs.size();
486 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000487 SourceLocation TyBeginLoc = TypeRange.getBegin();
488 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
489
Sebastian Redlf53597f2009-03-15 17:47:39 +0000490 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000491 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000492 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000493
494 return Owned(CXXUnresolvedConstructExpr::Create(Context,
495 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000496 LParenLoc,
497 Exprs, NumExprs,
498 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000499 }
500
Anders Carlssonbb60a502009-08-27 03:53:50 +0000501 if (Ty->isArrayType())
502 return ExprError(Diag(TyBeginLoc,
503 diag::err_value_init_for_array_type) << FullRange);
504 if (!Ty->isVoidType() &&
505 RequireCompleteType(TyBeginLoc, Ty,
506 PDiag(diag::err_invalid_incomplete_type_use)
507 << FullRange))
508 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000509
Anders Carlssonbb60a502009-08-27 03:53:50 +0000510 if (RequireNonAbstractType(TyBeginLoc, Ty,
511 diag::err_allocation_of_abstract_type))
512 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000513
514
Douglas Gregor506ae412009-01-16 18:33:17 +0000515 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000516 // If the expression list is a single expression, the type conversion
517 // expression is equivalent (in definedness, and if defined in meaning) to the
518 // corresponding cast expression.
519 //
520 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000521 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000522 CXXBaseSpecifierArray BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000523 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
524 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000525 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000526
527 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000528
529 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000530 TInfo, TyBeginLoc, Kind,
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000531 Exprs[0], BasePath,
532 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000533 }
534
Ted Kremenek6217b802009-07-29 21:53:49 +0000535 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000536 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000537
Mike Stump1eb44332009-09-09 15:08:12 +0000538 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000539 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000540 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
541 InitializationKind Kind
542 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
543 LParenLoc, RParenLoc)
544 : InitializationKind::CreateValue(TypeRange.getBegin(),
545 LParenLoc, RParenLoc);
546 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
547 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
548 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000549
Eli Friedman6997aae2010-01-31 20:58:15 +0000550 // FIXME: Improve AST representation?
551 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000552 }
553
554 // Fall through to value-initialize an object of class type that
555 // doesn't have a user-declared default constructor.
556 }
557
558 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000559 // If the expression list specifies more than a single value, the type shall
560 // be a class with a suitably declared constructor.
561 //
562 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000563 return ExprError(Diag(CommaLocs[0],
564 diag::err_builtin_func_cast_more_than_one_arg)
565 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000566
567 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000568 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000569 // The expression T(), where T is a simple-type-specifier for a non-array
570 // complete object type or the (possibly cv-qualified) void type, creates an
571 // rvalue of the specified type, which is value-initialized.
572 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573 exprs.release();
574 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000575}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000576
577
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000578/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
579/// @code new (memory) int[size][4] @endcode
580/// or
581/// @code ::new Foo(23, "hello") @endcode
582/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000583Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000584Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000585 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000586 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000587 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000588 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000589 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000590 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000591 // If the specified type is an array, unwrap it and save the expression.
592 if (D.getNumTypeObjects() > 0 &&
593 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
594 DeclaratorChunk &Chunk = D.getTypeObject(0);
595 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000596 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
597 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000598 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000599 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
600 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000601
602 if (ParenTypeId) {
603 // Can't have dynamic array size when the type-id is in parentheses.
604 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
605 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
606 !NumElts->isIntegerConstantExpr(Context)) {
607 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
608 << NumElts->getSourceRange();
609 return ExprError();
610 }
611 }
612
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000613 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000614 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000615 }
616
Douglas Gregor043cad22009-09-11 00:18:58 +0000617 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000618 if (ArraySize) {
619 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000620 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
621 break;
622
623 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
624 if (Expr *NumElts = (Expr *)Array.NumElts) {
625 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
626 !NumElts->isIntegerConstantExpr(Context)) {
627 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
628 << NumElts->getSourceRange();
629 return ExprError();
630 }
631 }
632 }
633 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000634
John McCalla93c9342009-12-07 02:54:59 +0000635 //FIXME: Store TypeSourceInfo in CXXNew expression.
636 TypeSourceInfo *TInfo = 0;
637 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000638 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000639 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000640
Mike Stump1eb44332009-09-09 15:08:12 +0000641 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000642 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000643 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000644 PlacementRParen,
645 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000646 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000647 D.getSourceRange().getBegin(),
648 D.getSourceRange(),
649 Owned(ArraySize),
650 ConstructorLParen,
651 move(ConstructorArgs),
652 ConstructorRParen);
653}
654
Mike Stump1eb44332009-09-09 15:08:12 +0000655Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000656Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
657 SourceLocation PlacementLParen,
658 MultiExprArg PlacementArgs,
659 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000660 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000661 QualType AllocType,
662 SourceLocation TypeLoc,
663 SourceRange TypeRange,
664 ExprArg ArraySizeE,
665 SourceLocation ConstructorLParen,
666 MultiExprArg ConstructorArgs,
667 SourceLocation ConstructorRParen) {
668 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000669 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000670
Douglas Gregor3433cf72009-05-21 00:00:09 +0000671 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000672
673 // That every array dimension except the first is constant was already
674 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000675
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000676 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
677 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000678 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000679 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000680 QualType SizeType = ArraySize->getType();
681 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000682 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
683 diag::err_array_size_not_integral)
684 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000685 // Let's see if this is a constant < 0. If so, we reject it out of hand.
686 // We don't care about special rules, so we tell the machinery it's not
687 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000688 if (!ArraySize->isValueDependent()) {
689 llvm::APSInt Value;
690 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
691 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000692 llvm::APInt::getNullValue(Value.getBitWidth()),
693 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000694 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
695 diag::err_typecheck_negative_array_size)
696 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000697 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000698 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000699
Eli Friedman73c39ab2009-10-20 08:27:19 +0000700 ImpCastExprToType(ArraySize, Context.getSizeType(),
701 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000702 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000703
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000704 FunctionDecl *OperatorNew = 0;
705 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000706 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
707 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000708
Sebastian Redl28507842009-02-26 14:39:58 +0000709 if (!AllocType->isDependentType() &&
710 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
711 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000712 SourceRange(PlacementLParen, PlacementRParen),
713 UseGlobal, AllocType, ArraySize, PlaceArgs,
714 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000715 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000716 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000717 if (OperatorNew) {
718 // Add default arguments, if any.
719 const FunctionProtoType *Proto =
720 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000721 VariadicCallType CallType =
722 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000723 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
724 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000725 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000726 if (Invalid)
727 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000728
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000729 NumPlaceArgs = AllPlaceArgs.size();
730 if (NumPlaceArgs > 0)
731 PlaceArgs = &AllPlaceArgs[0];
732 }
733
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000734 bool Init = ConstructorLParen.isValid();
735 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000736 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000737 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
738 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000739 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
740
Douglas Gregor99a2e602009-12-16 01:38:02 +0000741 if (!AllocType->isDependentType() &&
742 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
743 // C++0x [expr.new]p15:
744 // A new-expression that creates an object of type T initializes that
745 // object as follows:
746 InitializationKind Kind
747 // - If the new-initializer is omitted, the object is default-
748 // initialized (8.5); if no initialization is performed,
749 // the object has indeterminate value
750 = !Init? InitializationKind::CreateDefault(TypeLoc)
751 // - Otherwise, the new-initializer is interpreted according to the
752 // initialization rules of 8.5 for direct-initialization.
753 : InitializationKind::CreateDirect(TypeLoc,
754 ConstructorLParen,
755 ConstructorRParen);
756
Douglas Gregor99a2e602009-12-16 01:38:02 +0000757 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000758 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000759 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000760 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
761 move(ConstructorArgs));
762 if (FullInit.isInvalid())
763 return ExprError();
764
765 // FullInit is our initializer; walk through it to determine if it's a
766 // constructor call, which CXXNewExpr handles directly.
767 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
768 if (CXXBindTemporaryExpr *Binder
769 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
770 FullInitExpr = Binder->getSubExpr();
771 if (CXXConstructExpr *Construct
772 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
773 Constructor = Construct->getConstructor();
774 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
775 AEnd = Construct->arg_end();
776 A != AEnd; ++A)
777 ConvertedConstructorArgs.push_back(A->Retain());
778 } else {
779 // Take the converted initializer.
780 ConvertedConstructorArgs.push_back(FullInit.release());
781 }
782 } else {
783 // No initialization required.
784 }
785
786 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000787 NumConsArgs = ConvertedConstructorArgs.size();
788 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000789 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000790
Douglas Gregor6d908702010-02-26 05:06:18 +0000791 // Mark the new and delete operators as referenced.
792 if (OperatorNew)
793 MarkDeclarationReferenced(StartLoc, OperatorNew);
794 if (OperatorDelete)
795 MarkDeclarationReferenced(StartLoc, OperatorDelete);
796
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000797 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000798
Sebastian Redlf53597f2009-03-15 17:47:39 +0000799 PlacementArgs.release();
800 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000801 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000802 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
803 PlaceArgs, NumPlaceArgs, ParenTypeId,
804 ArraySize, Constructor, Init,
805 ConsArgs, NumConsArgs, OperatorDelete,
806 ResultType, StartLoc,
807 Init ? ConstructorRParen :
808 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000809}
810
811/// CheckAllocatedType - Checks that a type is suitable as the allocated type
812/// in a new-expression.
813/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000814bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000815 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000816 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
817 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000818 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000819 return Diag(Loc, diag::err_bad_new_type)
820 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000821 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000822 return Diag(Loc, diag::err_bad_new_type)
823 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000824 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000825 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000826 PDiag(diag::err_new_incomplete_type)
827 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000828 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000829 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000830 diag::err_allocation_of_abstract_type))
831 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000832
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000833 return false;
834}
835
Douglas Gregor6d908702010-02-26 05:06:18 +0000836/// \brief Determine whether the given function is a non-placement
837/// deallocation function.
838static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
839 if (FD->isInvalidDecl())
840 return false;
841
842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
843 return Method->isUsualDeallocationFunction();
844
845 return ((FD->getOverloadedOperator() == OO_Delete ||
846 FD->getOverloadedOperator() == OO_Array_Delete) &&
847 FD->getNumParams() == 1);
848}
849
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000850/// FindAllocationFunctions - Finds the overloads of operator new and delete
851/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000852bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
853 bool UseGlobal, QualType AllocType,
854 bool IsArray, Expr **PlaceArgs,
855 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000856 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000857 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000858 // --- Choosing an allocation function ---
859 // C++ 5.3.4p8 - 14 & 18
860 // 1) If UseGlobal is true, only look in the global scope. Else, also look
861 // in the scope of the allocated class.
862 // 2) If an array size is given, look for operator new[], else look for
863 // operator new.
864 // 3) The first argument is always size_t. Append the arguments from the
865 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000866
867 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
868 // We don't care about the actual value of this argument.
869 // FIXME: Should the Sema create the expression and embed it in the syntax
870 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000871 IntegerLiteral Size(llvm::APInt::getNullValue(
872 Context.Target.getPointerWidth(0)),
873 Context.getSizeType(),
874 SourceLocation());
875 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000876 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
877
Douglas Gregor6d908702010-02-26 05:06:18 +0000878 // C++ [expr.new]p8:
879 // If the allocated type is a non-array type, the allocation
880 // function’s name is operator new and the deallocation function’s
881 // name is operator delete. If the allocated type is an array
882 // type, the allocation function’s name is operator new[] and the
883 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000884 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
885 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000886 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
887 IsArray ? OO_Array_Delete : OO_Delete);
888
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000889 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000890 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000891 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000892 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000893 AllocArgs.size(), Record, /*AllowMissing=*/true,
894 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000895 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000896 }
897 if (!OperatorNew) {
898 // Didn't find a member overload. Look for a global one.
899 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000900 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000901 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000902 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
903 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000904 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000905 }
906
John McCall9c82afc2010-04-20 02:18:25 +0000907 // We don't need an operator delete if we're running under
908 // -fno-exceptions.
909 if (!getLangOptions().Exceptions) {
910 OperatorDelete = 0;
911 return false;
912 }
913
Anders Carlssond9583892009-05-31 20:26:12 +0000914 // FindAllocationOverload can change the passed in arguments, so we need to
915 // copy them back.
916 if (NumPlaceArgs > 0)
917 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Douglas Gregor6d908702010-02-26 05:06:18 +0000919 // C++ [expr.new]p19:
920 //
921 // If the new-expression begins with a unary :: operator, the
922 // deallocation function’s name is looked up in the global
923 // scope. Otherwise, if the allocated type is a class type T or an
924 // array thereof, the deallocation function’s name is looked up in
925 // the scope of T. If this lookup fails to find the name, or if
926 // the allocated type is not a class type or array thereof, the
927 // deallocation function’s name is looked up in the global scope.
928 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
929 if (AllocType->isRecordType() && !UseGlobal) {
930 CXXRecordDecl *RD
931 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
932 LookupQualifiedName(FoundDelete, RD);
933 }
John McCall90c8c572010-03-18 08:19:33 +0000934 if (FoundDelete.isAmbiguous())
935 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000936
937 if (FoundDelete.empty()) {
938 DeclareGlobalNewDelete();
939 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
940 }
941
942 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000943
944 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
945
John McCall90c8c572010-03-18 08:19:33 +0000946 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000947 // C++ [expr.new]p20:
948 // A declaration of a placement deallocation function matches the
949 // declaration of a placement allocation function if it has the
950 // same number of parameters and, after parameter transformations
951 // (8.3.5), all parameter types except the first are
952 // identical. [...]
953 //
954 // To perform this comparison, we compute the function type that
955 // the deallocation function should have, and use that type both
956 // for template argument deduction and for comparison purposes.
957 QualType ExpectedFunctionType;
958 {
959 const FunctionProtoType *Proto
960 = OperatorNew->getType()->getAs<FunctionProtoType>();
961 llvm::SmallVector<QualType, 4> ArgTypes;
962 ArgTypes.push_back(Context.VoidPtrTy);
963 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
964 ArgTypes.push_back(Proto->getArgType(I));
965
966 ExpectedFunctionType
967 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
968 ArgTypes.size(),
969 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +0000970 0, false, false, 0, 0,
971 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +0000972 }
973
974 for (LookupResult::iterator D = FoundDelete.begin(),
975 DEnd = FoundDelete.end();
976 D != DEnd; ++D) {
977 FunctionDecl *Fn = 0;
978 if (FunctionTemplateDecl *FnTmpl
979 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
980 // Perform template argument deduction to try to match the
981 // expected function type.
982 TemplateDeductionInfo Info(Context, StartLoc);
983 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
984 continue;
985 } else
986 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
987
988 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +0000989 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +0000990 }
991 } else {
992 // C++ [expr.new]p20:
993 // [...] Any non-placement deallocation function matches a
994 // non-placement allocation function. [...]
995 for (LookupResult::iterator D = FoundDelete.begin(),
996 DEnd = FoundDelete.end();
997 D != DEnd; ++D) {
998 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
999 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001000 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001001 }
1002 }
1003
1004 // C++ [expr.new]p20:
1005 // [...] If the lookup finds a single matching deallocation
1006 // function, that function will be called; otherwise, no
1007 // deallocation function will be called.
1008 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001009 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001010
1011 // C++0x [expr.new]p20:
1012 // If the lookup finds the two-parameter form of a usual
1013 // deallocation function (3.7.4.2) and that function, considered
1014 // as a placement deallocation function, would have been
1015 // selected as a match for the allocation function, the program
1016 // is ill-formed.
1017 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1018 isNonPlacementDeallocationFunction(OperatorDelete)) {
1019 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1020 << SourceRange(PlaceArgs[0]->getLocStart(),
1021 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1022 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1023 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001024 } else {
1025 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001026 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001027 }
1028 }
1029
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001030 return false;
1031}
1032
Sebastian Redl7f662392008-12-04 22:20:51 +00001033/// FindAllocationOverload - Find an fitting overload for the allocation
1034/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001035bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1036 DeclarationName Name, Expr** Args,
1037 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001038 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001039 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1040 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001041 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001042 if (AllowMissing)
1043 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001044 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001045 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001046 }
1047
John McCall90c8c572010-03-18 08:19:33 +00001048 if (R.isAmbiguous())
1049 return true;
1050
1051 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001052
John McCall5769d612010-02-08 23:07:23 +00001053 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001054 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1055 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001056 // Even member operator new/delete are implicitly treated as
1057 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001058 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001059
John McCall9aa472c2010-03-19 07:35:19 +00001060 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1061 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001062 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1063 Candidates,
1064 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001065 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001066 }
1067
John McCall9aa472c2010-03-19 07:35:19 +00001068 FunctionDecl *Fn = cast<FunctionDecl>(D);
1069 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001070 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001071 }
1072
1073 // Do the resolution.
1074 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001075 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001076 case OR_Success: {
1077 // Got one!
1078 FunctionDecl *FnDecl = Best->Function;
1079 // The first argument is size_t, and the first parameter must be size_t,
1080 // too. This is checked on declaration and can be assumed. (It can't be
1081 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001082 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001083 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1084 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001085 OwningExprResult Result
1086 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1087 FnDecl->getParamDecl(i)),
1088 SourceLocation(),
1089 Owned(Args[i]->Retain()));
1090 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001091 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001092
1093 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001094 }
1095 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001096 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001097 return false;
1098 }
1099
1100 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001101 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001102 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001103 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001104 return true;
1105
1106 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001107 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001108 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001109 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001110 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001111
1112 case OR_Deleted:
1113 Diag(StartLoc, diag::err_ovl_deleted_call)
1114 << Best->Function->isDeleted()
1115 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001116 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001117 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001118 }
1119 assert(false && "Unreachable, bad result from BestViableFunction");
1120 return true;
1121}
1122
1123
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001124/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1125/// delete. These are:
1126/// @code
1127/// void* operator new(std::size_t) throw(std::bad_alloc);
1128/// void* operator new[](std::size_t) throw(std::bad_alloc);
1129/// void operator delete(void *) throw();
1130/// void operator delete[](void *) throw();
1131/// @endcode
1132/// Note that the placement and nothrow forms of new are *not* implicitly
1133/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001134void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001135 if (GlobalNewDeleteDeclared)
1136 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001137
1138 // C++ [basic.std.dynamic]p2:
1139 // [...] The following allocation and deallocation functions (18.4) are
1140 // implicitly declared in global scope in each translation unit of a
1141 // program
1142 //
1143 // void* operator new(std::size_t) throw(std::bad_alloc);
1144 // void* operator new[](std::size_t) throw(std::bad_alloc);
1145 // void operator delete(void*) throw();
1146 // void operator delete[](void*) throw();
1147 //
1148 // These implicit declarations introduce only the function names operator
1149 // new, operator new[], operator delete, operator delete[].
1150 //
1151 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1152 // "std" or "bad_alloc" as necessary to form the exception specification.
1153 // However, we do not make these implicit declarations visible to name
1154 // lookup.
1155 if (!StdNamespace) {
1156 // The "std" namespace has not yet been defined, so build one implicitly.
1157 StdNamespace = NamespaceDecl::Create(Context,
1158 Context.getTranslationUnitDecl(),
1159 SourceLocation(),
1160 &PP.getIdentifierTable().get("std"));
1161 StdNamespace->setImplicit(true);
1162 }
1163
1164 if (!StdBadAlloc) {
1165 // The "std::bad_alloc" class has not yet been declared, so build it
1166 // implicitly.
1167 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1168 StdNamespace,
1169 SourceLocation(),
1170 &PP.getIdentifierTable().get("bad_alloc"),
1171 SourceLocation(), 0);
1172 StdBadAlloc->setImplicit(true);
1173 }
1174
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001175 GlobalNewDeleteDeclared = true;
1176
1177 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1178 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001179 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001180
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001181 DeclareGlobalAllocationFunction(
1182 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001183 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001184 DeclareGlobalAllocationFunction(
1185 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001186 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001187 DeclareGlobalAllocationFunction(
1188 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1189 Context.VoidTy, VoidPtr);
1190 DeclareGlobalAllocationFunction(
1191 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1192 Context.VoidTy, VoidPtr);
1193}
1194
1195/// DeclareGlobalAllocationFunction - Declares a single implicit global
1196/// allocation function if it doesn't already exist.
1197void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001198 QualType Return, QualType Argument,
1199 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001200 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1201
1202 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001203 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001204 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001205 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001206 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001207 // Only look at non-template functions, as it is the predefined,
1208 // non-templated allocation function we are trying to declare here.
1209 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1210 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001211 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001212 Func->getParamDecl(0)->getType().getUnqualifiedType());
1213 // FIXME: Do we need to check for default arguments here?
1214 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1215 return;
1216 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001217 }
1218 }
1219
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001220 QualType BadAllocType;
1221 bool HasBadAllocExceptionSpec
1222 = (Name.getCXXOverloadedOperator() == OO_New ||
1223 Name.getCXXOverloadedOperator() == OO_Array_New);
1224 if (HasBadAllocExceptionSpec) {
1225 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1226 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1227 }
1228
1229 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1230 true, false,
1231 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001232 &BadAllocType,
1233 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001234 FunctionDecl *Alloc =
1235 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001236 FnType, /*TInfo=*/0, FunctionDecl::None,
1237 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001238 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001239
1240 if (AddMallocAttr)
1241 Alloc->addAttr(::new (Context) MallocAttr());
1242
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001243 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001244 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001245 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001246 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001247 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001248
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001249 // FIXME: Also add this declaration to the IdentifierResolver, but
1250 // make sure it is at the end of the chain to coincide with the
1251 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001252 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001253}
1254
Anders Carlsson78f74552009-11-15 18:45:20 +00001255bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1256 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001257 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001258 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001259 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001260 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001261
John McCalla24dc2e2009-11-17 02:14:36 +00001262 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001263 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001264
1265 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1266 F != FEnd; ++F) {
1267 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1268 if (Delete->isUsualDeallocationFunction()) {
1269 Operator = Delete;
1270 return false;
1271 }
1272 }
1273
1274 // We did find operator delete/operator delete[] declarations, but
1275 // none of them were suitable.
1276 if (!Found.empty()) {
1277 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1278 << Name << RD;
1279
1280 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1281 F != FEnd; ++F) {
Douglas Gregorb0fd4832010-04-25 20:55:08 +00001282 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlsson78f74552009-11-15 18:45:20 +00001283 << Name;
1284 }
1285
1286 return true;
1287 }
1288
1289 // Look for a global declaration.
1290 DeclareGlobalNewDelete();
1291 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1292
1293 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1294 Expr* DeallocArgs[1];
1295 DeallocArgs[0] = &Null;
1296 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1297 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1298 Operator))
1299 return true;
1300
1301 assert(Operator && "Did not find a deallocation function!");
1302 return false;
1303}
1304
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001305/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1306/// @code ::delete ptr; @endcode
1307/// or
1308/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001309Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001310Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001311 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001312 // C++ [expr.delete]p1:
1313 // The operand shall have a pointer type, or a class type having a single
1314 // conversion function to a pointer type. The result has type void.
1315 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001316 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1317
Anders Carlssond67c4c32009-08-16 20:29:29 +00001318 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Sebastian Redlf53597f2009-03-15 17:47:39 +00001320 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001321 if (!Ex->isTypeDependent()) {
1322 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001323
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001324 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001325 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1326
Fariborz Jahanian53462782009-09-11 21:44:33 +00001327 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001328 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001329 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001330 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001331 NamedDecl *D = I.getDecl();
1332 if (isa<UsingShadowDecl>(D))
1333 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1334
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001335 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001336 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001337 continue;
1338
John McCall32daa422010-03-31 01:36:47 +00001339 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001340
1341 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1342 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1343 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001344 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001345 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001346 if (ObjectPtrConversions.size() == 1) {
1347 // We have a single conversion to a pointer-to-object type. Perform
1348 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001349 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001350 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001351 if (!PerformImplicitConversion(Ex,
1352 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001353 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001354 Operand = Owned(Ex);
1355 Type = Ex->getType();
1356 }
1357 }
1358 else if (ObjectPtrConversions.size() > 1) {
1359 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1360 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001361 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1362 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001363 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001364 }
Sebastian Redl28507842009-02-26 14:39:58 +00001365 }
1366
Sebastian Redlf53597f2009-03-15 17:47:39 +00001367 if (!Type->isPointerType())
1368 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1369 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001370
Ted Kremenek6217b802009-07-29 21:53:49 +00001371 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001372 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001373 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1374 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001375 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001376 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001377 PDiag(diag::warn_delete_incomplete)
1378 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001379 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001380
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001381 // C++ [expr.delete]p2:
1382 // [Note: a pointer to a const type can be the operand of a
1383 // delete-expression; it is not necessary to cast away the constness
1384 // (5.2.11) of the pointer expression before it is used as the operand
1385 // of the delete-expression. ]
1386 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1387 CastExpr::CK_NoOp);
1388
1389 // Update the operand.
1390 Operand.take();
1391 Operand = ExprArg(*this, Ex);
1392
Anders Carlssond67c4c32009-08-16 20:29:29 +00001393 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1394 ArrayForm ? OO_Array_Delete : OO_Delete);
1395
Anders Carlsson78f74552009-11-15 18:45:20 +00001396 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1397 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1398
1399 if (!UseGlobal &&
1400 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001401 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001402
Anders Carlsson78f74552009-11-15 18:45:20 +00001403 if (!RD->hasTrivialDestructor())
1404 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001405 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001406 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001407 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001408
Anders Carlssond67c4c32009-08-16 20:29:29 +00001409 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001410 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001411 DeclareGlobalNewDelete();
1412 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001413 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001414 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001415 OperatorDelete))
1416 return ExprError();
1417 }
Mike Stump1eb44332009-09-09 15:08:12 +00001418
John McCall9c82afc2010-04-20 02:18:25 +00001419 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1420
Sebastian Redl28507842009-02-26 14:39:58 +00001421 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001422 }
1423
Sebastian Redlf53597f2009-03-15 17:47:39 +00001424 Operand.release();
1425 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001426 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001427}
1428
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001429/// \brief Check the use of the given variable as a C++ condition in an if,
1430/// while, do-while, or switch statement.
1431Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1432 QualType T = ConditionVar->getType();
1433
1434 // C++ [stmt.select]p2:
1435 // The declarator shall not specify a function or an array.
1436 if (T->isFunctionType())
1437 return ExprError(Diag(ConditionVar->getLocation(),
1438 diag::err_invalid_use_of_function_type)
1439 << ConditionVar->getSourceRange());
1440 else if (T->isArrayType())
1441 return ExprError(Diag(ConditionVar->getLocation(),
1442 diag::err_invalid_use_of_array_type)
1443 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001444
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001445 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1446 ConditionVar->getLocation(),
1447 ConditionVar->getType().getNonReferenceType()));
1448}
1449
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001450/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1451bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1452 // C++ 6.4p4:
1453 // The value of a condition that is an initialized declaration in a statement
1454 // other than a switch statement is the value of the declared variable
1455 // implicitly converted to type bool. If that conversion is ill-formed, the
1456 // program is ill-formed.
1457 // The value of a condition that is an expression is the value of the
1458 // expression, implicitly converted to bool.
1459 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001460 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001461}
Douglas Gregor77a52232008-09-12 00:47:35 +00001462
1463/// Helper function to determine whether this is the (deprecated) C++
1464/// conversion from a string literal to a pointer to non-const char or
1465/// non-const wchar_t (for narrow and wide string literals,
1466/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001467bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001468Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1469 // Look inside the implicit cast, if it exists.
1470 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1471 From = Cast->getSubExpr();
1472
1473 // A string literal (2.13.4) that is not a wide string literal can
1474 // be converted to an rvalue of type "pointer to char"; a wide
1475 // string literal can be converted to an rvalue of type "pointer
1476 // to wchar_t" (C++ 4.2p2).
1477 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001478 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001479 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001480 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001481 // This conversion is considered only when there is an
1482 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001483 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001484 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1485 (!StrLit->isWide() &&
1486 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1487 ToPointeeType->getKind() == BuiltinType::Char_S))))
1488 return true;
1489 }
1490
1491 return false;
1492}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001493
Douglas Gregorba70ab62010-04-16 22:17:36 +00001494static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1495 SourceLocation CastLoc,
1496 QualType Ty,
1497 CastExpr::CastKind Kind,
1498 CXXMethodDecl *Method,
1499 Sema::ExprArg Arg) {
1500 Expr *From = Arg.takeAs<Expr>();
1501
1502 switch (Kind) {
1503 default: assert(0 && "Unhandled cast kind!");
1504 case CastExpr::CK_ConstructorConversion: {
1505 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1506
1507 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1508 Sema::MultiExprArg(S, (void **)&From, 1),
1509 CastLoc, ConstructorArgs))
1510 return S.ExprError();
1511
1512 Sema::OwningExprResult Result =
1513 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1514 move_arg(ConstructorArgs));
1515 if (Result.isInvalid())
1516 return S.ExprError();
1517
1518 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1519 }
1520
1521 case CastExpr::CK_UserDefinedConversion: {
1522 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1523
1524 // Create an implicit call expr that calls it.
1525 // FIXME: pass the FoundDecl for the user-defined conversion here
1526 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1527 return S.MaybeBindToTemporary(CE);
1528 }
1529 }
1530}
1531
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001532/// PerformImplicitConversion - Perform an implicit conversion of the
1533/// expression From to the type ToType using the pre-computed implicit
1534/// conversion sequence ICS. Returns true if there was an error, false
1535/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001536/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001537/// used in the error message.
1538bool
1539Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1540 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001541 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001542 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001543 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001544 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001545 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001546 return true;
1547 break;
1548
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001549 case ImplicitConversionSequence::UserDefinedConversion: {
1550
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001551 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1552 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001553 QualType BeforeToType;
1554 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001555 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001556
1557 // If the user-defined conversion is specified by a conversion function,
1558 // the initial standard conversion sequence converts the source type to
1559 // the implicit object parameter of the conversion function.
1560 BeforeToType = Context.getTagDeclType(Conv->getParent());
1561 } else if (const CXXConstructorDecl *Ctor =
1562 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001563 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001564 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001565 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001566 // If the user-defined conversion is specified by a constructor, the
1567 // initial standard conversion sequence converts the source type to the
1568 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001569 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1570 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001571 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001572 else
1573 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001574 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001575 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001576 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001577 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001578 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001579 return true;
1580 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001581
Anders Carlsson0aebc812009-09-09 21:33:21 +00001582 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001583 = BuildCXXCastArgument(*this,
1584 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001585 ToType.getNonReferenceType(),
1586 CastKind, cast<CXXMethodDecl>(FD),
1587 Owned(From));
1588
1589 if (CastArg.isInvalid())
1590 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001591
1592 From = CastArg.takeAs<Expr>();
1593
Eli Friedmand8889622009-11-27 04:41:50 +00001594 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001595 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001596 }
John McCall1d318332010-01-12 00:44:57 +00001597
1598 case ImplicitConversionSequence::AmbiguousConversion:
1599 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1600 PDiag(diag::err_typecheck_ambiguous_condition)
1601 << From->getSourceRange());
1602 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001603
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001604 case ImplicitConversionSequence::EllipsisConversion:
1605 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001606 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001607
1608 case ImplicitConversionSequence::BadConversion:
1609 return true;
1610 }
1611
1612 // Everything went well.
1613 return false;
1614}
1615
1616/// PerformImplicitConversion - Perform an implicit conversion of the
1617/// expression From to the type ToType by following the standard
1618/// conversion sequence SCS. Returns true if there was an error, false
1619/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001620/// expression. Flavor is the context in which we're performing this
1621/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001622bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001623Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001624 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001625 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001626 // Overall FIXME: we are recomputing too many types here and doing far too
1627 // much extra work. What this means is that we need to keep track of more
1628 // information that is computed when we try the implicit conversion initially,
1629 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001630 QualType FromType = From->getType();
1631
Douglas Gregor225c41e2008-11-03 19:09:14 +00001632 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001633 // FIXME: When can ToType be a reference type?
1634 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001635 if (SCS.Second == ICK_Derived_To_Base) {
1636 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1637 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1638 MultiExprArg(*this, (void **)&From, 1),
1639 /*FIXME:ConstructLoc*/SourceLocation(),
1640 ConstructorArgs))
1641 return true;
1642 OwningExprResult FromResult =
1643 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1644 ToType, SCS.CopyConstructor,
1645 move_arg(ConstructorArgs));
1646 if (FromResult.isInvalid())
1647 return true;
1648 From = FromResult.takeAs<Expr>();
1649 return false;
1650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651 OwningExprResult FromResult =
1652 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1653 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001654 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001656 if (FromResult.isInvalid())
1657 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001659 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001660 return false;
1661 }
1662
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001663 // Perform the first implicit conversion.
1664 switch (SCS.First) {
1665 case ICK_Identity:
1666 case ICK_Lvalue_To_Rvalue:
1667 // Nothing to do.
1668 break;
1669
1670 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001671 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001672 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001673 break;
1674
1675 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001676 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00001677 DeclAccessPair Found;
1678 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1679 true, Found);
Douglas Gregor904eed32008-11-10 20:40:00 +00001680 if (!Fn)
1681 return true;
1682
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001683 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1684 return true;
1685
John McCall6bb80172010-03-30 21:47:33 +00001686 From = FixOverloadedFunctionReference(From, Found, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001687 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001688
Sebastian Redl759986e2009-10-17 20:50:27 +00001689 // If there's already an address-of operator in the expression, we have
1690 // the right type already, and the code below would just introduce an
1691 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001692 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001693 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001694 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001695 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001696 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001697 break;
1698
1699 default:
1700 assert(false && "Improper first standard conversion");
1701 break;
1702 }
1703
1704 // Perform the second implicit conversion
1705 switch (SCS.Second) {
1706 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001707 // If both sides are functions (or pointers/references to them), there could
1708 // be incompatible exception declarations.
1709 if (CheckExceptionSpecCompatibility(From, ToType))
1710 return true;
1711 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001712 break;
1713
Douglas Gregor43c79c22009-12-09 00:47:37 +00001714 case ICK_NoReturn_Adjustment:
1715 // If both sides are functions (or pointers/references to them), there could
1716 // be incompatible exception declarations.
1717 if (CheckExceptionSpecCompatibility(From, ToType))
1718 return true;
1719
1720 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1721 CastExpr::CK_NoOp);
1722 break;
1723
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001724 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001725 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001726 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1727 break;
1728
1729 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001730 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001731 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1732 break;
1733
1734 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001735 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001736 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1737 break;
1738
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001739 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001740 if (ToType->isFloatingType())
1741 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1742 else
1743 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1744 break;
1745
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001746 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001747 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1748 break;
1749
Douglas Gregorf9201e02009-02-11 23:02:49 +00001750 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001751 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001752 break;
1753
Anders Carlsson61faec12009-09-12 04:46:44 +00001754 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001755 if (SCS.IncompatibleObjC) {
1756 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001757 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001758 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001759 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001760 << From->getSourceRange();
1761 }
1762
Anders Carlsson61faec12009-09-12 04:46:44 +00001763
1764 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001765 CXXBaseSpecifierArray BasePath;
1766 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001767 return true;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001768 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001769 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001770 }
1771
1772 case ICK_Pointer_Member: {
1773 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001774 CXXBaseSpecifierArray BasePath;
1775 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1776 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001777 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001778 if (CheckExceptionSpecCompatibility(From, ToType))
1779 return true;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001780 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001781 break;
1782 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001783 case ICK_Boolean_Conversion: {
1784 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1785 if (FromType->isMemberPointerType())
1786 Kind = CastExpr::CK_MemberPointerToBoolean;
1787
1788 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001789 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001790 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001791
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001792 case ICK_Derived_To_Base:
1793 if (CheckDerivedToBaseConversion(From->getType(),
1794 ToType.getNonReferenceType(),
1795 From->getLocStart(),
Anders Carlssone25a96c2010-04-24 17:11:09 +00001796 From->getSourceRange(), 0,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001797 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001798 return true;
1799 ImpCastExprToType(From, ToType.getNonReferenceType(),
1800 CastExpr::CK_DerivedToBase);
1801 break;
1802
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001803 default:
1804 assert(false && "Improper second standard conversion");
1805 break;
1806 }
1807
1808 switch (SCS.Third) {
1809 case ICK_Identity:
1810 // Nothing to do.
1811 break;
1812
1813 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001814 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1815 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001816 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00001817 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001818
1819 if (SCS.DeprecatedStringLiteralToCharPtr)
1820 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1821 << ToType.getNonReferenceType();
1822
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001823 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001824
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001825 default:
1826 assert(false && "Improper second standard conversion");
1827 break;
1828 }
1829
1830 return false;
1831}
1832
Sebastian Redl64b45f72009-01-05 20:52:13 +00001833Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1834 SourceLocation KWLoc,
1835 SourceLocation LParen,
1836 TypeTy *Ty,
1837 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001838 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001840 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1841 // all traits except __is_class, __is_enum and __is_union require a the type
1842 // to be complete.
1843 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001844 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001845 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001846 return ExprError();
1847 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001848
1849 // There is no point in eagerly computing the value. The traits are designed
1850 // to be used from type trait templates, so Ty will be a template parameter
1851 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001852 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1853 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001854}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001855
1856QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001857 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001858 const char *OpSpelling = isIndirect ? "->*" : ".*";
1859 // C++ 5.5p2
1860 // The binary operator .* [p3: ->*] binds its second operand, which shall
1861 // be of type "pointer to member of T" (where T is a completely-defined
1862 // class type) [...]
1863 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001864 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001865 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001866 Diag(Loc, diag::err_bad_memptr_rhs)
1867 << OpSpelling << RType << rex->getSourceRange();
1868 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001869 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001870
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001871 QualType Class(MemPtr->getClass(), 0);
1872
Sebastian Redl59fc2692010-04-10 10:14:54 +00001873 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1874 return QualType();
1875
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001876 // C++ 5.5p2
1877 // [...] to its first operand, which shall be of class T or of a class of
1878 // which T is an unambiguous and accessible base class. [p3: a pointer to
1879 // such a class]
1880 QualType LType = lex->getType();
1881 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001882 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001883 LType = Ptr->getPointeeType().getNonReferenceType();
1884 else {
1885 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001886 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001887 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001888 return QualType();
1889 }
1890 }
1891
Douglas Gregora4923eb2009-11-16 21:35:15 +00001892 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001893 // If we want to check the hierarchy, we need a complete type.
1894 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1895 << OpSpelling << (int)isIndirect)) {
1896 return QualType();
1897 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001898 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001899 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001900 // FIXME: Would it be useful to print full ambiguity paths, or is that
1901 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001902 if (!IsDerivedFrom(LType, Class, Paths) ||
1903 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1904 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001905 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001906 return QualType();
1907 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001908 // Cast LHS to type of use.
1909 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1910 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001911
1912 CXXBaseSpecifierArray BasePath;
1913 BuildBasePathArray(Paths, BasePath);
1914 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1915 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001916 }
1917
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001918 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001919 // Diagnose use of pointer-to-member type which when used as
1920 // the functional cast in a pointer-to-member expression.
1921 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1922 return QualType();
1923 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001924 // C++ 5.5p2
1925 // The result is an object or a function of the type specified by the
1926 // second operand.
1927 // The cv qualifiers are the union of those in the pointer and the left side,
1928 // in accordance with 5.5p5 and 5.2.5.
1929 // FIXME: This returns a dereferenced member function pointer as a normal
1930 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001931 // calling them. There's also a GCC extension to get a function pointer to the
1932 // thing, which is another complication, because this type - unlike the type
1933 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001934 // argument.
1935 // We probably need a "MemberFunctionClosureType" or something like that.
1936 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001937 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001938 return Result;
1939}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001940
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001941/// \brief Try to convert a type to another according to C++0x 5.16p3.
1942///
1943/// This is part of the parameter validation for the ? operator. If either
1944/// value operand is a class type, the two operands are attempted to be
1945/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001946/// It returns true if the program is ill-formed and has already been diagnosed
1947/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001948static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1949 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00001950 bool &HaveConversion,
1951 QualType &ToType) {
1952 HaveConversion = false;
1953 ToType = To->getType();
1954
1955 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1956 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001957 // C++0x 5.16p3
1958 // The process for determining whether an operand expression E1 of type T1
1959 // can be converted to match an operand expression E2 of type T2 is defined
1960 // as follows:
1961 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001962 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1963 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001964 // E1 can be converted to match E2 if E1 can be implicitly converted to
1965 // type "lvalue reference to T2", subject to the constraint that in the
1966 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001967 QualType T = Self.Context.getLValueReferenceType(ToType);
1968 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1969
1970 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1971 if (InitSeq.isDirectReferenceBinding()) {
1972 ToType = T;
1973 HaveConversion = true;
1974 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001975 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001976
1977 if (InitSeq.isAmbiguous())
1978 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001979 }
John McCallb1bdc622010-02-25 01:37:24 +00001980
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001981 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1982 // -- if E1 and E2 have class type, and the underlying class types are
1983 // the same or one is a base class of the other:
1984 QualType FTy = From->getType();
1985 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001986 const RecordType *FRec = FTy->getAs<RecordType>();
1987 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00001988 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1989 Self.IsDerivedFrom(FTy, TTy);
1990 if (FRec && TRec &&
1991 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001992 // E1 can be converted to match E2 if the class of T2 is the
1993 // same type as, or a base class of, the class of T1, and
1994 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00001995 if (FRec == TRec || FDerivedFromT) {
1996 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00001997 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1998 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1999 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2000 HaveConversion = true;
2001 return false;
2002 }
2003
2004 if (InitSeq.isAmbiguous())
2005 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2006 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002007 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002008
2009 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002010 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002011
2012 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2013 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002014 // if E2 were converted to an rvalue (or the type it has, if E2 is
2015 // an rvalue).
2016 //
2017 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2018 // to the array-to-pointer or function-to-pointer conversions.
2019 if (!TTy->getAs<TagType>())
2020 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002021
2022 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2023 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2024 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2025 ToType = TTy;
2026 if (InitSeq.isAmbiguous())
2027 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2028
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002029 return false;
2030}
2031
2032/// \brief Try to find a common type for two according to C++0x 5.16p5.
2033///
2034/// This is part of the parameter validation for the ? operator. If either
2035/// value operand is a class type, overload resolution is used to find a
2036/// conversion to a common type.
2037static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2038 SourceLocation Loc) {
2039 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002040 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002041 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002042
2043 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002044 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002045 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002046 // We found a match. Perform the conversions on the arguments and move on.
2047 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002048 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002049 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002050 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002051 break;
2052 return false;
2053
Douglas Gregor20093b42009-12-09 23:02:17 +00002054 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002055 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2056 << LHS->getType() << RHS->getType()
2057 << LHS->getSourceRange() << RHS->getSourceRange();
2058 return true;
2059
Douglas Gregor20093b42009-12-09 23:02:17 +00002060 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002061 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2062 << LHS->getType() << RHS->getType()
2063 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002064 // FIXME: Print the possible common types by printing the return types of
2065 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002066 break;
2067
Douglas Gregor20093b42009-12-09 23:02:17 +00002068 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002069 assert(false && "Conditional operator has only built-in overloads");
2070 break;
2071 }
2072 return true;
2073}
2074
Sebastian Redl76458502009-04-17 16:30:52 +00002075/// \brief Perform an "extended" implicit conversion as returned by
2076/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002077static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2078 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2079 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2080 SourceLocation());
2081 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2082 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2083 Sema::MultiExprArg(Self, (void **)&E, 1));
2084 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002085 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002086
2087 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002088 return false;
2089}
2090
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002091/// \brief Check the operands of ?: under C++ semantics.
2092///
2093/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2094/// extension. In this case, LHS == Cond. (But they're not aliases.)
2095QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2096 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002097 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2098 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002099
2100 // C++0x 5.16p1
2101 // The first expression is contextually converted to bool.
2102 if (!Cond->isTypeDependent()) {
2103 if (CheckCXXBooleanCondition(Cond))
2104 return QualType();
2105 }
2106
2107 // Either of the arguments dependent?
2108 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2109 return Context.DependentTy;
2110
John McCalld1b47bf2010-03-11 19:43:18 +00002111 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCallb13c87f2009-11-05 09:23:39 +00002112
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002113 // C++0x 5.16p2
2114 // If either the second or the third operand has type (cv) void, ...
2115 QualType LTy = LHS->getType();
2116 QualType RTy = RHS->getType();
2117 bool LVoid = LTy->isVoidType();
2118 bool RVoid = RTy->isVoidType();
2119 if (LVoid || RVoid) {
2120 // ... then the [l2r] conversions are performed on the second and third
2121 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002122 DefaultFunctionArrayLvalueConversion(LHS);
2123 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002124 LTy = LHS->getType();
2125 RTy = RHS->getType();
2126
2127 // ... and one of the following shall hold:
2128 // -- The second or the third operand (but not both) is a throw-
2129 // expression; the result is of the type of the other and is an rvalue.
2130 bool LThrow = isa<CXXThrowExpr>(LHS);
2131 bool RThrow = isa<CXXThrowExpr>(RHS);
2132 if (LThrow && !RThrow)
2133 return RTy;
2134 if (RThrow && !LThrow)
2135 return LTy;
2136
2137 // -- Both the second and third operands have type void; the result is of
2138 // type void and is an rvalue.
2139 if (LVoid && RVoid)
2140 return Context.VoidTy;
2141
2142 // Neither holds, error.
2143 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2144 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2145 << LHS->getSourceRange() << RHS->getSourceRange();
2146 return QualType();
2147 }
2148
2149 // Neither is void.
2150
2151 // C++0x 5.16p3
2152 // Otherwise, if the second and third operand have different types, and
2153 // either has (cv) class type, and attempt is made to convert each of those
2154 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002155 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002156 (LTy->isRecordType() || RTy->isRecordType())) {
2157 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2158 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002159 QualType L2RType, R2LType;
2160 bool HaveL2R, HaveR2L;
2161 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002162 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002163 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002164 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002165
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002166 // If both can be converted, [...] the program is ill-formed.
2167 if (HaveL2R && HaveR2L) {
2168 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2169 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2170 return QualType();
2171 }
2172
2173 // If exactly one conversion is possible, that conversion is applied to
2174 // the chosen operand and the converted operands are used in place of the
2175 // original operands for the remainder of this section.
2176 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002177 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002178 return QualType();
2179 LTy = LHS->getType();
2180 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002181 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002182 return QualType();
2183 RTy = RHS->getType();
2184 }
2185 }
2186
2187 // C++0x 5.16p4
2188 // If the second and third operands are lvalues and have the same type,
2189 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002190 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002191 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2192 RHS->isLvalue(Context) == Expr::LV_Valid)
2193 return LTy;
2194
2195 // C++0x 5.16p5
2196 // Otherwise, the result is an rvalue. If the second and third operands
2197 // do not have the same type, and either has (cv) class type, ...
2198 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2199 // ... overload resolution is used to determine the conversions (if any)
2200 // to be applied to the operands. If the overload resolution fails, the
2201 // program is ill-formed.
2202 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2203 return QualType();
2204 }
2205
2206 // C++0x 5.16p6
2207 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2208 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002209 DefaultFunctionArrayLvalueConversion(LHS);
2210 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002211 LTy = LHS->getType();
2212 RTy = RHS->getType();
2213
2214 // After those conversions, one of the following shall hold:
2215 // -- The second and third operands have the same type; the result
2216 // is of that type.
2217 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2218 return LTy;
2219
2220 // -- The second and third operands have arithmetic or enumeration type;
2221 // the usual arithmetic conversions are performed to bring them to a
2222 // common type, and the result is of that type.
2223 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2224 UsualArithmeticConversions(LHS, RHS);
2225 return LHS->getType();
2226 }
2227
2228 // -- The second and third operands have pointer type, or one has pointer
2229 // type and the other is a null pointer constant; pointer conversions
2230 // and qualification conversions are performed to bring them to their
2231 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002232 // -- The second and third operands have pointer to member type, or one has
2233 // pointer to member type and the other is a null pointer constant;
2234 // pointer to member conversions and qualification conversions are
2235 // performed to bring them to a common type, whose cv-qualification
2236 // shall match the cv-qualification of either the second or the third
2237 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002238 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002239 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002240 isSFINAEContext()? 0 : &NonStandardCompositeType);
2241 if (!Composite.isNull()) {
2242 if (NonStandardCompositeType)
2243 Diag(QuestionLoc,
2244 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2245 << LTy << RTy << Composite
2246 << LHS->getSourceRange() << RHS->getSourceRange();
2247
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002248 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002249 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002250
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002251 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002252 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2253 if (!Composite.isNull())
2254 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002255
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002256 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2257 << LHS->getType() << RHS->getType()
2258 << LHS->getSourceRange() << RHS->getSourceRange();
2259 return QualType();
2260}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002261
2262/// \brief Find a merged pointer type and convert the two expressions to it.
2263///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002264/// This finds the composite pointer type (or member pointer type) for @p E1
2265/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2266/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002267/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002268///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002269/// \param Loc The location of the operator requiring these two expressions to
2270/// be converted to the composite pointer type.
2271///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002272/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2273/// a non-standard (but still sane) composite type to which both expressions
2274/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2275/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002276QualType Sema::FindCompositePointerType(SourceLocation Loc,
2277 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002278 bool *NonStandardCompositeType) {
2279 if (NonStandardCompositeType)
2280 *NonStandardCompositeType = false;
2281
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002282 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2283 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002285 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2286 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002287 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002288
2289 // C++0x 5.9p2
2290 // Pointer conversions and qualification conversions are performed on
2291 // pointer operands to bring them to their composite pointer type. If
2292 // one operand is a null pointer constant, the composite pointer type is
2293 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002294 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002295 if (T2->isMemberPointerType())
2296 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2297 else
2298 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002299 return T2;
2300 }
Douglas Gregorce940492009-09-25 04:25:58 +00002301 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002302 if (T1->isMemberPointerType())
2303 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2304 else
2305 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002306 return T1;
2307 }
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregor20b3e992009-08-24 17:42:35 +00002309 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002310 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2311 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002312 return QualType();
2313
2314 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2315 // the other has type "pointer to cv2 T" and the composite pointer type is
2316 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2317 // Otherwise, the composite pointer type is a pointer type similar to the
2318 // type of one of the operands, with a cv-qualification signature that is
2319 // the union of the cv-qualification signatures of the operand types.
2320 // In practice, the first part here is redundant; it's subsumed by the second.
2321 // What we do here is, we build the two possible composite types, and try the
2322 // conversions in both directions. If only one works, or if the two composite
2323 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002324 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002325 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2326 QualifierVector QualifierUnion;
2327 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2328 ContainingClassVector;
2329 ContainingClassVector MemberOfClass;
2330 QualType Composite1 = Context.getCanonicalType(T1),
2331 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002332 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002333 do {
2334 const PointerType *Ptr1, *Ptr2;
2335 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2336 (Ptr2 = Composite2->getAs<PointerType>())) {
2337 Composite1 = Ptr1->getPointeeType();
2338 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002339
2340 // If we're allowed to create a non-standard composite type, keep track
2341 // of where we need to fill in additional 'const' qualifiers.
2342 if (NonStandardCompositeType &&
2343 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2344 NeedConstBefore = QualifierUnion.size();
2345
Douglas Gregor20b3e992009-08-24 17:42:35 +00002346 QualifierUnion.push_back(
2347 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2348 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2349 continue;
2350 }
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Douglas Gregor20b3e992009-08-24 17:42:35 +00002352 const MemberPointerType *MemPtr1, *MemPtr2;
2353 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2354 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2355 Composite1 = MemPtr1->getPointeeType();
2356 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002357
2358 // If we're allowed to create a non-standard composite type, keep track
2359 // of where we need to fill in additional 'const' qualifiers.
2360 if (NonStandardCompositeType &&
2361 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2362 NeedConstBefore = QualifierUnion.size();
2363
Douglas Gregor20b3e992009-08-24 17:42:35 +00002364 QualifierUnion.push_back(
2365 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2366 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2367 MemPtr2->getClass()));
2368 continue;
2369 }
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Douglas Gregor20b3e992009-08-24 17:42:35 +00002371 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregor20b3e992009-08-24 17:42:35 +00002373 // Cannot unwrap any more types.
2374 break;
2375 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002376
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002377 if (NeedConstBefore && NonStandardCompositeType) {
2378 // Extension: Add 'const' to qualifiers that come before the first qualifier
2379 // mismatch, so that our (non-standard!) composite type meets the
2380 // requirements of C++ [conv.qual]p4 bullet 3.
2381 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2382 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2383 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2384 *NonStandardCompositeType = true;
2385 }
2386 }
2387 }
2388
Douglas Gregor20b3e992009-08-24 17:42:35 +00002389 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002390 ContainingClassVector::reverse_iterator MOC
2391 = MemberOfClass.rbegin();
2392 for (QualifierVector::reverse_iterator
2393 I = QualifierUnion.rbegin(),
2394 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002395 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002396 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002397 if (MOC->first && MOC->second) {
2398 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002399 Composite1 = Context.getMemberPointerType(
2400 Context.getQualifiedType(Composite1, Quals),
2401 MOC->first);
2402 Composite2 = Context.getMemberPointerType(
2403 Context.getQualifiedType(Composite2, Quals),
2404 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002405 } else {
2406 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002407 Composite1
2408 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2409 Composite2
2410 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002411 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002412 }
2413
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002414 // Try to convert to the first composite pointer type.
2415 InitializedEntity Entity1
2416 = InitializedEntity::InitializeTemporary(Composite1);
2417 InitializationKind Kind
2418 = InitializationKind::CreateCopy(Loc, SourceLocation());
2419 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2420 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002421
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002422 if (E1ToC1 && E2ToC1) {
2423 // Conversion to Composite1 is viable.
2424 if (!Context.hasSameType(Composite1, Composite2)) {
2425 // Composite2 is a different type from Composite1. Check whether
2426 // Composite2 is also viable.
2427 InitializedEntity Entity2
2428 = InitializedEntity::InitializeTemporary(Composite2);
2429 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2430 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2431 if (E1ToC2 && E2ToC2) {
2432 // Both Composite1 and Composite2 are viable and are different;
2433 // this is an ambiguity.
2434 return QualType();
2435 }
2436 }
2437
2438 // Convert E1 to Composite1
2439 OwningExprResult E1Result
2440 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2441 if (E1Result.isInvalid())
2442 return QualType();
2443 E1 = E1Result.takeAs<Expr>();
2444
2445 // Convert E2 to Composite1
2446 OwningExprResult E2Result
2447 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2448 if (E2Result.isInvalid())
2449 return QualType();
2450 E2 = E2Result.takeAs<Expr>();
2451
2452 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002453 }
2454
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002455 // Check whether Composite2 is viable.
2456 InitializedEntity Entity2
2457 = InitializedEntity::InitializeTemporary(Composite2);
2458 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2459 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2460 if (!E1ToC2 || !E2ToC2)
2461 return QualType();
2462
2463 // Convert E1 to Composite2
2464 OwningExprResult E1Result
2465 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2466 if (E1Result.isInvalid())
2467 return QualType();
2468 E1 = E1Result.takeAs<Expr>();
2469
2470 // Convert E2 to Composite2
2471 OwningExprResult E2Result
2472 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2473 if (E2Result.isInvalid())
2474 return QualType();
2475 E2 = E2Result.takeAs<Expr>();
2476
2477 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002478}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002479
Anders Carlssondef11992009-05-30 20:36:53 +00002480Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002481 if (!Context.getLangOptions().CPlusPlus)
2482 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Douglas Gregor51326552009-12-24 18:51:59 +00002484 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2485
Ted Kremenek6217b802009-07-29 21:53:49 +00002486 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002487 if (!RT)
2488 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002489
John McCall86ff3082010-02-04 22:26:26 +00002490 // If this is the result of a call expression, our source might
2491 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002492 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2493 QualType Ty = CE->getCallee()->getType();
2494 if (const PointerType *PT = Ty->getAs<PointerType>())
2495 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002496 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2497 Ty = BPT->getPointeeType();
2498
John McCall183700f2009-09-21 23:43:11 +00002499 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002500 if (FTy->getResultType()->isReferenceType())
2501 return Owned(E);
2502 }
John McCall86ff3082010-02-04 22:26:26 +00002503
2504 // That should be enough to guarantee that this type is complete.
2505 // If it has a trivial destructor, we can avoid the extra copy.
2506 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2507 if (RD->hasTrivialDestructor())
2508 return Owned(E);
2509
Mike Stump1eb44332009-09-09 15:08:12 +00002510 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002511 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002512 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002513 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002514 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002515 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002516 CheckDestructorAccess(E->getExprLoc(), Destructor,
2517 PDiag(diag::err_access_dtor_temp)
2518 << E->getType());
2519 }
Anders Carlssondef11992009-05-30 20:36:53 +00002520 // FIXME: Add the temporary to the temporaries vector.
2521 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2522}
2523
Anders Carlsson0ece4912009-12-15 20:51:39 +00002524Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002525 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002527 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2528 assert(ExprTemporaries.size() >= FirstTemporary);
2529 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002530 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002531
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002532 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002533 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002534 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002535 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2536 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002538 return E;
2539}
2540
Douglas Gregor90f93822009-12-22 22:17:25 +00002541Sema::OwningExprResult
2542Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2543 if (SubExpr.isInvalid())
2544 return ExprError();
2545
2546 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2547}
2548
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002549FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2550 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2551 assert(ExprTemporaries.size() >= FirstTemporary);
2552
2553 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2554 CXXTemporary **Temporaries =
2555 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2556
2557 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2558
2559 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2560 ExprTemporaries.end());
2561
2562 return E;
2563}
2564
Mike Stump1eb44332009-09-09 15:08:12 +00002565Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002566Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002567 tok::TokenKind OpKind, TypeTy *&ObjectType,
2568 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002569 // Since this might be a postfix expression, get rid of ParenListExprs.
2570 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002572 Expr *BaseExpr = (Expr*)Base.get();
2573 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002575 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002576 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002577 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002578 // If we have a pointer to a dependent type and are using the -> operator,
2579 // the object type is the type that the pointer points to. We might still
2580 // have enough information about that type to do something useful.
2581 if (OpKind == tok::arrow)
2582 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2583 BaseType = Ptr->getPointeeType();
2584
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002585 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002586 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002587 return move(Base);
2588 }
Mike Stump1eb44332009-09-09 15:08:12 +00002589
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002590 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002591 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002592 // returned, with the original second operand.
2593 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002594 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002595 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002596 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002597 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002598
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002599 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002600 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002601 BaseExpr = (Expr*)Base.get();
2602 if (BaseExpr == NULL)
2603 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002604 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002605 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002606 BaseType = BaseExpr->getType();
2607 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002608 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002609 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002610 for (unsigned i = 0; i < Locations.size(); i++)
2611 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002612 return ExprError();
2613 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002614 }
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Douglas Gregor31658df2009-11-20 19:58:21 +00002616 if (BaseType->isPointerType())
2617 BaseType = BaseType->getPointeeType();
2618 }
Mike Stump1eb44332009-09-09 15:08:12 +00002619
2620 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002621 // vector types or Objective-C interfaces. Just return early and let
2622 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002623 if (!BaseType->isRecordType()) {
2624 // C++ [basic.lookup.classref]p2:
2625 // [...] If the type of the object expression is of pointer to scalar
2626 // type, the unqualified-id is looked up in the context of the complete
2627 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002628 //
2629 // This also indicates that we should be parsing a
2630 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002631 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002632 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002633 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002634 }
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Douglas Gregor03c57052009-11-17 05:17:33 +00002636 // The object type must be complete (or dependent).
2637 if (!BaseType->isDependentType() &&
2638 RequireCompleteType(OpLoc, BaseType,
2639 PDiag(diag::err_incomplete_member_access)))
2640 return ExprError();
2641
Douglas Gregorc68afe22009-09-03 21:38:09 +00002642 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002643 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002644 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002645 // type C (or of pointer to a class type C), the unqualified-id is looked
2646 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002647 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002648 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002649}
2650
Douglas Gregor77549082010-02-24 21:29:12 +00002651Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2652 ExprArg MemExpr) {
2653 Expr *E = (Expr *) MemExpr.get();
2654 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2655 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2656 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002657 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002658
2659 return ActOnCallExpr(/*Scope*/ 0,
2660 move(MemExpr),
2661 /*LPLoc*/ ExpectedLParenLoc,
2662 Sema::MultiExprArg(*this, 0, 0),
2663 /*CommaLocs*/ 0,
2664 /*RPLoc*/ ExpectedLParenLoc);
2665}
Douglas Gregord4dca082010-02-24 18:44:31 +00002666
Douglas Gregorb57fb492010-02-24 22:38:50 +00002667Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2668 SourceLocation OpLoc,
2669 tok::TokenKind OpKind,
2670 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002671 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002672 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002673 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002674 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002675 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002676 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002677
2678 // C++ [expr.pseudo]p2:
2679 // The left-hand side of the dot operator shall be of scalar type. The
2680 // left-hand side of the arrow operator shall be of pointer to scalar type.
2681 // This scalar type is the object type.
2682 Expr *BaseE = (Expr *)Base.get();
2683 QualType ObjectType = BaseE->getType();
2684 if (OpKind == tok::arrow) {
2685 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2686 ObjectType = Ptr->getPointeeType();
2687 } else if (!BaseE->isTypeDependent()) {
2688 // The user wrote "p->" when she probably meant "p."; fix it.
2689 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2690 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002691 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002692 if (isSFINAEContext())
2693 return ExprError();
2694
2695 OpKind = tok::period;
2696 }
2697 }
2698
2699 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2700 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2701 << ObjectType << BaseE->getSourceRange();
2702 return ExprError();
2703 }
2704
2705 // C++ [expr.pseudo]p2:
2706 // [...] The cv-unqualified versions of the object type and of the type
2707 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002708 if (DestructedTypeInfo) {
2709 QualType DestructedType = DestructedTypeInfo->getType();
2710 SourceLocation DestructedTypeStart
2711 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2712 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2713 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2714 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2715 << ObjectType << DestructedType << BaseE->getSourceRange()
2716 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2717
2718 // Recover by setting the destructed type to the object type.
2719 DestructedType = ObjectType;
2720 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2721 DestructedTypeStart);
2722 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2723 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002724 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002725
Douglas Gregorb57fb492010-02-24 22:38:50 +00002726 // C++ [expr.pseudo]p2:
2727 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2728 // form
2729 //
2730 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2731 //
2732 // shall designate the same scalar type.
2733 if (ScopeTypeInfo) {
2734 QualType ScopeType = ScopeTypeInfo->getType();
2735 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2736 !Context.hasSameType(ScopeType, ObjectType)) {
2737
2738 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2739 diag::err_pseudo_dtor_type_mismatch)
2740 << ObjectType << ScopeType << BaseE->getSourceRange()
2741 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2742
2743 ScopeType = QualType();
2744 ScopeTypeInfo = 0;
2745 }
2746 }
2747
2748 OwningExprResult Result
2749 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2750 Base.takeAs<Expr>(),
2751 OpKind == tok::arrow,
2752 OpLoc,
2753 (NestedNameSpecifier *) SS.getScopeRep(),
2754 SS.getRange(),
2755 ScopeTypeInfo,
2756 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002757 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002758 Destructed));
2759
Douglas Gregorb57fb492010-02-24 22:38:50 +00002760 if (HasTrailingLParen)
2761 return move(Result);
2762
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002763 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002764}
2765
2766Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2767 SourceLocation OpLoc,
2768 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002769 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002770 UnqualifiedId &FirstTypeName,
2771 SourceLocation CCLoc,
2772 SourceLocation TildeLoc,
2773 UnqualifiedId &SecondTypeName,
2774 bool HasTrailingLParen) {
2775 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2776 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2777 "Invalid first type name in pseudo-destructor");
2778 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2779 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2780 "Invalid second type name in pseudo-destructor");
2781
2782 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002783
2784 // C++ [expr.pseudo]p2:
2785 // The left-hand side of the dot operator shall be of scalar type. The
2786 // left-hand side of the arrow operator shall be of pointer to scalar type.
2787 // This scalar type is the object type.
2788 QualType ObjectType = BaseE->getType();
2789 if (OpKind == tok::arrow) {
2790 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2791 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002792 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002793 // The user wrote "p->" when she probably meant "p."; fix it.
2794 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002795 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002796 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002797 if (isSFINAEContext())
2798 return ExprError();
2799
2800 OpKind = tok::period;
2801 }
2802 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002803
2804 // Compute the object type that we should use for name lookup purposes. Only
2805 // record types and dependent types matter.
2806 void *ObjectTypePtrForLookup = 0;
2807 if (!SS.isSet()) {
2808 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2809 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2810 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2811 }
Douglas Gregor77549082010-02-24 21:29:12 +00002812
Douglas Gregorb57fb492010-02-24 22:38:50 +00002813 // Convert the name of the type being destructed (following the ~) into a
2814 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002815 QualType DestructedType;
2816 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002817 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002818 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2819 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2820 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002821 S, &SS, true, ObjectTypePtrForLookup);
2822 if (!T &&
2823 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2824 (!SS.isSet() && ObjectType->isDependentType()))) {
2825 // The name of the type being destroyed is a dependent name, and we
2826 // couldn't find anything useful in scope. Just store the identifier and
2827 // it's location, and we'll perform (qualified) name lookup again at
2828 // template instantiation time.
2829 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2830 SecondTypeName.StartLocation);
2831 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002832 Diag(SecondTypeName.StartLocation,
2833 diag::err_pseudo_dtor_destructor_non_type)
2834 << SecondTypeName.Identifier << ObjectType;
2835 if (isSFINAEContext())
2836 return ExprError();
2837
2838 // Recover by assuming we had the right type all along.
2839 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002840 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002841 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002842 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002843 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002844 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002845 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2846 TemplateId->getTemplateArgs(),
2847 TemplateId->NumArgs);
2848 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2849 TemplateId->TemplateNameLoc,
2850 TemplateId->LAngleLoc,
2851 TemplateArgsPtr,
2852 TemplateId->RAngleLoc);
2853 if (T.isInvalid() || !T.get()) {
2854 // Recover by assuming we had the right type all along.
2855 DestructedType = ObjectType;
2856 } else
2857 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002858 }
2859
Douglas Gregorb57fb492010-02-24 22:38:50 +00002860 // If we've performed some kind of recovery, (re-)build the type source
2861 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002862 if (!DestructedType.isNull()) {
2863 if (!DestructedTypeInfo)
2864 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002865 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002866 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2867 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002868
2869 // Convert the name of the scope type (the type prior to '::') into a type.
2870 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002871 QualType ScopeType;
2872 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2873 FirstTypeName.Identifier) {
2874 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2875 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2876 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002877 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002878 if (!T) {
2879 Diag(FirstTypeName.StartLocation,
2880 diag::err_pseudo_dtor_destructor_non_type)
2881 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002882
Douglas Gregorb57fb492010-02-24 22:38:50 +00002883 if (isSFINAEContext())
2884 return ExprError();
2885
2886 // Just drop this type. It's unnecessary anyway.
2887 ScopeType = QualType();
2888 } else
2889 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002890 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002891 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002892 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002893 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2894 TemplateId->getTemplateArgs(),
2895 TemplateId->NumArgs);
2896 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2897 TemplateId->TemplateNameLoc,
2898 TemplateId->LAngleLoc,
2899 TemplateArgsPtr,
2900 TemplateId->RAngleLoc);
2901 if (T.isInvalid() || !T.get()) {
2902 // Recover by dropping this type.
2903 ScopeType = QualType();
2904 } else
2905 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002906 }
2907 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002908
2909 if (!ScopeType.isNull() && !ScopeTypeInfo)
2910 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2911 FirstTypeName.StartLocation);
2912
2913
Douglas Gregorb57fb492010-02-24 22:38:50 +00002914 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002915 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002916 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002917}
2918
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002919CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00002920 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002921 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00002922 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2923 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00002924 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2925
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002926 MemberExpr *ME =
2927 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2928 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002929 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002930 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2931 CXXMemberCallExpr *CE =
2932 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2933 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002934 return CE;
2935}
2936
Anders Carlsson165a0a02009-05-17 18:41:29 +00002937Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2938 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002939 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002940 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002941
Anders Carlsson165a0a02009-05-17 18:41:29 +00002942 return Owned(FullExpr);
2943}