blob: 23d52adf91a1528a04f3932b6ffad2c255c190a8 [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,
32 Scope *S, const CXXScopeSpec &SS,
33 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);
175 // If we found the injected-class-name of a class template, retrieve the
176 // type of that template.
177 // FIXME: We really shouldn't need to do this.
178 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type))
179 if (Record->isInjectedClassName())
180 if (Record->getDescribedClassTemplate())
181 T = Record->getDescribedClassTemplate()
182 ->getInjectedClassNameType(Context);
183
184 if (SearchType.isNull() || SearchType->isDependentType() ||
185 Context.hasSameUnqualifiedType(T, SearchType)) {
186 // We found our type!
187
188 return T.getAsOpaquePtr();
189 }
190 }
191
192 // If the name that we found is a class template name, and it is
193 // the same name as the template name in the last part of the
194 // nested-name-specifier (if present) or the object type, then
195 // this is the destructor for that class.
196 // FIXME: This is a workaround until we get real drafting for core
197 // issue 399, for which there isn't even an obvious direction.
198 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
199 QualType MemberOfType;
200 if (SS.isSet()) {
201 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
202 // Figure out the type of the context, if it has one.
203 if (ClassTemplateSpecializationDecl *Spec
204 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx))
205 MemberOfType = Context.getTypeDeclType(Spec);
206 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
207 if (Record->getDescribedClassTemplate())
208 MemberOfType = Record->getDescribedClassTemplate()
209 ->getInjectedClassNameType(Context);
210 else
211 MemberOfType = Context.getTypeDeclType(Record);
212 }
213 }
214 }
215 if (MemberOfType.isNull())
216 MemberOfType = SearchType;
217
218 if (MemberOfType.isNull())
219 continue;
220
221 // We're referring into a class template specialization. If the
222 // class template we found is the same as the template being
223 // specialized, we found what we are looking for.
224 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
225 if (ClassTemplateSpecializationDecl *Spec
226 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
227 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
228 Template->getCanonicalDecl())
229 return MemberOfType.getAsOpaquePtr();
230 }
231
232 continue;
233 }
234
235 // We're referring to an unresolved class template
236 // specialization. Determine whether we class template we found
237 // is the same as the template being specialized or, if we don't
238 // know which template is being specialized, that it at least
239 // has the same name.
240 if (const TemplateSpecializationType *SpecType
241 = MemberOfType->getAs<TemplateSpecializationType>()) {
242 TemplateName SpecName = SpecType->getTemplateName();
243
244 // The class template we found is the same template being
245 // specialized.
246 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
247 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
248 return MemberOfType.getAsOpaquePtr();
249
250 continue;
251 }
252
253 // The class template we found has the same name as the
254 // (dependent) template name being specialized.
255 if (DependentTemplateName *DepTemplate
256 = SpecName.getAsDependentTemplateName()) {
257 if (DepTemplate->isIdentifier() &&
258 DepTemplate->getIdentifier() == Template->getIdentifier())
259 return MemberOfType.getAsOpaquePtr();
260
261 continue;
262 }
263 }
264 }
265 }
266
267 if (isDependent) {
268 // We didn't find our type, but that's okay: it's dependent
269 // anyway.
270 NestedNameSpecifier *NNS = 0;
271 SourceRange Range;
272 if (SS.isSet()) {
273 NNS = (NestedNameSpecifier *)SS.getScopeRep();
274 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
275 } else {
276 NNS = NestedNameSpecifier::Create(Context, &II);
277 Range = SourceRange(NameLoc);
278 }
279
280 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
281 }
282
283 if (ObjectTypePtr)
284 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
285 << &II;
286 else
287 Diag(NameLoc, diag::err_destructor_class_name);
288
289 return 0;
290}
291
Sebastian Redlc42e1182008-11-11 11:37:55 +0000292/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000293Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000294Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
295 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000296 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000297 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000298
Douglas Gregorf57f2072009-12-23 20:51:04 +0000299 if (isType) {
300 // C++ [expr.typeid]p4:
301 // The top-level cv-qualifiers of the lvalue expression or the type-id
302 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000303 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000304 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000305 QualType T = GetTypeFromParser(TyOrExpr);
306 if (T.isNull())
307 return ExprError();
308
309 // C++ [expr.typeid]p4:
310 // If the type of the type-id is a class type or a reference to a class
311 // type, the class shall be completely-defined.
312 QualType CheckT = T;
313 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
314 CheckT = RefType->getPointeeType();
315
316 if (CheckT->getAs<RecordType>() &&
317 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
318 return ExprError();
319
320 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000321 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000322
Chris Lattner572af492008-11-20 05:51:55 +0000323 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000324 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
325 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000326 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000327 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000328 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000329
330 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
331
Douglas Gregorac7610d2009-06-22 20:57:11 +0000332 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000333 bool isUnevaluatedOperand = true;
334 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000335 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000336 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000337 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000338 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000339 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000340 // [...] If the type of the expression is a class type, the class
341 // shall be completely-defined.
342 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
343 return ExprError();
344
345 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000346 // When typeid is applied to an expression other than an lvalue of a
347 // polymorphic class type [...] [the] expression is an unevaluated
348 // operand. [...]
349 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000350 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000351 }
352
353 // C++ [expr.typeid]p4:
354 // [...] If the type of the type-id is a reference to a possibly
355 // cv-qualified type, the result of the typeid expression refers to a
356 // std::type_info object representing the cv-unqualified referenced
357 // type.
358 if (T.hasQualifiers()) {
359 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
360 E->isLvalue(Context));
361 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000362 }
363 }
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Douglas Gregor2afce722009-11-26 00:44:06 +0000365 // If this is an unevaluated operand, clear out the set of
366 // declaration references we have been computing and eliminate any
367 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000368 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000369 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Sebastian Redlf53597f2009-03-15 17:47:39 +0000372 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
373 TypeInfoType.withConst(),
374 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000375}
376
Steve Naroff1b273c42007-09-16 14:56:35 +0000377/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000378Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000379Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000380 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000382 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
383 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000384}
Chris Lattner50dd2892008-02-26 00:51:44 +0000385
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000386/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
387Action::OwningExprResult
388Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
389 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
390}
391
Chris Lattner50dd2892008-02-26 00:51:44 +0000392/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000393Action::OwningExprResult
394Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000395 Expr *Ex = E.takeAs<Expr>();
396 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
397 return ExprError();
398 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
399}
400
401/// CheckCXXThrowOperand - Validate the operand of a throw.
402bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
403 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000404 // A throw-expression initializes a temporary object, called the exception
405 // object, the type of which is determined by removing any top-level
406 // cv-qualifiers from the static type of the operand of throw and adjusting
407 // the type from "array of T" or "function returning T" to "pointer to T"
408 // or "pointer to function returning T", [...]
409 if (E->getType().hasQualifiers())
410 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
411 E->isLvalue(Context) == Expr::LV_Valid);
412
Sebastian Redl972041f2009-04-27 20:27:31 +0000413 DefaultFunctionArrayConversion(E);
414
415 // If the type of the exception would be an incomplete type or a pointer
416 // to an incomplete type other than (cv) void the program is ill-formed.
417 QualType Ty = E->getType();
418 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000419 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000420 Ty = Ptr->getPointeeType();
421 isPointer = 1;
422 }
423 if (!isPointer || !Ty->isVoidType()) {
424 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000425 PDiag(isPointer ? diag::err_throw_incomplete_ptr
426 : diag::err_throw_incomplete)
427 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000428 return true;
429 }
430
431 // FIXME: Construct a temporary here.
432 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000433}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000434
Sebastian Redlf53597f2009-03-15 17:47:39 +0000435Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000436 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
437 /// is a non-lvalue expression whose value is the address of the object for
438 /// which the function is called.
439
Sebastian Redlf53597f2009-03-15 17:47:39 +0000440 if (!isa<FunctionDecl>(CurContext))
441 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000442
443 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
444 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000445 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000446 MD->getThisType(Context),
447 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000448
Sebastian Redlf53597f2009-03-15 17:47:39 +0000449 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000450}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000451
452/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
453/// Can be interpreted either as function-style casting ("int(x)")
454/// or class type construction ("ClassType(x,y,z)")
455/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000456Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000457Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
458 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000459 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000460 SourceLocation *CommaLocs,
461 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000462 if (!TypeRep)
463 return ExprError();
464
John McCall9d125032010-01-15 18:39:57 +0000465 TypeSourceInfo *TInfo;
466 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
467 if (!TInfo)
468 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000469 unsigned NumExprs = exprs.size();
470 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000471 SourceLocation TyBeginLoc = TypeRange.getBegin();
472 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
473
Sebastian Redlf53597f2009-03-15 17:47:39 +0000474 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000475 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000476 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000477
478 return Owned(CXXUnresolvedConstructExpr::Create(Context,
479 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000480 LParenLoc,
481 Exprs, NumExprs,
482 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000483 }
484
Anders Carlssonbb60a502009-08-27 03:53:50 +0000485 if (Ty->isArrayType())
486 return ExprError(Diag(TyBeginLoc,
487 diag::err_value_init_for_array_type) << FullRange);
488 if (!Ty->isVoidType() &&
489 RequireCompleteType(TyBeginLoc, Ty,
490 PDiag(diag::err_invalid_incomplete_type_use)
491 << FullRange))
492 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000493
Anders Carlssonbb60a502009-08-27 03:53:50 +0000494 if (RequireNonAbstractType(TyBeginLoc, Ty,
495 diag::err_allocation_of_abstract_type))
496 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000497
498
Douglas Gregor506ae412009-01-16 18:33:17 +0000499 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000500 // If the expression list is a single expression, the type conversion
501 // expression is equivalent (in definedness, and if defined in meaning) to the
502 // corresponding cast expression.
503 //
504 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000505 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000506 CXXMethodDecl *Method = 0;
507 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
508 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000509 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000510
511 exprs.release();
512 if (Method) {
513 OwningExprResult CastArg
514 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
515 Kind, Method, Owned(Exprs[0]));
516 if (CastArg.isInvalid())
517 return ExprError();
518
519 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000520 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000521
522 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000523 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000524 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000525 }
526
Ted Kremenek6217b802009-07-29 21:53:49 +0000527 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000528 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000529
Mike Stump1eb44332009-09-09 15:08:12 +0000530 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000531 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000532 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
533 InitializationKind Kind
534 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
535 LParenLoc, RParenLoc)
536 : InitializationKind::CreateValue(TypeRange.getBegin(),
537 LParenLoc, RParenLoc);
538 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
539 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
540 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000541
Eli Friedman6997aae2010-01-31 20:58:15 +0000542 // FIXME: Improve AST representation?
543 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000544 }
545
546 // Fall through to value-initialize an object of class type that
547 // doesn't have a user-declared default constructor.
548 }
549
550 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000551 // If the expression list specifies more than a single value, the type shall
552 // be a class with a suitably declared constructor.
553 //
554 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000555 return ExprError(Diag(CommaLocs[0],
556 diag::err_builtin_func_cast_more_than_one_arg)
557 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000558
559 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000560 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000561 // The expression T(), where T is a simple-type-specifier for a non-array
562 // complete object type or the (possibly cv-qualified) void type, creates an
563 // rvalue of the specified type, which is value-initialized.
564 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000565 exprs.release();
566 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000567}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000568
569
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000570/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
571/// @code new (memory) int[size][4] @endcode
572/// or
573/// @code ::new Foo(23, "hello") @endcode
574/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000575Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000576Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000577 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000578 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000579 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000580 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000581 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000582 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000583 // If the specified type is an array, unwrap it and save the expression.
584 if (D.getNumTypeObjects() > 0 &&
585 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
586 DeclaratorChunk &Chunk = D.getTypeObject(0);
587 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000588 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
589 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000590 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000591 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
592 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000593
594 if (ParenTypeId) {
595 // Can't have dynamic array size when the type-id is in parentheses.
596 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
597 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
598 !NumElts->isIntegerConstantExpr(Context)) {
599 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
600 << NumElts->getSourceRange();
601 return ExprError();
602 }
603 }
604
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000605 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000606 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000607 }
608
Douglas Gregor043cad22009-09-11 00:18:58 +0000609 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000610 if (ArraySize) {
611 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000612 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
613 break;
614
615 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
616 if (Expr *NumElts = (Expr *)Array.NumElts) {
617 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
618 !NumElts->isIntegerConstantExpr(Context)) {
619 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
620 << NumElts->getSourceRange();
621 return ExprError();
622 }
623 }
624 }
625 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000626
John McCalla93c9342009-12-07 02:54:59 +0000627 //FIXME: Store TypeSourceInfo in CXXNew expression.
628 TypeSourceInfo *TInfo = 0;
629 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000630 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000631 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000632
Mike Stump1eb44332009-09-09 15:08:12 +0000633 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000634 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000635 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000636 PlacementRParen,
637 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000638 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000639 D.getSourceRange().getBegin(),
640 D.getSourceRange(),
641 Owned(ArraySize),
642 ConstructorLParen,
643 move(ConstructorArgs),
644 ConstructorRParen);
645}
646
Mike Stump1eb44332009-09-09 15:08:12 +0000647Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000648Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
649 SourceLocation PlacementLParen,
650 MultiExprArg PlacementArgs,
651 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000652 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000653 QualType AllocType,
654 SourceLocation TypeLoc,
655 SourceRange TypeRange,
656 ExprArg ArraySizeE,
657 SourceLocation ConstructorLParen,
658 MultiExprArg ConstructorArgs,
659 SourceLocation ConstructorRParen) {
660 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000661 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000662
Douglas Gregor3433cf72009-05-21 00:00:09 +0000663 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000664
665 // That every array dimension except the first is constant was already
666 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000667
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000668 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
669 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000670 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000671 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000672 QualType SizeType = ArraySize->getType();
673 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000674 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
675 diag::err_array_size_not_integral)
676 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000677 // Let's see if this is a constant < 0. If so, we reject it out of hand.
678 // We don't care about special rules, so we tell the machinery it's not
679 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000680 if (!ArraySize->isValueDependent()) {
681 llvm::APSInt Value;
682 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
683 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000684 llvm::APInt::getNullValue(Value.getBitWidth()),
685 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000686 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
687 diag::err_typecheck_negative_array_size)
688 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000689 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000690 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000691
Eli Friedman73c39ab2009-10-20 08:27:19 +0000692 ImpCastExprToType(ArraySize, Context.getSizeType(),
693 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000694 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000695
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000696 FunctionDecl *OperatorNew = 0;
697 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000698 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
699 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000700
Sebastian Redl28507842009-02-26 14:39:58 +0000701 if (!AllocType->isDependentType() &&
702 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
703 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000704 SourceRange(PlacementLParen, PlacementRParen),
705 UseGlobal, AllocType, ArraySize, PlaceArgs,
706 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000707 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000708 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000709 if (OperatorNew) {
710 // Add default arguments, if any.
711 const FunctionProtoType *Proto =
712 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000713 VariadicCallType CallType =
714 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000715 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
716 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000717 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000718 if (Invalid)
719 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000720
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000721 NumPlaceArgs = AllPlaceArgs.size();
722 if (NumPlaceArgs > 0)
723 PlaceArgs = &AllPlaceArgs[0];
724 }
725
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000726 bool Init = ConstructorLParen.isValid();
727 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000728 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000729 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
730 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000731 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
732
Douglas Gregor99a2e602009-12-16 01:38:02 +0000733 if (!AllocType->isDependentType() &&
734 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
735 // C++0x [expr.new]p15:
736 // A new-expression that creates an object of type T initializes that
737 // object as follows:
738 InitializationKind Kind
739 // - If the new-initializer is omitted, the object is default-
740 // initialized (8.5); if no initialization is performed,
741 // the object has indeterminate value
742 = !Init? InitializationKind::CreateDefault(TypeLoc)
743 // - Otherwise, the new-initializer is interpreted according to the
744 // initialization rules of 8.5 for direct-initialization.
745 : InitializationKind::CreateDirect(TypeLoc,
746 ConstructorLParen,
747 ConstructorRParen);
748
Douglas Gregor99a2e602009-12-16 01:38:02 +0000749 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000750 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000751 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000752 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
753 move(ConstructorArgs));
754 if (FullInit.isInvalid())
755 return ExprError();
756
757 // FullInit is our initializer; walk through it to determine if it's a
758 // constructor call, which CXXNewExpr handles directly.
759 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
760 if (CXXBindTemporaryExpr *Binder
761 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
762 FullInitExpr = Binder->getSubExpr();
763 if (CXXConstructExpr *Construct
764 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
765 Constructor = Construct->getConstructor();
766 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
767 AEnd = Construct->arg_end();
768 A != AEnd; ++A)
769 ConvertedConstructorArgs.push_back(A->Retain());
770 } else {
771 // Take the converted initializer.
772 ConvertedConstructorArgs.push_back(FullInit.release());
773 }
774 } else {
775 // No initialization required.
776 }
777
778 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000779 NumConsArgs = ConvertedConstructorArgs.size();
780 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000781 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000782
Douglas Gregor6d908702010-02-26 05:06:18 +0000783 // Mark the new and delete operators as referenced.
784 if (OperatorNew)
785 MarkDeclarationReferenced(StartLoc, OperatorNew);
786 if (OperatorDelete)
787 MarkDeclarationReferenced(StartLoc, OperatorDelete);
788
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000789 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000790
Sebastian Redlf53597f2009-03-15 17:47:39 +0000791 PlacementArgs.release();
792 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000793 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000794 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
795 PlaceArgs, NumPlaceArgs, ParenTypeId,
796 ArraySize, Constructor, Init,
797 ConsArgs, NumConsArgs, OperatorDelete,
798 ResultType, StartLoc,
799 Init ? ConstructorRParen :
800 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000801}
802
803/// CheckAllocatedType - Checks that a type is suitable as the allocated type
804/// in a new-expression.
805/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000806bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000807 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000808 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
809 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000810 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000811 return Diag(Loc, diag::err_bad_new_type)
812 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000813 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000814 return Diag(Loc, diag::err_bad_new_type)
815 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000816 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000817 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000818 PDiag(diag::err_new_incomplete_type)
819 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000820 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000821 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000822 diag::err_allocation_of_abstract_type))
823 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000824
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000825 return false;
826}
827
Douglas Gregor6d908702010-02-26 05:06:18 +0000828/// \brief Determine whether the given function is a non-placement
829/// deallocation function.
830static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
831 if (FD->isInvalidDecl())
832 return false;
833
834 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
835 return Method->isUsualDeallocationFunction();
836
837 return ((FD->getOverloadedOperator() == OO_Delete ||
838 FD->getOverloadedOperator() == OO_Array_Delete) &&
839 FD->getNumParams() == 1);
840}
841
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000842/// FindAllocationFunctions - Finds the overloads of operator new and delete
843/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000844bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
845 bool UseGlobal, QualType AllocType,
846 bool IsArray, Expr **PlaceArgs,
847 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000848 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000849 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000850 // --- Choosing an allocation function ---
851 // C++ 5.3.4p8 - 14 & 18
852 // 1) If UseGlobal is true, only look in the global scope. Else, also look
853 // in the scope of the allocated class.
854 // 2) If an array size is given, look for operator new[], else look for
855 // operator new.
856 // 3) The first argument is always size_t. Append the arguments from the
857 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000858
859 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
860 // We don't care about the actual value of this argument.
861 // FIXME: Should the Sema create the expression and embed it in the syntax
862 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000863 IntegerLiteral Size(llvm::APInt::getNullValue(
864 Context.Target.getPointerWidth(0)),
865 Context.getSizeType(),
866 SourceLocation());
867 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000868 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
869
Douglas Gregor6d908702010-02-26 05:06:18 +0000870 // C++ [expr.new]p8:
871 // If the allocated type is a non-array type, the allocation
872 // function’s name is operator new and the deallocation function’s
873 // name is operator delete. If the allocated type is an array
874 // type, the allocation function’s name is operator new[] and the
875 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000876 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
877 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000878 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
879 IsArray ? OO_Array_Delete : OO_Delete);
880
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000881 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000882 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000883 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000884 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000885 AllocArgs.size(), Record, /*AllowMissing=*/true,
886 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000887 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000888 }
889 if (!OperatorNew) {
890 // Didn't find a member overload. Look for a global one.
891 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000892 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000893 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000894 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
895 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000896 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000897 }
898
Anders Carlssond9583892009-05-31 20:26:12 +0000899 // FindAllocationOverload can change the passed in arguments, so we need to
900 // copy them back.
901 if (NumPlaceArgs > 0)
902 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Douglas Gregor6d908702010-02-26 05:06:18 +0000904 // C++ [expr.new]p19:
905 //
906 // If the new-expression begins with a unary :: operator, the
907 // deallocation function’s name is looked up in the global
908 // scope. Otherwise, if the allocated type is a class type T or an
909 // array thereof, the deallocation function’s name is looked up in
910 // the scope of T. If this lookup fails to find the name, or if
911 // the allocated type is not a class type or array thereof, the
912 // deallocation function’s name is looked up in the global scope.
913 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
914 if (AllocType->isRecordType() && !UseGlobal) {
915 CXXRecordDecl *RD
916 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
917 LookupQualifiedName(FoundDelete, RD);
918 }
919
920 if (FoundDelete.empty()) {
921 DeclareGlobalNewDelete();
922 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
923 }
924
925 FoundDelete.suppressDiagnostics();
926 llvm::SmallVector<NamedDecl *, 4> Matches;
927 if (NumPlaceArgs > 1) {
928 // C++ [expr.new]p20:
929 // A declaration of a placement deallocation function matches the
930 // declaration of a placement allocation function if it has the
931 // same number of parameters and, after parameter transformations
932 // (8.3.5), all parameter types except the first are
933 // identical. [...]
934 //
935 // To perform this comparison, we compute the function type that
936 // the deallocation function should have, and use that type both
937 // for template argument deduction and for comparison purposes.
938 QualType ExpectedFunctionType;
939 {
940 const FunctionProtoType *Proto
941 = OperatorNew->getType()->getAs<FunctionProtoType>();
942 llvm::SmallVector<QualType, 4> ArgTypes;
943 ArgTypes.push_back(Context.VoidPtrTy);
944 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
945 ArgTypes.push_back(Proto->getArgType(I));
946
947 ExpectedFunctionType
948 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
949 ArgTypes.size(),
950 Proto->isVariadic(),
951 0, false, false, 0, 0, false, CC_Default);
952 }
953
954 for (LookupResult::iterator D = FoundDelete.begin(),
955 DEnd = FoundDelete.end();
956 D != DEnd; ++D) {
957 FunctionDecl *Fn = 0;
958 if (FunctionTemplateDecl *FnTmpl
959 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
960 // Perform template argument deduction to try to match the
961 // expected function type.
962 TemplateDeductionInfo Info(Context, StartLoc);
963 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
964 continue;
965 } else
966 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
967
968 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
969 Matches.push_back(Fn);
970 }
971 } else {
972 // C++ [expr.new]p20:
973 // [...] Any non-placement deallocation function matches a
974 // non-placement allocation function. [...]
975 for (LookupResult::iterator D = FoundDelete.begin(),
976 DEnd = FoundDelete.end();
977 D != DEnd; ++D) {
978 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
979 if (isNonPlacementDeallocationFunction(Fn))
980 Matches.push_back(*D);
981 }
982 }
983
984 // C++ [expr.new]p20:
985 // [...] If the lookup finds a single matching deallocation
986 // function, that function will be called; otherwise, no
987 // deallocation function will be called.
988 if (Matches.size() == 1) {
989 // FIXME: Drops access, using-declaration info!
990 OperatorDelete = cast<FunctionDecl>(Matches[0]->getUnderlyingDecl());
991
992 // C++0x [expr.new]p20:
993 // If the lookup finds the two-parameter form of a usual
994 // deallocation function (3.7.4.2) and that function, considered
995 // as a placement deallocation function, would have been
996 // selected as a match for the allocation function, the program
997 // is ill-formed.
998 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
999 isNonPlacementDeallocationFunction(OperatorDelete)) {
1000 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1001 << SourceRange(PlaceArgs[0]->getLocStart(),
1002 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1003 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1004 << DeleteName;
1005 }
1006 }
1007
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001008 return false;
1009}
1010
Sebastian Redl7f662392008-12-04 22:20:51 +00001011/// FindAllocationOverload - Find an fitting overload for the allocation
1012/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001013bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1014 DeclarationName Name, Expr** Args,
1015 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001016 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001017 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1018 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001019 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001020 if (AllowMissing)
1021 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001022 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001023 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001024 }
1025
John McCallf36e02d2009-10-09 21:13:30 +00001026 // FIXME: handle ambiguity
1027
John McCall5769d612010-02-08 23:07:23 +00001028 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001029 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1030 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001031 // Even member operator new/delete are implicitly treated as
1032 // static, so don't use AddMemberCandidate.
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001033
1034 if (FunctionTemplateDecl *FnTemplate =
1035 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
1036 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
1037 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1038 Candidates,
1039 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001040 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001041 }
1042
1043 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
1044 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
1045 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001046 }
1047
1048 // Do the resolution.
1049 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001050 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001051 case OR_Success: {
1052 // Got one!
1053 FunctionDecl *FnDecl = Best->Function;
1054 // The first argument is size_t, and the first parameter must be size_t,
1055 // too. This is checked on declaration and can be assumed. (It can't be
1056 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001057 // Whatch out for variadic allocator function.
1058 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1059 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +00001060 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +00001061 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001062 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +00001063 return true;
1064 }
1065 Operator = FnDecl;
1066 return false;
1067 }
1068
1069 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001070 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001071 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001072 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001073 return true;
1074
1075 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001076 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001077 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001078 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001079 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001080
1081 case OR_Deleted:
1082 Diag(StartLoc, diag::err_ovl_deleted_call)
1083 << Best->Function->isDeleted()
1084 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001085 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001086 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001087 }
1088 assert(false && "Unreachable, bad result from BestViableFunction");
1089 return true;
1090}
1091
1092
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001093/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1094/// delete. These are:
1095/// @code
1096/// void* operator new(std::size_t) throw(std::bad_alloc);
1097/// void* operator new[](std::size_t) throw(std::bad_alloc);
1098/// void operator delete(void *) throw();
1099/// void operator delete[](void *) throw();
1100/// @endcode
1101/// Note that the placement and nothrow forms of new are *not* implicitly
1102/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001103void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001104 if (GlobalNewDeleteDeclared)
1105 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001106
1107 // C++ [basic.std.dynamic]p2:
1108 // [...] The following allocation and deallocation functions (18.4) are
1109 // implicitly declared in global scope in each translation unit of a
1110 // program
1111 //
1112 // void* operator new(std::size_t) throw(std::bad_alloc);
1113 // void* operator new[](std::size_t) throw(std::bad_alloc);
1114 // void operator delete(void*) throw();
1115 // void operator delete[](void*) throw();
1116 //
1117 // These implicit declarations introduce only the function names operator
1118 // new, operator new[], operator delete, operator delete[].
1119 //
1120 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1121 // "std" or "bad_alloc" as necessary to form the exception specification.
1122 // However, we do not make these implicit declarations visible to name
1123 // lookup.
1124 if (!StdNamespace) {
1125 // The "std" namespace has not yet been defined, so build one implicitly.
1126 StdNamespace = NamespaceDecl::Create(Context,
1127 Context.getTranslationUnitDecl(),
1128 SourceLocation(),
1129 &PP.getIdentifierTable().get("std"));
1130 StdNamespace->setImplicit(true);
1131 }
1132
1133 if (!StdBadAlloc) {
1134 // The "std::bad_alloc" class has not yet been declared, so build it
1135 // implicitly.
1136 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1137 StdNamespace,
1138 SourceLocation(),
1139 &PP.getIdentifierTable().get("bad_alloc"),
1140 SourceLocation(), 0);
1141 StdBadAlloc->setImplicit(true);
1142 }
1143
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001144 GlobalNewDeleteDeclared = true;
1145
1146 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1147 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001148 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001149
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001150 DeclareGlobalAllocationFunction(
1151 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001152 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001153 DeclareGlobalAllocationFunction(
1154 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001155 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001156 DeclareGlobalAllocationFunction(
1157 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1158 Context.VoidTy, VoidPtr);
1159 DeclareGlobalAllocationFunction(
1160 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1161 Context.VoidTy, VoidPtr);
1162}
1163
1164/// DeclareGlobalAllocationFunction - Declares a single implicit global
1165/// allocation function if it doesn't already exist.
1166void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001167 QualType Return, QualType Argument,
1168 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001169 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1170
1171 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001172 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001173 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001174 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001175 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001176 // Only look at non-template functions, as it is the predefined,
1177 // non-templated allocation function we are trying to declare here.
1178 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1179 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001180 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001181 Func->getParamDecl(0)->getType().getUnqualifiedType());
1182 // FIXME: Do we need to check for default arguments here?
1183 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1184 return;
1185 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001186 }
1187 }
1188
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001189 QualType BadAllocType;
1190 bool HasBadAllocExceptionSpec
1191 = (Name.getCXXOverloadedOperator() == OO_New ||
1192 Name.getCXXOverloadedOperator() == OO_Array_New);
1193 if (HasBadAllocExceptionSpec) {
1194 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1195 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1196 }
1197
1198 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1199 true, false,
1200 HasBadAllocExceptionSpec? 1 : 0,
Douglas Gregorce056bc2010-02-21 22:15:06 +00001201 &BadAllocType, false, CC_Default);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001202 FunctionDecl *Alloc =
1203 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +00001204 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001205 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001206
1207 if (AddMallocAttr)
1208 Alloc->addAttr(::new (Context) MallocAttr());
1209
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001210 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001211 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001212 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001213 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001214
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001215 // FIXME: Also add this declaration to the IdentifierResolver, but
1216 // make sure it is at the end of the chain to coincide with the
1217 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001218 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001219}
1220
Anders Carlsson78f74552009-11-15 18:45:20 +00001221bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1222 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001223 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001224 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001225 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001226 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001227
John McCalla24dc2e2009-11-17 02:14:36 +00001228 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001229 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001230
1231 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1232 F != FEnd; ++F) {
1233 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1234 if (Delete->isUsualDeallocationFunction()) {
1235 Operator = Delete;
1236 return false;
1237 }
1238 }
1239
1240 // We did find operator delete/operator delete[] declarations, but
1241 // none of them were suitable.
1242 if (!Found.empty()) {
1243 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1244 << Name << RD;
1245
1246 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1247 F != FEnd; ++F) {
1248 Diag((*F)->getLocation(),
1249 diag::note_delete_member_function_declared_here)
1250 << Name;
1251 }
1252
1253 return true;
1254 }
1255
1256 // Look for a global declaration.
1257 DeclareGlobalNewDelete();
1258 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1259
1260 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1261 Expr* DeallocArgs[1];
1262 DeallocArgs[0] = &Null;
1263 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1264 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1265 Operator))
1266 return true;
1267
1268 assert(Operator && "Did not find a deallocation function!");
1269 return false;
1270}
1271
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001272/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1273/// @code ::delete ptr; @endcode
1274/// or
1275/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001276Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001277Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001278 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001279 // C++ [expr.delete]p1:
1280 // The operand shall have a pointer type, or a class type having a single
1281 // conversion function to a pointer type. The result has type void.
1282 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001283 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1284
Anders Carlssond67c4c32009-08-16 20:29:29 +00001285 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Sebastian Redlf53597f2009-03-15 17:47:39 +00001287 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001288 if (!Ex->isTypeDependent()) {
1289 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001290
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001291 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001292 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +00001293 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00001294 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001295
John McCalleec51cf2010-01-20 00:46:10 +00001296 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001297 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001298 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +00001299 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001300 continue;
1301
John McCallba135432009-11-21 08:51:07 +00001302 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001303
1304 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1305 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1306 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001307 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001308 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001309 if (ObjectPtrConversions.size() == 1) {
1310 // We have a single conversion to a pointer-to-object type. Perform
1311 // that conversion.
1312 Operand.release();
1313 if (!PerformImplicitConversion(Ex,
1314 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001315 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001316 Operand = Owned(Ex);
1317 Type = Ex->getType();
1318 }
1319 }
1320 else if (ObjectPtrConversions.size() > 1) {
1321 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1322 << Type << Ex->getSourceRange();
1323 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1324 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +00001325 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001326 }
1327 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001328 }
Sebastian Redl28507842009-02-26 14:39:58 +00001329 }
1330
Sebastian Redlf53597f2009-03-15 17:47:39 +00001331 if (!Type->isPointerType())
1332 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1333 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001334
Ted Kremenek6217b802009-07-29 21:53:49 +00001335 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001336 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001337 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1338 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001339 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001340 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001341 PDiag(diag::warn_delete_incomplete)
1342 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001343 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001344
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001345 // C++ [expr.delete]p2:
1346 // [Note: a pointer to a const type can be the operand of a
1347 // delete-expression; it is not necessary to cast away the constness
1348 // (5.2.11) of the pointer expression before it is used as the operand
1349 // of the delete-expression. ]
1350 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1351 CastExpr::CK_NoOp);
1352
1353 // Update the operand.
1354 Operand.take();
1355 Operand = ExprArg(*this, Ex);
1356
Anders Carlssond67c4c32009-08-16 20:29:29 +00001357 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1358 ArrayForm ? OO_Array_Delete : OO_Delete);
1359
Anders Carlsson78f74552009-11-15 18:45:20 +00001360 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1361 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1362
1363 if (!UseGlobal &&
1364 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001365 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001366
Anders Carlsson78f74552009-11-15 18:45:20 +00001367 if (!RD->hasTrivialDestructor())
1368 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001369 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001370 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001371 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001372
Anders Carlssond67c4c32009-08-16 20:29:29 +00001373 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001374 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001375 DeclareGlobalNewDelete();
1376 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001377 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001378 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001379 OperatorDelete))
1380 return ExprError();
1381 }
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Sebastian Redl28507842009-02-26 14:39:58 +00001383 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001384 }
1385
Sebastian Redlf53597f2009-03-15 17:47:39 +00001386 Operand.release();
1387 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001388 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001389}
1390
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001391/// \brief Check the use of the given variable as a C++ condition in an if,
1392/// while, do-while, or switch statement.
1393Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1394 QualType T = ConditionVar->getType();
1395
1396 // C++ [stmt.select]p2:
1397 // The declarator shall not specify a function or an array.
1398 if (T->isFunctionType())
1399 return ExprError(Diag(ConditionVar->getLocation(),
1400 diag::err_invalid_use_of_function_type)
1401 << ConditionVar->getSourceRange());
1402 else if (T->isArrayType())
1403 return ExprError(Diag(ConditionVar->getLocation(),
1404 diag::err_invalid_use_of_array_type)
1405 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001406
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001407 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1408 ConditionVar->getLocation(),
1409 ConditionVar->getType().getNonReferenceType()));
1410}
1411
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001412/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1413bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1414 // C++ 6.4p4:
1415 // The value of a condition that is an initialized declaration in a statement
1416 // other than a switch statement is the value of the declared variable
1417 // implicitly converted to type bool. If that conversion is ill-formed, the
1418 // program is ill-formed.
1419 // The value of a condition that is an expression is the value of the
1420 // expression, implicitly converted to bool.
1421 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001422 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001423}
Douglas Gregor77a52232008-09-12 00:47:35 +00001424
1425/// Helper function to determine whether this is the (deprecated) C++
1426/// conversion from a string literal to a pointer to non-const char or
1427/// non-const wchar_t (for narrow and wide string literals,
1428/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001429bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001430Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1431 // Look inside the implicit cast, if it exists.
1432 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1433 From = Cast->getSubExpr();
1434
1435 // A string literal (2.13.4) that is not a wide string literal can
1436 // be converted to an rvalue of type "pointer to char"; a wide
1437 // string literal can be converted to an rvalue of type "pointer
1438 // to wchar_t" (C++ 4.2p2).
1439 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001440 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001441 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001442 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001443 // This conversion is considered only when there is an
1444 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001445 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001446 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1447 (!StrLit->isWide() &&
1448 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1449 ToPointeeType->getKind() == BuiltinType::Char_S))))
1450 return true;
1451 }
1452
1453 return false;
1454}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001455
1456/// PerformImplicitConversion - Perform an implicit conversion of the
1457/// expression From to the type ToType. Returns true if there was an
1458/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001459/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001460/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001461/// explicit user-defined conversions are permitted. @p Elidable should be true
1462/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1463/// resolution works differently in that case.
1464bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001465Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001466 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001467 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001468 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001469 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001470 Elidable, ICS);
1471}
1472
1473bool
1474Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001475 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001476 bool Elidable,
1477 ImplicitConversionSequence& ICS) {
John McCallb1bdc622010-02-25 01:37:24 +00001478 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001479 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001480 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001481 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001482 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001483 /*ForceRValue=*/true,
1484 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001485 }
John McCall1d318332010-01-12 00:44:57 +00001486 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001487 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001488 /*SuppressUserConversions=*/false,
1489 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001490 /*ForceRValue=*/false,
1491 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001492 }
Douglas Gregor68647482009-12-16 03:45:30 +00001493 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001494}
1495
1496/// PerformImplicitConversion - Perform an implicit conversion of the
1497/// expression From to the type ToType using the pre-computed implicit
1498/// conversion sequence ICS. Returns true if there was an error, false
1499/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001500/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001501/// used in the error message.
1502bool
1503Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1504 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001505 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001506 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001507 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001508 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001509 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001510 return true;
1511 break;
1512
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001513 case ImplicitConversionSequence::UserDefinedConversion: {
1514
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001515 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1516 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001517 QualType BeforeToType;
1518 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001519 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001520
1521 // If the user-defined conversion is specified by a conversion function,
1522 // the initial standard conversion sequence converts the source type to
1523 // the implicit object parameter of the conversion function.
1524 BeforeToType = Context.getTagDeclType(Conv->getParent());
1525 } else if (const CXXConstructorDecl *Ctor =
1526 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001527 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001528 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001529 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001530 // If the user-defined conversion is specified by a constructor, the
1531 // initial standard conversion sequence converts the source type to the
1532 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001533 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1534 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001535 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001536 else
1537 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001538 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001539 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001540 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001541 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001542 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001543 return true;
1544 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001545
Anders Carlsson0aebc812009-09-09 21:33:21 +00001546 OwningExprResult CastArg
1547 = BuildCXXCastArgument(From->getLocStart(),
1548 ToType.getNonReferenceType(),
1549 CastKind, cast<CXXMethodDecl>(FD),
1550 Owned(From));
1551
1552 if (CastArg.isInvalid())
1553 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001554
1555 From = CastArg.takeAs<Expr>();
1556
Eli Friedmand8889622009-11-27 04:41:50 +00001557 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001558 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001559 }
John McCall1d318332010-01-12 00:44:57 +00001560
1561 case ImplicitConversionSequence::AmbiguousConversion:
1562 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1563 PDiag(diag::err_typecheck_ambiguous_condition)
1564 << From->getSourceRange());
1565 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001566
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001567 case ImplicitConversionSequence::EllipsisConversion:
1568 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001569 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001570
1571 case ImplicitConversionSequence::BadConversion:
1572 return true;
1573 }
1574
1575 // Everything went well.
1576 return false;
1577}
1578
1579/// PerformImplicitConversion - Perform an implicit conversion of the
1580/// expression From to the type ToType by following the standard
1581/// conversion sequence SCS. Returns true if there was an error, false
1582/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001583/// expression. Flavor is the context in which we're performing this
1584/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001585bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001586Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001587 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001588 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001589 // Overall FIXME: we are recomputing too many types here and doing far too
1590 // much extra work. What this means is that we need to keep track of more
1591 // information that is computed when we try the implicit conversion initially,
1592 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001593 QualType FromType = From->getType();
1594
Douglas Gregor225c41e2008-11-03 19:09:14 +00001595 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001596 // FIXME: When can ToType be a reference type?
1597 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001598 if (SCS.Second == ICK_Derived_To_Base) {
1599 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1600 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1601 MultiExprArg(*this, (void **)&From, 1),
1602 /*FIXME:ConstructLoc*/SourceLocation(),
1603 ConstructorArgs))
1604 return true;
1605 OwningExprResult FromResult =
1606 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1607 ToType, SCS.CopyConstructor,
1608 move_arg(ConstructorArgs));
1609 if (FromResult.isInvalid())
1610 return true;
1611 From = FromResult.takeAs<Expr>();
1612 return false;
1613 }
Mike Stump1eb44332009-09-09 15:08:12 +00001614 OwningExprResult FromResult =
1615 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1616 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001617 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001619 if (FromResult.isInvalid())
1620 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001622 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001623 return false;
1624 }
1625
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001626 // Perform the first implicit conversion.
1627 switch (SCS.First) {
1628 case ICK_Identity:
1629 case ICK_Lvalue_To_Rvalue:
1630 // Nothing to do.
1631 break;
1632
1633 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001634 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001635 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001636 break;
1637
1638 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001639 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001640 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1641 if (!Fn)
1642 return true;
1643
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001644 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1645 return true;
1646
Anders Carlsson96ad5332009-10-21 17:16:23 +00001647 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001648 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001649
Sebastian Redl759986e2009-10-17 20:50:27 +00001650 // If there's already an address-of operator in the expression, we have
1651 // the right type already, and the code below would just introduce an
1652 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001653 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001654 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001655 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001656 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001657 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001658 break;
1659
1660 default:
1661 assert(false && "Improper first standard conversion");
1662 break;
1663 }
1664
1665 // Perform the second implicit conversion
1666 switch (SCS.Second) {
1667 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001668 // If both sides are functions (or pointers/references to them), there could
1669 // be incompatible exception declarations.
1670 if (CheckExceptionSpecCompatibility(From, ToType))
1671 return true;
1672 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001673 break;
1674
Douglas Gregor43c79c22009-12-09 00:47:37 +00001675 case ICK_NoReturn_Adjustment:
1676 // If both sides are functions (or pointers/references to them), there could
1677 // be incompatible exception declarations.
1678 if (CheckExceptionSpecCompatibility(From, ToType))
1679 return true;
1680
1681 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1682 CastExpr::CK_NoOp);
1683 break;
1684
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001685 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001686 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001687 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1688 break;
1689
1690 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001691 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001692 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1693 break;
1694
1695 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001696 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001697 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1698 break;
1699
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001700 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001701 if (ToType->isFloatingType())
1702 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1703 else
1704 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1705 break;
1706
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001707 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001708 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1709 break;
1710
Douglas Gregorf9201e02009-02-11 23:02:49 +00001711 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001712 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001713 break;
1714
Anders Carlsson61faec12009-09-12 04:46:44 +00001715 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001716 if (SCS.IncompatibleObjC) {
1717 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001718 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001719 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001720 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001721 << From->getSourceRange();
1722 }
1723
Anders Carlsson61faec12009-09-12 04:46:44 +00001724
1725 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001726 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001727 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001728 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001729 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001730 }
1731
1732 case ICK_Pointer_Member: {
1733 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001734 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001735 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001736 if (CheckExceptionSpecCompatibility(From, ToType))
1737 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001738 ImpCastExprToType(From, ToType, Kind);
1739 break;
1740 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001741 case ICK_Boolean_Conversion: {
1742 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1743 if (FromType->isMemberPointerType())
1744 Kind = CastExpr::CK_MemberPointerToBoolean;
1745
1746 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001747 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001748 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001749
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001750 case ICK_Derived_To_Base:
1751 if (CheckDerivedToBaseConversion(From->getType(),
1752 ToType.getNonReferenceType(),
1753 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001754 From->getSourceRange(),
1755 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001756 return true;
1757 ImpCastExprToType(From, ToType.getNonReferenceType(),
1758 CastExpr::CK_DerivedToBase);
1759 break;
1760
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001761 default:
1762 assert(false && "Improper second standard conversion");
1763 break;
1764 }
1765
1766 switch (SCS.Third) {
1767 case ICK_Identity:
1768 // Nothing to do.
1769 break;
1770
1771 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001772 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1773 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001774 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001775 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001776 ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001777
1778 if (SCS.DeprecatedStringLiteralToCharPtr)
1779 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1780 << ToType.getNonReferenceType();
1781
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001782 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001783
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001784 default:
1785 assert(false && "Improper second standard conversion");
1786 break;
1787 }
1788
1789 return false;
1790}
1791
Sebastian Redl64b45f72009-01-05 20:52:13 +00001792Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1793 SourceLocation KWLoc,
1794 SourceLocation LParen,
1795 TypeTy *Ty,
1796 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001797 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001799 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1800 // all traits except __is_class, __is_enum and __is_union require a the type
1801 // to be complete.
1802 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001803 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001804 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001805 return ExprError();
1806 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001807
1808 // There is no point in eagerly computing the value. The traits are designed
1809 // to be used from type trait templates, so Ty will be a template parameter
1810 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001811 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1812 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001813}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001814
1815QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001816 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001817 const char *OpSpelling = isIndirect ? "->*" : ".*";
1818 // C++ 5.5p2
1819 // The binary operator .* [p3: ->*] binds its second operand, which shall
1820 // be of type "pointer to member of T" (where T is a completely-defined
1821 // class type) [...]
1822 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001823 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001824 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001825 Diag(Loc, diag::err_bad_memptr_rhs)
1826 << OpSpelling << RType << rex->getSourceRange();
1827 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001828 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001829
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001830 QualType Class(MemPtr->getClass(), 0);
1831
1832 // C++ 5.5p2
1833 // [...] to its first operand, which shall be of class T or of a class of
1834 // which T is an unambiguous and accessible base class. [p3: a pointer to
1835 // such a class]
1836 QualType LType = lex->getType();
1837 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001838 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001839 LType = Ptr->getPointeeType().getNonReferenceType();
1840 else {
1841 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001842 << OpSpelling << 1 << LType
1843 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001844 return QualType();
1845 }
1846 }
1847
Douglas Gregora4923eb2009-11-16 21:35:15 +00001848 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001849 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1850 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001851 // FIXME: Would it be useful to print full ambiguity paths, or is that
1852 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001853 if (!IsDerivedFrom(LType, Class, Paths) ||
1854 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1855 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001856 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001857 return QualType();
1858 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001859 // Cast LHS to type of use.
1860 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1861 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1862 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001863 }
1864
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001865 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001866 // Diagnose use of pointer-to-member type which when used as
1867 // the functional cast in a pointer-to-member expression.
1868 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1869 return QualType();
1870 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001871 // C++ 5.5p2
1872 // The result is an object or a function of the type specified by the
1873 // second operand.
1874 // The cv qualifiers are the union of those in the pointer and the left side,
1875 // in accordance with 5.5p5 and 5.2.5.
1876 // FIXME: This returns a dereferenced member function pointer as a normal
1877 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001878 // calling them. There's also a GCC extension to get a function pointer to the
1879 // thing, which is another complication, because this type - unlike the type
1880 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001881 // argument.
1882 // We probably need a "MemberFunctionClosureType" or something like that.
1883 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001884 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001885 return Result;
1886}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001887
1888/// \brief Get the target type of a standard or user-defined conversion.
1889static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001890 switch (ICS.getKind()) {
1891 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001892 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001893 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001894 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001895 case ImplicitConversionSequence::AmbiguousConversion:
1896 return ICS.Ambiguous.getToType();
John McCallb1bdc622010-02-25 01:37:24 +00001897
John McCall1d318332010-01-12 00:44:57 +00001898 case ImplicitConversionSequence::EllipsisConversion:
1899 case ImplicitConversionSequence::BadConversion:
1900 llvm_unreachable("function not valid for ellipsis or bad conversions");
1901 }
1902 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001903}
1904
1905/// \brief Try to convert a type to another according to C++0x 5.16p3.
1906///
1907/// This is part of the parameter validation for the ? operator. If either
1908/// value operand is a class type, the two operands are attempted to be
1909/// converted to each other. This function does the conversion in one direction.
1910/// It emits a diagnostic and returns true only if it finds an ambiguous
1911/// conversion.
1912static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1913 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001914 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001915 // C++0x 5.16p3
1916 // The process for determining whether an operand expression E1 of type T1
1917 // can be converted to match an operand expression E2 of type T2 is defined
1918 // as follows:
1919 // -- If E2 is an lvalue:
1920 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1921 // E1 can be converted to match E2 if E1 can be implicitly converted to
1922 // type "lvalue reference to T2", subject to the constraint that in the
1923 // conversion the reference must bind directly to E1.
1924 if (!Self.CheckReferenceInit(From,
1925 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001926 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001927 /*SuppressUserConversions=*/false,
1928 /*AllowExplicit=*/false,
1929 /*ForceRValue=*/false,
1930 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001931 {
John McCall1d318332010-01-12 00:44:57 +00001932 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001933 "expected a definite conversion");
1934 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001935 ICS.isStandard() ? ICS.Standard.DirectBinding
1936 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001937 if (DirectBinding)
1938 return false;
1939 }
1940 }
John McCallb1bdc622010-02-25 01:37:24 +00001941
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001942 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1943 // -- if E1 and E2 have class type, and the underlying class types are
1944 // the same or one is a base class of the other:
1945 QualType FTy = From->getType();
1946 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001947 const RecordType *FRec = FTy->getAs<RecordType>();
1948 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001949 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1950 if (FRec && TRec && (FRec == TRec ||
1951 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1952 // E1 can be converted to match E2 if the class of T2 is the
1953 // same type as, or a base class of, the class of T1, and
1954 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00001955 if (FRec == TRec || FDerivedFromT) {
1956 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
1957 // Could still fail if there's no copy constructor.
1958 // FIXME: Is this a hard error then, or just a conversion failure? The
1959 // standard doesn't say.
1960 ICS = Self.TryCopyInitialization(From, TTy,
1961 /*SuppressUserConversions=*/false,
1962 /*ForceRValue=*/false,
1963 /*InOverloadResolution=*/false);
1964 } else {
1965 ICS.setBad(BadConversionSequence::bad_qualifiers, From, TTy);
1966 }
1967 } else {
1968 // Can't implicitly convert FTy to a derived class TTy.
1969 // TODO: more specific error for this.
1970 ICS.setBad(BadConversionSequence::no_conversion, From, TTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001971 }
1972 } else {
1973 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1974 // implicitly converted to the type that expression E2 would have
1975 // if E2 were converted to an rvalue.
1976 // First find the decayed type.
1977 if (TTy->isFunctionType())
1978 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001979 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001980 TTy = Self.Context.getArrayDecayedType(TTy);
1981
1982 // Now try the implicit conversion.
1983 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001984 ICS = Self.TryImplicitConversion(From, TTy,
1985 /*SuppressUserConversions=*/false,
1986 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001987 /*ForceRValue=*/false,
1988 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001989 }
1990 return false;
1991}
1992
1993/// \brief Try to find a common type for two according to C++0x 5.16p5.
1994///
1995/// This is part of the parameter validation for the ? operator. If either
1996/// value operand is a class type, overload resolution is used to find a
1997/// conversion to a common type.
1998static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1999 SourceLocation Loc) {
2000 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002001 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002002 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002003
2004 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002005 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002006 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002007 // We found a match. Perform the conversions on the arguments and move on.
2008 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002009 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002010 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002011 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002012 break;
2013 return false;
2014
Douglas Gregor20093b42009-12-09 23:02:17 +00002015 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002016 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2017 << LHS->getType() << RHS->getType()
2018 << LHS->getSourceRange() << RHS->getSourceRange();
2019 return true;
2020
Douglas Gregor20093b42009-12-09 23:02:17 +00002021 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002022 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2023 << LHS->getType() << RHS->getType()
2024 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002025 // FIXME: Print the possible common types by printing the return types of
2026 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002027 break;
2028
Douglas Gregor20093b42009-12-09 23:02:17 +00002029 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002030 assert(false && "Conditional operator has only built-in overloads");
2031 break;
2032 }
2033 return true;
2034}
2035
Sebastian Redl76458502009-04-17 16:30:52 +00002036/// \brief Perform an "extended" implicit conversion as returned by
2037/// TryClassUnification.
2038///
2039/// TryClassUnification generates ICSs that include reference bindings.
2040/// PerformImplicitConversion is not suitable for this; it chokes if the
2041/// second part of a standard conversion is ICK_DerivedToBase. This function
2042/// handles the reference binding specially.
2043static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00002044 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00002045 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00002046 assert(ICS.Standard.DirectBinding &&
2047 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00002048 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
2049 // redoing all the work.
2050 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002051 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00002052 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002053 /*SuppressUserConversions=*/false,
2054 /*AllowExplicit=*/false,
2055 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00002056 }
John McCall1d318332010-01-12 00:44:57 +00002057 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00002058 assert(ICS.UserDefined.After.DirectBinding &&
2059 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00002060 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002061 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00002062 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002063 /*SuppressUserConversions=*/false,
2064 /*AllowExplicit=*/false,
2065 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00002066 }
Douglas Gregor68647482009-12-16 03:45:30 +00002067 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00002068 return true;
2069 return false;
2070}
2071
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002072/// \brief Check the operands of ?: under C++ semantics.
2073///
2074/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2075/// extension. In this case, LHS == Cond. (But they're not aliases.)
2076QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2077 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002078 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2079 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002080
2081 // C++0x 5.16p1
2082 // The first expression is contextually converted to bool.
2083 if (!Cond->isTypeDependent()) {
2084 if (CheckCXXBooleanCondition(Cond))
2085 return QualType();
2086 }
2087
2088 // Either of the arguments dependent?
2089 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2090 return Context.DependentTy;
2091
John McCallb13c87f2009-11-05 09:23:39 +00002092 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
2093
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002094 // C++0x 5.16p2
2095 // If either the second or the third operand has type (cv) void, ...
2096 QualType LTy = LHS->getType();
2097 QualType RTy = RHS->getType();
2098 bool LVoid = LTy->isVoidType();
2099 bool RVoid = RTy->isVoidType();
2100 if (LVoid || RVoid) {
2101 // ... then the [l2r] conversions are performed on the second and third
2102 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002103 DefaultFunctionArrayLvalueConversion(LHS);
2104 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002105 LTy = LHS->getType();
2106 RTy = RHS->getType();
2107
2108 // ... and one of the following shall hold:
2109 // -- The second or the third operand (but not both) is a throw-
2110 // expression; the result is of the type of the other and is an rvalue.
2111 bool LThrow = isa<CXXThrowExpr>(LHS);
2112 bool RThrow = isa<CXXThrowExpr>(RHS);
2113 if (LThrow && !RThrow)
2114 return RTy;
2115 if (RThrow && !LThrow)
2116 return LTy;
2117
2118 // -- Both the second and third operands have type void; the result is of
2119 // type void and is an rvalue.
2120 if (LVoid && RVoid)
2121 return Context.VoidTy;
2122
2123 // Neither holds, error.
2124 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2125 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2126 << LHS->getSourceRange() << RHS->getSourceRange();
2127 return QualType();
2128 }
2129
2130 // Neither is void.
2131
2132 // C++0x 5.16p3
2133 // Otherwise, if the second and third operand have different types, and
2134 // either has (cv) class type, and attempt is made to convert each of those
2135 // operands to the other.
2136 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
2137 (LTy->isRecordType() || RTy->isRecordType())) {
2138 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2139 // These return true if a single direction is already ambiguous.
2140 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
2141 return QualType();
2142 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
2143 return QualType();
2144
John McCall1d318332010-01-12 00:44:57 +00002145 bool HaveL2R = !ICSLeftToRight.isBad();
2146 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002147 // If both can be converted, [...] the program is ill-formed.
2148 if (HaveL2R && HaveR2L) {
2149 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2150 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2151 return QualType();
2152 }
2153
2154 // If exactly one conversion is possible, that conversion is applied to
2155 // the chosen operand and the converted operands are used in place of the
2156 // original operands for the remainder of this section.
2157 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00002158 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002159 return QualType();
2160 LTy = LHS->getType();
2161 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00002162 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002163 return QualType();
2164 RTy = RHS->getType();
2165 }
2166 }
2167
2168 // C++0x 5.16p4
2169 // If the second and third operands are lvalues and have the same type,
2170 // the result is of that type [...]
2171 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
2172 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2173 RHS->isLvalue(Context) == Expr::LV_Valid)
2174 return LTy;
2175
2176 // C++0x 5.16p5
2177 // Otherwise, the result is an rvalue. If the second and third operands
2178 // do not have the same type, and either has (cv) class type, ...
2179 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2180 // ... overload resolution is used to determine the conversions (if any)
2181 // to be applied to the operands. If the overload resolution fails, the
2182 // program is ill-formed.
2183 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2184 return QualType();
2185 }
2186
2187 // C++0x 5.16p6
2188 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2189 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002190 DefaultFunctionArrayLvalueConversion(LHS);
2191 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002192 LTy = LHS->getType();
2193 RTy = RHS->getType();
2194
2195 // After those conversions, one of the following shall hold:
2196 // -- The second and third operands have the same type; the result
2197 // is of that type.
2198 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2199 return LTy;
2200
2201 // -- The second and third operands have arithmetic or enumeration type;
2202 // the usual arithmetic conversions are performed to bring them to a
2203 // common type, and the result is of that type.
2204 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2205 UsualArithmeticConversions(LHS, RHS);
2206 return LHS->getType();
2207 }
2208
2209 // -- The second and third operands have pointer type, or one has pointer
2210 // type and the other is a null pointer constant; pointer conversions
2211 // and qualification conversions are performed to bring them to their
2212 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002213 // -- The second and third operands have pointer to member type, or one has
2214 // pointer to member type and the other is a null pointer constant;
2215 // pointer to member conversions and qualification conversions are
2216 // performed to bring them to a common type, whose cv-qualification
2217 // shall match the cv-qualification of either the second or the third
2218 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002219 bool NonStandardCompositeType = false;
2220 QualType Composite = FindCompositePointerType(LHS, RHS,
2221 isSFINAEContext()? 0 : &NonStandardCompositeType);
2222 if (!Composite.isNull()) {
2223 if (NonStandardCompositeType)
2224 Diag(QuestionLoc,
2225 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2226 << LTy << RTy << Composite
2227 << LHS->getSourceRange() << RHS->getSourceRange();
2228
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002229 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002230 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002231
2232 // Similarly, attempt to find composite type of twp objective-c pointers.
2233 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2234 if (!Composite.isNull())
2235 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002236
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002237 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2238 << LHS->getType() << RHS->getType()
2239 << LHS->getSourceRange() << RHS->getSourceRange();
2240 return QualType();
2241}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002242
2243/// \brief Find a merged pointer type and convert the two expressions to it.
2244///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002245/// This finds the composite pointer type (or member pointer type) for @p E1
2246/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2247/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002248/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002249///
2250/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2251/// a non-standard (but still sane) composite type to which both expressions
2252/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2253/// will be set true.
2254QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2,
2255 bool *NonStandardCompositeType) {
2256 if (NonStandardCompositeType)
2257 *NonStandardCompositeType = false;
2258
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002259 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2260 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002262 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2263 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002264 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002265
2266 // C++0x 5.9p2
2267 // Pointer conversions and qualification conversions are performed on
2268 // pointer operands to bring them to their composite pointer type. If
2269 // one operand is a null pointer constant, the composite pointer type is
2270 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002271 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002272 if (T2->isMemberPointerType())
2273 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2274 else
2275 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002276 return T2;
2277 }
Douglas Gregorce940492009-09-25 04:25:58 +00002278 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002279 if (T1->isMemberPointerType())
2280 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2281 else
2282 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002283 return T1;
2284 }
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Douglas Gregor20b3e992009-08-24 17:42:35 +00002286 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002287 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2288 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002289 return QualType();
2290
2291 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2292 // the other has type "pointer to cv2 T" and the composite pointer type is
2293 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2294 // Otherwise, the composite pointer type is a pointer type similar to the
2295 // type of one of the operands, with a cv-qualification signature that is
2296 // the union of the cv-qualification signatures of the operand types.
2297 // In practice, the first part here is redundant; it's subsumed by the second.
2298 // What we do here is, we build the two possible composite types, and try the
2299 // conversions in both directions. If only one works, or if the two composite
2300 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002301 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002302 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2303 QualifierVector QualifierUnion;
2304 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2305 ContainingClassVector;
2306 ContainingClassVector MemberOfClass;
2307 QualType Composite1 = Context.getCanonicalType(T1),
2308 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002309 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002310 do {
2311 const PointerType *Ptr1, *Ptr2;
2312 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2313 (Ptr2 = Composite2->getAs<PointerType>())) {
2314 Composite1 = Ptr1->getPointeeType();
2315 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002316
2317 // If we're allowed to create a non-standard composite type, keep track
2318 // of where we need to fill in additional 'const' qualifiers.
2319 if (NonStandardCompositeType &&
2320 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2321 NeedConstBefore = QualifierUnion.size();
2322
Douglas Gregor20b3e992009-08-24 17:42:35 +00002323 QualifierUnion.push_back(
2324 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2325 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2326 continue;
2327 }
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Douglas Gregor20b3e992009-08-24 17:42:35 +00002329 const MemberPointerType *MemPtr1, *MemPtr2;
2330 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2331 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2332 Composite1 = MemPtr1->getPointeeType();
2333 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002334
2335 // If we're allowed to create a non-standard composite type, keep track
2336 // of where we need to fill in additional 'const' qualifiers.
2337 if (NonStandardCompositeType &&
2338 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2339 NeedConstBefore = QualifierUnion.size();
2340
Douglas Gregor20b3e992009-08-24 17:42:35 +00002341 QualifierUnion.push_back(
2342 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2343 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2344 MemPtr2->getClass()));
2345 continue;
2346 }
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregor20b3e992009-08-24 17:42:35 +00002348 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Douglas Gregor20b3e992009-08-24 17:42:35 +00002350 // Cannot unwrap any more types.
2351 break;
2352 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002354 if (NeedConstBefore && NonStandardCompositeType) {
2355 // Extension: Add 'const' to qualifiers that come before the first qualifier
2356 // mismatch, so that our (non-standard!) composite type meets the
2357 // requirements of C++ [conv.qual]p4 bullet 3.
2358 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2359 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2360 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2361 *NonStandardCompositeType = true;
2362 }
2363 }
2364 }
2365
Douglas Gregor20b3e992009-08-24 17:42:35 +00002366 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002367 ContainingClassVector::reverse_iterator MOC
2368 = MemberOfClass.rbegin();
2369 for (QualifierVector::reverse_iterator
2370 I = QualifierUnion.rbegin(),
2371 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002372 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002373 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002374 if (MOC->first && MOC->second) {
2375 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002376 Composite1 = Context.getMemberPointerType(
2377 Context.getQualifiedType(Composite1, Quals),
2378 MOC->first);
2379 Composite2 = Context.getMemberPointerType(
2380 Context.getQualifiedType(Composite2, Quals),
2381 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002382 } else {
2383 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002384 Composite1
2385 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2386 Composite2
2387 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002388 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002389 }
2390
Mike Stump1eb44332009-09-09 15:08:12 +00002391 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002392 TryImplicitConversion(E1, Composite1,
2393 /*SuppressUserConversions=*/false,
2394 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002395 /*ForceRValue=*/false,
2396 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002397 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002398 TryImplicitConversion(E2, Composite1,
2399 /*SuppressUserConversions=*/false,
2400 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002401 /*ForceRValue=*/false,
2402 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002403
John McCallb1bdc622010-02-25 01:37:24 +00002404 bool ToC2Viable = false;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002405 ImplicitConversionSequence E1ToC2, E2ToC2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002406 if (Context.getCanonicalType(Composite1) !=
2407 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002408 E1ToC2 = TryImplicitConversion(E1, Composite2,
2409 /*SuppressUserConversions=*/false,
2410 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002411 /*ForceRValue=*/false,
2412 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002413 E2ToC2 = TryImplicitConversion(E2, Composite2,
2414 /*SuppressUserConversions=*/false,
2415 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002416 /*ForceRValue=*/false,
2417 /*InOverloadResolution=*/false);
John McCallb1bdc622010-02-25 01:37:24 +00002418 ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002419 }
2420
John McCall1d318332010-01-12 00:44:57 +00002421 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002422 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002423 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2424 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002425 return Composite1;
2426 }
2427 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002428 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2429 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002430 return Composite2;
2431 }
2432 return QualType();
2433}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002434
Anders Carlssondef11992009-05-30 20:36:53 +00002435Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002436 if (!Context.getLangOptions().CPlusPlus)
2437 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002438
Douglas Gregor51326552009-12-24 18:51:59 +00002439 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2440
Ted Kremenek6217b802009-07-29 21:53:49 +00002441 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002442 if (!RT)
2443 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002444
John McCall86ff3082010-02-04 22:26:26 +00002445 // If this is the result of a call expression, our source might
2446 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002447 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2448 QualType Ty = CE->getCallee()->getType();
2449 if (const PointerType *PT = Ty->getAs<PointerType>())
2450 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002451 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2452 Ty = BPT->getPointeeType();
2453
John McCall183700f2009-09-21 23:43:11 +00002454 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002455 if (FTy->getResultType()->isReferenceType())
2456 return Owned(E);
2457 }
John McCall86ff3082010-02-04 22:26:26 +00002458
2459 // That should be enough to guarantee that this type is complete.
2460 // If it has a trivial destructor, we can avoid the extra copy.
2461 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2462 if (RD->hasTrivialDestructor())
2463 return Owned(E);
2464
Mike Stump1eb44332009-09-09 15:08:12 +00002465 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002466 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002467 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002468 if (CXXDestructorDecl *Destructor =
2469 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2470 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002471 // FIXME: Add the temporary to the temporaries vector.
2472 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2473}
2474
Anders Carlsson0ece4912009-12-15 20:51:39 +00002475Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002476 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002478 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2479 assert(ExprTemporaries.size() >= FirstTemporary);
2480 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002481 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002483 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002484 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002485 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002486 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2487 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002489 return E;
2490}
2491
Douglas Gregor90f93822009-12-22 22:17:25 +00002492Sema::OwningExprResult
2493Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2494 if (SubExpr.isInvalid())
2495 return ExprError();
2496
2497 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2498}
2499
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002500FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2501 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2502 assert(ExprTemporaries.size() >= FirstTemporary);
2503
2504 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2505 CXXTemporary **Temporaries =
2506 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2507
2508 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2509
2510 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2511 ExprTemporaries.end());
2512
2513 return E;
2514}
2515
Mike Stump1eb44332009-09-09 15:08:12 +00002516Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002517Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002518 tok::TokenKind OpKind, TypeTy *&ObjectType,
2519 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002520 // Since this might be a postfix expression, get rid of ParenListExprs.
2521 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002523 Expr *BaseExpr = (Expr*)Base.get();
2524 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002525
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002526 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002527 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002528 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002529 // If we have a pointer to a dependent type and are using the -> operator,
2530 // the object type is the type that the pointer points to. We might still
2531 // have enough information about that type to do something useful.
2532 if (OpKind == tok::arrow)
2533 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2534 BaseType = Ptr->getPointeeType();
2535
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002536 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002537 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002538 return move(Base);
2539 }
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002541 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002542 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002543 // returned, with the original second operand.
2544 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002545 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002546 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002547 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002548 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002549
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002550 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002551 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002552 BaseExpr = (Expr*)Base.get();
2553 if (BaseExpr == NULL)
2554 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002555 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002556 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002557 BaseType = BaseExpr->getType();
2558 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002559 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002560 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002561 for (unsigned i = 0; i < Locations.size(); i++)
2562 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002563 return ExprError();
2564 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002565 }
Mike Stump1eb44332009-09-09 15:08:12 +00002566
Douglas Gregor31658df2009-11-20 19:58:21 +00002567 if (BaseType->isPointerType())
2568 BaseType = BaseType->getPointeeType();
2569 }
Mike Stump1eb44332009-09-09 15:08:12 +00002570
2571 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002572 // vector types or Objective-C interfaces. Just return early and let
2573 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002574 if (!BaseType->isRecordType()) {
2575 // C++ [basic.lookup.classref]p2:
2576 // [...] If the type of the object expression is of pointer to scalar
2577 // type, the unqualified-id is looked up in the context of the complete
2578 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002579 //
2580 // This also indicates that we should be parsing a
2581 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002582 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002583 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002584 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Douglas Gregor03c57052009-11-17 05:17:33 +00002587 // The object type must be complete (or dependent).
2588 if (!BaseType->isDependentType() &&
2589 RequireCompleteType(OpLoc, BaseType,
2590 PDiag(diag::err_incomplete_member_access)))
2591 return ExprError();
2592
Douglas Gregorc68afe22009-09-03 21:38:09 +00002593 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002594 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002595 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002596 // type C (or of pointer to a class type C), the unqualified-id is looked
2597 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002598 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002599 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002600}
2601
Douglas Gregor77549082010-02-24 21:29:12 +00002602Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2603 ExprArg MemExpr) {
2604 Expr *E = (Expr *) MemExpr.get();
2605 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2606 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2607 << isa<CXXPseudoDestructorExpr>(E)
2608 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2609
2610 return ActOnCallExpr(/*Scope*/ 0,
2611 move(MemExpr),
2612 /*LPLoc*/ ExpectedLParenLoc,
2613 Sema::MultiExprArg(*this, 0, 0),
2614 /*CommaLocs*/ 0,
2615 /*RPLoc*/ ExpectedLParenLoc);
2616}
Douglas Gregord4dca082010-02-24 18:44:31 +00002617
Douglas Gregorb57fb492010-02-24 22:38:50 +00002618Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2619 SourceLocation OpLoc,
2620 tok::TokenKind OpKind,
2621 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002622 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002623 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002624 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002625 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002626 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002627 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002628
2629 // C++ [expr.pseudo]p2:
2630 // The left-hand side of the dot operator shall be of scalar type. The
2631 // left-hand side of the arrow operator shall be of pointer to scalar type.
2632 // This scalar type is the object type.
2633 Expr *BaseE = (Expr *)Base.get();
2634 QualType ObjectType = BaseE->getType();
2635 if (OpKind == tok::arrow) {
2636 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2637 ObjectType = Ptr->getPointeeType();
2638 } else if (!BaseE->isTypeDependent()) {
2639 // The user wrote "p->" when she probably meant "p."; fix it.
2640 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2641 << ObjectType << true
2642 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2643 if (isSFINAEContext())
2644 return ExprError();
2645
2646 OpKind = tok::period;
2647 }
2648 }
2649
2650 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2651 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2652 << ObjectType << BaseE->getSourceRange();
2653 return ExprError();
2654 }
2655
2656 // C++ [expr.pseudo]p2:
2657 // [...] The cv-unqualified versions of the object type and of the type
2658 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002659 if (DestructedTypeInfo) {
2660 QualType DestructedType = DestructedTypeInfo->getType();
2661 SourceLocation DestructedTypeStart
2662 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2663 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2664 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2665 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2666 << ObjectType << DestructedType << BaseE->getSourceRange()
2667 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2668
2669 // Recover by setting the destructed type to the object type.
2670 DestructedType = ObjectType;
2671 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2672 DestructedTypeStart);
2673 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2674 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002675 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002676
Douglas Gregorb57fb492010-02-24 22:38:50 +00002677 // C++ [expr.pseudo]p2:
2678 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2679 // form
2680 //
2681 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2682 //
2683 // shall designate the same scalar type.
2684 if (ScopeTypeInfo) {
2685 QualType ScopeType = ScopeTypeInfo->getType();
2686 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2687 !Context.hasSameType(ScopeType, ObjectType)) {
2688
2689 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2690 diag::err_pseudo_dtor_type_mismatch)
2691 << ObjectType << ScopeType << BaseE->getSourceRange()
2692 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2693
2694 ScopeType = QualType();
2695 ScopeTypeInfo = 0;
2696 }
2697 }
2698
2699 OwningExprResult Result
2700 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2701 Base.takeAs<Expr>(),
2702 OpKind == tok::arrow,
2703 OpLoc,
2704 (NestedNameSpecifier *) SS.getScopeRep(),
2705 SS.getRange(),
2706 ScopeTypeInfo,
2707 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002708 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002709 Destructed));
2710
Douglas Gregorb57fb492010-02-24 22:38:50 +00002711 if (HasTrailingLParen)
2712 return move(Result);
2713
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002714 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002715}
2716
2717Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2718 SourceLocation OpLoc,
2719 tok::TokenKind OpKind,
2720 const CXXScopeSpec &SS,
2721 UnqualifiedId &FirstTypeName,
2722 SourceLocation CCLoc,
2723 SourceLocation TildeLoc,
2724 UnqualifiedId &SecondTypeName,
2725 bool HasTrailingLParen) {
2726 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2727 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2728 "Invalid first type name in pseudo-destructor");
2729 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2730 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2731 "Invalid second type name in pseudo-destructor");
2732
2733 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002734
2735 // C++ [expr.pseudo]p2:
2736 // The left-hand side of the dot operator shall be of scalar type. The
2737 // left-hand side of the arrow operator shall be of pointer to scalar type.
2738 // This scalar type is the object type.
2739 QualType ObjectType = BaseE->getType();
2740 if (OpKind == tok::arrow) {
2741 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2742 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002743 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002744 // The user wrote "p->" when she probably meant "p."; fix it.
2745 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002746 << ObjectType << true
2747 << CodeModificationHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002748 if (isSFINAEContext())
2749 return ExprError();
2750
2751 OpKind = tok::period;
2752 }
2753 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002754
2755 // Compute the object type that we should use for name lookup purposes. Only
2756 // record types and dependent types matter.
2757 void *ObjectTypePtrForLookup = 0;
2758 if (!SS.isSet()) {
2759 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2760 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2761 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2762 }
Douglas Gregor77549082010-02-24 21:29:12 +00002763
Douglas Gregorb57fb492010-02-24 22:38:50 +00002764 // Convert the name of the type being destructed (following the ~) into a
2765 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002766 QualType DestructedType;
2767 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002768 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002769 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2770 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2771 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002772 S, &SS, true, ObjectTypePtrForLookup);
2773 if (!T &&
2774 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2775 (!SS.isSet() && ObjectType->isDependentType()))) {
2776 // The name of the type being destroyed is a dependent name, and we
2777 // couldn't find anything useful in scope. Just store the identifier and
2778 // it's location, and we'll perform (qualified) name lookup again at
2779 // template instantiation time.
2780 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2781 SecondTypeName.StartLocation);
2782 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002783 Diag(SecondTypeName.StartLocation,
2784 diag::err_pseudo_dtor_destructor_non_type)
2785 << SecondTypeName.Identifier << ObjectType;
2786 if (isSFINAEContext())
2787 return ExprError();
2788
2789 // Recover by assuming we had the right type all along.
2790 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002791 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002792 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002793 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002794 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002795 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002796 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2797 TemplateId->getTemplateArgs(),
2798 TemplateId->NumArgs);
2799 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2800 TemplateId->TemplateNameLoc,
2801 TemplateId->LAngleLoc,
2802 TemplateArgsPtr,
2803 TemplateId->RAngleLoc);
2804 if (T.isInvalid() || !T.get()) {
2805 // Recover by assuming we had the right type all along.
2806 DestructedType = ObjectType;
2807 } else
2808 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002809 }
2810
Douglas Gregorb57fb492010-02-24 22:38:50 +00002811 // If we've performed some kind of recovery, (re-)build the type source
2812 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002813 if (!DestructedType.isNull()) {
2814 if (!DestructedTypeInfo)
2815 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002816 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002817 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2818 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002819
2820 // Convert the name of the scope type (the type prior to '::') into a type.
2821 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002822 QualType ScopeType;
2823 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2824 FirstTypeName.Identifier) {
2825 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2826 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2827 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002828 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002829 if (!T) {
2830 Diag(FirstTypeName.StartLocation,
2831 diag::err_pseudo_dtor_destructor_non_type)
2832 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002833
Douglas Gregorb57fb492010-02-24 22:38:50 +00002834 if (isSFINAEContext())
2835 return ExprError();
2836
2837 // Just drop this type. It's unnecessary anyway.
2838 ScopeType = QualType();
2839 } else
2840 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002841 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002842 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002843 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002844 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2845 TemplateId->getTemplateArgs(),
2846 TemplateId->NumArgs);
2847 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2848 TemplateId->TemplateNameLoc,
2849 TemplateId->LAngleLoc,
2850 TemplateArgsPtr,
2851 TemplateId->RAngleLoc);
2852 if (T.isInvalid() || !T.get()) {
2853 // Recover by dropping this type.
2854 ScopeType = QualType();
2855 } else
2856 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002857 }
2858 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002859
2860 if (!ScopeType.isNull() && !ScopeTypeInfo)
2861 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2862 FirstTypeName.StartLocation);
2863
2864
Douglas Gregorb57fb492010-02-24 22:38:50 +00002865 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002866 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002867 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002868}
2869
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002870CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2871 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002872 if (PerformObjectArgumentInitialization(Exp, Method))
2873 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2874
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002875 MemberExpr *ME =
2876 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2877 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002878 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002879 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2880 CXXMemberCallExpr *CE =
2881 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2882 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002883 return CE;
2884}
2885
Anders Carlsson0aebc812009-09-09 21:33:21 +00002886Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2887 QualType Ty,
2888 CastExpr::CastKind Kind,
2889 CXXMethodDecl *Method,
2890 ExprArg Arg) {
2891 Expr *From = Arg.takeAs<Expr>();
2892
2893 switch (Kind) {
2894 default: assert(0 && "Unhandled cast kind!");
2895 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002896 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2897
2898 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2899 MultiExprArg(*this, (void **)&From, 1),
2900 CastLoc, ConstructorArgs))
2901 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002902
2903 OwningExprResult Result =
2904 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2905 move_arg(ConstructorArgs));
2906 if (Result.isInvalid())
2907 return ExprError();
2908
2909 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002910 }
2911
2912 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002913 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002914
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002915 // Create an implicit call expr that calls it.
2916 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002917 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002918 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002919 }
2920}
2921
Anders Carlsson165a0a02009-05-17 18:41:29 +00002922Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2923 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002924 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002925 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002926
Anders Carlsson165a0a02009-05-17 18:41:29 +00002927 return Owned(FullExpr);
2928}