blob: 9172956b515300ac31aa9070decf059c647ab859 [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"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000024#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Douglas Gregor124b8782010-02-16 19:09:40 +000028Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
29 IdentifierInfo &II,
30 SourceLocation NameLoc,
31 Scope *S, const CXXScopeSpec &SS,
32 TypeTy *ObjectTypePtr,
33 bool EnteringContext) {
34 // Determine where to perform name lookup.
35
36 // FIXME: This area of the standard is very messy, and the current
37 // wording is rather unclear about which scopes we search for the
38 // destructor name; see core issues 399 and 555. Issue 399 in
39 // particular shows where the current description of destructor name
40 // lookup is completely out of line with existing practice, e.g.,
41 // this appears to be ill-formed:
42 //
43 // namespace N {
44 // template <typename T> struct S {
45 // ~S();
46 // };
47 // }
48 //
49 // void f(N::S<int>* s) {
50 // s->N::S<int>::~S();
51 // }
52 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000053 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000054 QualType SearchType;
55 DeclContext *LookupCtx = 0;
56 bool isDependent = false;
57 bool LookInScope = false;
58
59 // If we have an object type, it's because we are in a
60 // pseudo-destructor-expression or a member access expression, and
61 // we know what type we're looking for.
62 if (ObjectTypePtr)
63 SearchType = GetTypeFromParser(ObjectTypePtr);
64
65 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000066 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
67
68 bool AlreadySearched = false;
69 bool LookAtPrefix = true;
70 if (!getLangOptions().CPlusPlus0x) {
71 // C++ [basic.lookup.qual]p6:
72 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
73 // the type-names are looked up as types in the scope designated by the
74 // nested-name-specifier. In a qualified-id of the form:
75 //
76 // ::[opt] nested-name-specifier ̃ class-name
77 //
78 // where the nested-name-specifier designates a namespace scope, and in
79 // a qualified-id of the form:
80 //
81 // ::opt nested-name-specifier class-name :: ̃ class-name
82 //
83 // the class-names are looked up as types in the scope designated by
84 // the nested-name-specifier.
85 //
86 // Here, we check the first case (completely) and determine whether the
87 // code below is permitted to look at the prefix of the
88 // nested-name-specifier (as we do in C++0x).
89 DeclContext *DC = computeDeclContext(SS, EnteringContext);
90 if (DC && DC->isFileContext()) {
91 AlreadySearched = true;
92 LookupCtx = DC;
93 isDependent = false;
94 } else if (DC && isa<CXXRecordDecl>(DC))
95 LookAtPrefix = false;
96 }
97
98 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +000099 // If a pseudo-destructor-name (5.2.4) contains a
100 // nested-name-specifier, the type-names are looked up as types
101 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000102 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000103 //
104 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
105 //
106 // the second class-name is looked up in the same scope as the first.
107 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000108 // To implement this, we look at the prefix of the
109 // nested-name-specifier we were given, and determine the lookup
110 // context from that.
111 //
112 // We also fold in the second case from the C++03 rules quoted further
113 // above.
114 NestedNameSpecifier *Prefix = 0;
115 if (AlreadySearched) {
116 // Nothing left to do.
117 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
118 CXXScopeSpec PrefixSS;
119 PrefixSS.setScopeRep(Prefix);
120 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
121 isDependent = isDependentScopeSpecifier(PrefixSS);
122 } else if (getLangOptions().CPlusPlus0x &&
123 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
124 if (!LookupCtx->isTranslationUnit())
125 LookupCtx = LookupCtx->getParent();
126 isDependent = LookupCtx && LookupCtx->isDependentContext();
127 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000128 LookupCtx = computeDeclContext(SearchType);
129 isDependent = SearchType->isDependentType();
130 } else {
131 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000132 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000133 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000134
Douglas Gregorb10cd042010-02-21 18:36:56 +0000135 LookInScope = (LookupCtx == 0) && !isDependent;
Douglas Gregor124b8782010-02-16 19:09:40 +0000136 } else if (ObjectTypePtr) {
137 // C++ [basic.lookup.classref]p3:
138 // If the unqualified-id is ~type-name, the type-name is looked up
139 // in the context of the entire postfix-expression. If the type T
140 // of the object expression is of a class type C, the type-name is
141 // also looked up in the scope of class C. At least one of the
142 // lookups shall find a name that refers to (possibly
143 // cv-qualified) T.
144 LookupCtx = computeDeclContext(SearchType);
145 isDependent = SearchType->isDependentType();
146 assert((isDependent || !SearchType->isIncompleteType()) &&
147 "Caller should have completed object type");
148
149 LookInScope = true;
150 } else {
151 // Perform lookup into the current scope (only).
152 LookInScope = true;
153 }
154
155 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
156 for (unsigned Step = 0; Step != 2; ++Step) {
157 // Look for the name first in the computed lookup context (if we
158 // have one) and, if that fails to find a match, in the sope (if
159 // we're allowed to look there).
160 Found.clear();
161 if (Step == 0 && LookupCtx)
162 LookupQualifiedName(Found, LookupCtx);
163 else if (Step == 1 && LookInScope)
164 LookupName(Found, S);
165 else
166 continue;
167
168 // FIXME: Should we be suppressing ambiguities here?
169 if (Found.isAmbiguous())
170 return 0;
171
172 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
173 QualType T = Context.getTypeDeclType(Type);
174 // If we found the injected-class-name of a class template, retrieve the
175 // type of that template.
176 // FIXME: We really shouldn't need to do this.
177 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type))
178 if (Record->isInjectedClassName())
179 if (Record->getDescribedClassTemplate())
180 T = Record->getDescribedClassTemplate()
181 ->getInjectedClassNameType(Context);
182
183 if (SearchType.isNull() || SearchType->isDependentType() ||
184 Context.hasSameUnqualifiedType(T, SearchType)) {
185 // We found our type!
186
187 return T.getAsOpaquePtr();
188 }
189 }
190
191 // If the name that we found is a class template name, and it is
192 // the same name as the template name in the last part of the
193 // nested-name-specifier (if present) or the object type, then
194 // this is the destructor for that class.
195 // FIXME: This is a workaround until we get real drafting for core
196 // issue 399, for which there isn't even an obvious direction.
197 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
198 QualType MemberOfType;
199 if (SS.isSet()) {
200 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
201 // Figure out the type of the context, if it has one.
202 if (ClassTemplateSpecializationDecl *Spec
203 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx))
204 MemberOfType = Context.getTypeDeclType(Spec);
205 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
206 if (Record->getDescribedClassTemplate())
207 MemberOfType = Record->getDescribedClassTemplate()
208 ->getInjectedClassNameType(Context);
209 else
210 MemberOfType = Context.getTypeDeclType(Record);
211 }
212 }
213 }
214 if (MemberOfType.isNull())
215 MemberOfType = SearchType;
216
217 if (MemberOfType.isNull())
218 continue;
219
220 // We're referring into a class template specialization. If the
221 // class template we found is the same as the template being
222 // specialized, we found what we are looking for.
223 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
224 if (ClassTemplateSpecializationDecl *Spec
225 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
226 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
227 Template->getCanonicalDecl())
228 return MemberOfType.getAsOpaquePtr();
229 }
230
231 continue;
232 }
233
234 // We're referring to an unresolved class template
235 // specialization. Determine whether we class template we found
236 // is the same as the template being specialized or, if we don't
237 // know which template is being specialized, that it at least
238 // has the same name.
239 if (const TemplateSpecializationType *SpecType
240 = MemberOfType->getAs<TemplateSpecializationType>()) {
241 TemplateName SpecName = SpecType->getTemplateName();
242
243 // The class template we found is the same template being
244 // specialized.
245 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
246 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
247 return MemberOfType.getAsOpaquePtr();
248
249 continue;
250 }
251
252 // The class template we found has the same name as the
253 // (dependent) template name being specialized.
254 if (DependentTemplateName *DepTemplate
255 = SpecName.getAsDependentTemplateName()) {
256 if (DepTemplate->isIdentifier() &&
257 DepTemplate->getIdentifier() == Template->getIdentifier())
258 return MemberOfType.getAsOpaquePtr();
259
260 continue;
261 }
262 }
263 }
264 }
265
266 if (isDependent) {
267 // We didn't find our type, but that's okay: it's dependent
268 // anyway.
269 NestedNameSpecifier *NNS = 0;
270 SourceRange Range;
271 if (SS.isSet()) {
272 NNS = (NestedNameSpecifier *)SS.getScopeRep();
273 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
274 } else {
275 NNS = NestedNameSpecifier::Create(Context, &II);
276 Range = SourceRange(NameLoc);
277 }
278
279 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
280 }
281
282 if (ObjectTypePtr)
283 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
284 << &II;
285 else
286 Diag(NameLoc, diag::err_destructor_class_name);
287
288 return 0;
289}
290
Sebastian Redlc42e1182008-11-11 11:37:55 +0000291/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000292Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000293Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
294 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000295 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000296 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000297
Douglas Gregorf57f2072009-12-23 20:51:04 +0000298 if (isType) {
299 // C++ [expr.typeid]p4:
300 // The top-level cv-qualifiers of the lvalue expression or the type-id
301 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000302 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000303 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000304 QualType T = GetTypeFromParser(TyOrExpr);
305 if (T.isNull())
306 return ExprError();
307
308 // C++ [expr.typeid]p4:
309 // If the type of the type-id is a class type or a reference to a class
310 // type, the class shall be completely-defined.
311 QualType CheckT = T;
312 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
313 CheckT = RefType->getPointeeType();
314
315 if (CheckT->getAs<RecordType>() &&
316 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
317 return ExprError();
318
319 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000320 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000321
Chris Lattner572af492008-11-20 05:51:55 +0000322 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000323 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
324 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000325 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000326 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000327 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000328
329 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
330
Douglas Gregorac7610d2009-06-22 20:57:11 +0000331 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000332 bool isUnevaluatedOperand = true;
333 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000334 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000335 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000336 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000337 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000338 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000339 // [...] If the type of the expression is a class type, the class
340 // shall be completely-defined.
341 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
342 return ExprError();
343
344 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000345 // When typeid is applied to an expression other than an lvalue of a
346 // polymorphic class type [...] [the] expression is an unevaluated
347 // operand. [...]
348 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000349 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000350 }
351
352 // C++ [expr.typeid]p4:
353 // [...] If the type of the type-id is a reference to a possibly
354 // cv-qualified type, the result of the typeid expression refers to a
355 // std::type_info object representing the cv-unqualified referenced
356 // type.
357 if (T.hasQualifiers()) {
358 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
359 E->isLvalue(Context));
360 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000361 }
362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Douglas Gregor2afce722009-11-26 00:44:06 +0000364 // If this is an unevaluated operand, clear out the set of
365 // declaration references we have been computing and eliminate any
366 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000367 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000368 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
372 TypeInfoType.withConst(),
373 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000374}
375
Steve Naroff1b273c42007-09-16 14:56:35 +0000376/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000377Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000378Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000379 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000381 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
382 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000383}
Chris Lattner50dd2892008-02-26 00:51:44 +0000384
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000385/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
386Action::OwningExprResult
387Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
388 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
389}
390
Chris Lattner50dd2892008-02-26 00:51:44 +0000391/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000392Action::OwningExprResult
393Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000394 Expr *Ex = E.takeAs<Expr>();
395 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
396 return ExprError();
397 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
398}
399
400/// CheckCXXThrowOperand - Validate the operand of a throw.
401bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
402 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000403 // A throw-expression initializes a temporary object, called the exception
404 // object, the type of which is determined by removing any top-level
405 // cv-qualifiers from the static type of the operand of throw and adjusting
406 // the type from "array of T" or "function returning T" to "pointer to T"
407 // or "pointer to function returning T", [...]
408 if (E->getType().hasQualifiers())
409 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
410 E->isLvalue(Context) == Expr::LV_Valid);
411
Sebastian Redl972041f2009-04-27 20:27:31 +0000412 DefaultFunctionArrayConversion(E);
413
414 // If the type of the exception would be an incomplete type or a pointer
415 // to an incomplete type other than (cv) void the program is ill-formed.
416 QualType Ty = E->getType();
417 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000418 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000419 Ty = Ptr->getPointeeType();
420 isPointer = 1;
421 }
422 if (!isPointer || !Ty->isVoidType()) {
423 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000424 PDiag(isPointer ? diag::err_throw_incomplete_ptr
425 : diag::err_throw_incomplete)
426 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000427 return true;
428 }
429
430 // FIXME: Construct a temporary here.
431 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000432}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000433
Sebastian Redlf53597f2009-03-15 17:47:39 +0000434Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000435 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
436 /// is a non-lvalue expression whose value is the address of the object for
437 /// which the function is called.
438
Sebastian Redlf53597f2009-03-15 17:47:39 +0000439 if (!isa<FunctionDecl>(CurContext))
440 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000441
442 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
443 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000444 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000445 MD->getThisType(Context),
446 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000447
Sebastian Redlf53597f2009-03-15 17:47:39 +0000448 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000449}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000450
451/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
452/// Can be interpreted either as function-style casting ("int(x)")
453/// or class type construction ("ClassType(x,y,z)")
454/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000455Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000456Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
457 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000458 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000459 SourceLocation *CommaLocs,
460 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000461 if (!TypeRep)
462 return ExprError();
463
John McCall9d125032010-01-15 18:39:57 +0000464 TypeSourceInfo *TInfo;
465 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
466 if (!TInfo)
467 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000468 unsigned NumExprs = exprs.size();
469 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000470 SourceLocation TyBeginLoc = TypeRange.getBegin();
471 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
472
Sebastian Redlf53597f2009-03-15 17:47:39 +0000473 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000474 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000476
477 return Owned(CXXUnresolvedConstructExpr::Create(Context,
478 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000479 LParenLoc,
480 Exprs, NumExprs,
481 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000482 }
483
Anders Carlssonbb60a502009-08-27 03:53:50 +0000484 if (Ty->isArrayType())
485 return ExprError(Diag(TyBeginLoc,
486 diag::err_value_init_for_array_type) << FullRange);
487 if (!Ty->isVoidType() &&
488 RequireCompleteType(TyBeginLoc, Ty,
489 PDiag(diag::err_invalid_incomplete_type_use)
490 << FullRange))
491 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000492
Anders Carlssonbb60a502009-08-27 03:53:50 +0000493 if (RequireNonAbstractType(TyBeginLoc, Ty,
494 diag::err_allocation_of_abstract_type))
495 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000496
497
Douglas Gregor506ae412009-01-16 18:33:17 +0000498 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000499 // If the expression list is a single expression, the type conversion
500 // expression is equivalent (in definedness, and if defined in meaning) to the
501 // corresponding cast expression.
502 //
503 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000504 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000505 CXXMethodDecl *Method = 0;
506 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
507 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000508 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000509
510 exprs.release();
511 if (Method) {
512 OwningExprResult CastArg
513 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
514 Kind, Method, Owned(Exprs[0]));
515 if (CastArg.isInvalid())
516 return ExprError();
517
518 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000519 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000520
521 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000522 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000523 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000524 }
525
Ted Kremenek6217b802009-07-29 21:53:49 +0000526 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000527 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000528
Mike Stump1eb44332009-09-09 15:08:12 +0000529 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000530 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000531 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
532 InitializationKind Kind
533 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
534 LParenLoc, RParenLoc)
535 : InitializationKind::CreateValue(TypeRange.getBegin(),
536 LParenLoc, RParenLoc);
537 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
538 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
539 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000540
Eli Friedman6997aae2010-01-31 20:58:15 +0000541 // FIXME: Improve AST representation?
542 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000543 }
544
545 // Fall through to value-initialize an object of class type that
546 // doesn't have a user-declared default constructor.
547 }
548
549 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000550 // If the expression list specifies more than a single value, the type shall
551 // be a class with a suitably declared constructor.
552 //
553 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000554 return ExprError(Diag(CommaLocs[0],
555 diag::err_builtin_func_cast_more_than_one_arg)
556 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000557
558 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000559 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000560 // The expression T(), where T is a simple-type-specifier for a non-array
561 // complete object type or the (possibly cv-qualified) void type, creates an
562 // rvalue of the specified type, which is value-initialized.
563 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000564 exprs.release();
565 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000566}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000567
568
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000569/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
570/// @code new (memory) int[size][4] @endcode
571/// or
572/// @code ::new Foo(23, "hello") @endcode
573/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000574Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000575Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000576 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000577 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000578 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000579 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000580 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000581 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000582 // If the specified type is an array, unwrap it and save the expression.
583 if (D.getNumTypeObjects() > 0 &&
584 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
585 DeclaratorChunk &Chunk = D.getTypeObject(0);
586 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000587 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
588 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000589 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000590 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
591 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000592
593 if (ParenTypeId) {
594 // Can't have dynamic array size when the type-id is in parentheses.
595 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
596 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
597 !NumElts->isIntegerConstantExpr(Context)) {
598 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
599 << NumElts->getSourceRange();
600 return ExprError();
601 }
602 }
603
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000604 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000605 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000606 }
607
Douglas Gregor043cad22009-09-11 00:18:58 +0000608 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000609 if (ArraySize) {
610 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000611 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
612 break;
613
614 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
615 if (Expr *NumElts = (Expr *)Array.NumElts) {
616 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
617 !NumElts->isIntegerConstantExpr(Context)) {
618 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
619 << NumElts->getSourceRange();
620 return ExprError();
621 }
622 }
623 }
624 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000625
John McCalla93c9342009-12-07 02:54:59 +0000626 //FIXME: Store TypeSourceInfo in CXXNew expression.
627 TypeSourceInfo *TInfo = 0;
628 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000629 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000630 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000631
Mike Stump1eb44332009-09-09 15:08:12 +0000632 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000633 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000634 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000635 PlacementRParen,
636 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000637 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000638 D.getSourceRange().getBegin(),
639 D.getSourceRange(),
640 Owned(ArraySize),
641 ConstructorLParen,
642 move(ConstructorArgs),
643 ConstructorRParen);
644}
645
Mike Stump1eb44332009-09-09 15:08:12 +0000646Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000647Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
648 SourceLocation PlacementLParen,
649 MultiExprArg PlacementArgs,
650 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000651 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000652 QualType AllocType,
653 SourceLocation TypeLoc,
654 SourceRange TypeRange,
655 ExprArg ArraySizeE,
656 SourceLocation ConstructorLParen,
657 MultiExprArg ConstructorArgs,
658 SourceLocation ConstructorRParen) {
659 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000660 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000661
Douglas Gregor3433cf72009-05-21 00:00:09 +0000662 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000663
664 // That every array dimension except the first is constant was already
665 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000666
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000667 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
668 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000669 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000670 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000671 QualType SizeType = ArraySize->getType();
672 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000673 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
674 diag::err_array_size_not_integral)
675 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000676 // Let's see if this is a constant < 0. If so, we reject it out of hand.
677 // We don't care about special rules, so we tell the machinery it's not
678 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000679 if (!ArraySize->isValueDependent()) {
680 llvm::APSInt Value;
681 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
682 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000683 llvm::APInt::getNullValue(Value.getBitWidth()),
684 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000685 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
686 diag::err_typecheck_negative_array_size)
687 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000688 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000689 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000690
Eli Friedman73c39ab2009-10-20 08:27:19 +0000691 ImpCastExprToType(ArraySize, Context.getSizeType(),
692 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000693 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000694
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000695 FunctionDecl *OperatorNew = 0;
696 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000697 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
698 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000699
Sebastian Redl28507842009-02-26 14:39:58 +0000700 if (!AllocType->isDependentType() &&
701 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
702 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000703 SourceRange(PlacementLParen, PlacementRParen),
704 UseGlobal, AllocType, ArraySize, PlaceArgs,
705 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000706 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000707 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000708 if (OperatorNew) {
709 // Add default arguments, if any.
710 const FunctionProtoType *Proto =
711 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000712 VariadicCallType CallType =
713 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000714 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
715 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000716 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000717 if (Invalid)
718 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000719
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000720 NumPlaceArgs = AllPlaceArgs.size();
721 if (NumPlaceArgs > 0)
722 PlaceArgs = &AllPlaceArgs[0];
723 }
724
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000725 bool Init = ConstructorLParen.isValid();
726 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000727 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000728 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
729 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000730 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
731
Douglas Gregor99a2e602009-12-16 01:38:02 +0000732 if (!AllocType->isDependentType() &&
733 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
734 // C++0x [expr.new]p15:
735 // A new-expression that creates an object of type T initializes that
736 // object as follows:
737 InitializationKind Kind
738 // - If the new-initializer is omitted, the object is default-
739 // initialized (8.5); if no initialization is performed,
740 // the object has indeterminate value
741 = !Init? InitializationKind::CreateDefault(TypeLoc)
742 // - Otherwise, the new-initializer is interpreted according to the
743 // initialization rules of 8.5 for direct-initialization.
744 : InitializationKind::CreateDirect(TypeLoc,
745 ConstructorLParen,
746 ConstructorRParen);
747
Douglas Gregor99a2e602009-12-16 01:38:02 +0000748 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000749 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000750 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000751 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
752 move(ConstructorArgs));
753 if (FullInit.isInvalid())
754 return ExprError();
755
756 // FullInit is our initializer; walk through it to determine if it's a
757 // constructor call, which CXXNewExpr handles directly.
758 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
759 if (CXXBindTemporaryExpr *Binder
760 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
761 FullInitExpr = Binder->getSubExpr();
762 if (CXXConstructExpr *Construct
763 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
764 Constructor = Construct->getConstructor();
765 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
766 AEnd = Construct->arg_end();
767 A != AEnd; ++A)
768 ConvertedConstructorArgs.push_back(A->Retain());
769 } else {
770 // Take the converted initializer.
771 ConvertedConstructorArgs.push_back(FullInit.release());
772 }
773 } else {
774 // No initialization required.
775 }
776
777 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000778 NumConsArgs = ConvertedConstructorArgs.size();
779 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000780 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000781
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000782 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000783
Sebastian Redlf53597f2009-03-15 17:47:39 +0000784 PlacementArgs.release();
785 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000786 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000787 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
788 PlaceArgs, NumPlaceArgs, ParenTypeId,
789 ArraySize, Constructor, Init,
790 ConsArgs, NumConsArgs, OperatorDelete,
791 ResultType, StartLoc,
792 Init ? ConstructorRParen :
793 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000794}
795
796/// CheckAllocatedType - Checks that a type is suitable as the allocated type
797/// in a new-expression.
798/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000799bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000800 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000801 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
802 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000803 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000804 return Diag(Loc, diag::err_bad_new_type)
805 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000806 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000807 return Diag(Loc, diag::err_bad_new_type)
808 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000809 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000810 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000811 PDiag(diag::err_new_incomplete_type)
812 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000813 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000814 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000815 diag::err_allocation_of_abstract_type))
816 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000817
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000818 return false;
819}
820
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000821/// FindAllocationFunctions - Finds the overloads of operator new and delete
822/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000823bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
824 bool UseGlobal, QualType AllocType,
825 bool IsArray, Expr **PlaceArgs,
826 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000827 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000828 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000829 // --- Choosing an allocation function ---
830 // C++ 5.3.4p8 - 14 & 18
831 // 1) If UseGlobal is true, only look in the global scope. Else, also look
832 // in the scope of the allocated class.
833 // 2) If an array size is given, look for operator new[], else look for
834 // operator new.
835 // 3) The first argument is always size_t. Append the arguments from the
836 // placement form.
837 // FIXME: Also find the appropriate delete operator.
838
839 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
840 // We don't care about the actual value of this argument.
841 // FIXME: Should the Sema create the expression and embed it in the syntax
842 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000843 IntegerLiteral Size(llvm::APInt::getNullValue(
844 Context.Target.getPointerWidth(0)),
845 Context.getSizeType(),
846 SourceLocation());
847 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000848 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
849
850 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
851 IsArray ? OO_Array_New : OO_New);
852 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000853 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000854 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000855 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000856 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000857 AllocArgs.size(), Record, /*AllowMissing=*/true,
858 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000859 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000860 }
861 if (!OperatorNew) {
862 // Didn't find a member overload. Look for a global one.
863 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000864 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000865 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000866 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
867 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000868 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000869 }
870
Anders Carlssond9583892009-05-31 20:26:12 +0000871 // FindAllocationOverload can change the passed in arguments, so we need to
872 // copy them back.
873 if (NumPlaceArgs > 0)
874 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000876 return false;
877}
878
Sebastian Redl7f662392008-12-04 22:20:51 +0000879/// FindAllocationOverload - Find an fitting overload for the allocation
880/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000881bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
882 DeclarationName Name, Expr** Args,
883 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000884 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000885 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
886 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000887 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000888 if (AllowMissing)
889 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000890 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000891 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000892 }
893
John McCallf36e02d2009-10-09 21:13:30 +0000894 // FIXME: handle ambiguity
895
John McCall5769d612010-02-08 23:07:23 +0000896 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000897 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
898 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000899 // Even member operator new/delete are implicitly treated as
900 // static, so don't use AddMemberCandidate.
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000901
902 if (FunctionTemplateDecl *FnTemplate =
903 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
904 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
905 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
906 Candidates,
907 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000908 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000909 }
910
911 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
912 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
913 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000914 }
915
916 // Do the resolution.
917 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000918 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000919 case OR_Success: {
920 // Got one!
921 FunctionDecl *FnDecl = Best->Function;
922 // The first argument is size_t, and the first parameter must be size_t,
923 // too. This is checked on declaration and can be assumed. (It can't be
924 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000925 // Whatch out for variadic allocator function.
926 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
927 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000928 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000929 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000930 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000931 return true;
932 }
933 Operator = FnDecl;
934 return false;
935 }
936
937 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000938 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000939 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000940 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000941 return true;
942
943 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000944 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000945 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000946 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000947 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000948
949 case OR_Deleted:
950 Diag(StartLoc, diag::err_ovl_deleted_call)
951 << Best->Function->isDeleted()
952 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000953 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000954 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000955 }
956 assert(false && "Unreachable, bad result from BestViableFunction");
957 return true;
958}
959
960
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000961/// DeclareGlobalNewDelete - Declare the global forms of operator new and
962/// delete. These are:
963/// @code
964/// void* operator new(std::size_t) throw(std::bad_alloc);
965/// void* operator new[](std::size_t) throw(std::bad_alloc);
966/// void operator delete(void *) throw();
967/// void operator delete[](void *) throw();
968/// @endcode
969/// Note that the placement and nothrow forms of new are *not* implicitly
970/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000971void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000972 if (GlobalNewDeleteDeclared)
973 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000974
975 // C++ [basic.std.dynamic]p2:
976 // [...] The following allocation and deallocation functions (18.4) are
977 // implicitly declared in global scope in each translation unit of a
978 // program
979 //
980 // void* operator new(std::size_t) throw(std::bad_alloc);
981 // void* operator new[](std::size_t) throw(std::bad_alloc);
982 // void operator delete(void*) throw();
983 // void operator delete[](void*) throw();
984 //
985 // These implicit declarations introduce only the function names operator
986 // new, operator new[], operator delete, operator delete[].
987 //
988 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
989 // "std" or "bad_alloc" as necessary to form the exception specification.
990 // However, we do not make these implicit declarations visible to name
991 // lookup.
992 if (!StdNamespace) {
993 // The "std" namespace has not yet been defined, so build one implicitly.
994 StdNamespace = NamespaceDecl::Create(Context,
995 Context.getTranslationUnitDecl(),
996 SourceLocation(),
997 &PP.getIdentifierTable().get("std"));
998 StdNamespace->setImplicit(true);
999 }
1000
1001 if (!StdBadAlloc) {
1002 // The "std::bad_alloc" class has not yet been declared, so build it
1003 // implicitly.
1004 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1005 StdNamespace,
1006 SourceLocation(),
1007 &PP.getIdentifierTable().get("bad_alloc"),
1008 SourceLocation(), 0);
1009 StdBadAlloc->setImplicit(true);
1010 }
1011
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001012 GlobalNewDeleteDeclared = true;
1013
1014 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1015 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001016 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001017
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001018 DeclareGlobalAllocationFunction(
1019 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001020 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001021 DeclareGlobalAllocationFunction(
1022 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001023 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001024 DeclareGlobalAllocationFunction(
1025 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1026 Context.VoidTy, VoidPtr);
1027 DeclareGlobalAllocationFunction(
1028 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1029 Context.VoidTy, VoidPtr);
1030}
1031
1032/// DeclareGlobalAllocationFunction - Declares a single implicit global
1033/// allocation function if it doesn't already exist.
1034void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001035 QualType Return, QualType Argument,
1036 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001037 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1038
1039 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001040 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001041 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001042 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001043 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001044 // Only look at non-template functions, as it is the predefined,
1045 // non-templated allocation function we are trying to declare here.
1046 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1047 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001048 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001049 Func->getParamDecl(0)->getType().getUnqualifiedType());
1050 // FIXME: Do we need to check for default arguments here?
1051 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1052 return;
1053 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001054 }
1055 }
1056
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001057 QualType BadAllocType;
1058 bool HasBadAllocExceptionSpec
1059 = (Name.getCXXOverloadedOperator() == OO_New ||
1060 Name.getCXXOverloadedOperator() == OO_Array_New);
1061 if (HasBadAllocExceptionSpec) {
1062 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1063 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1064 }
1065
1066 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1067 true, false,
1068 HasBadAllocExceptionSpec? 1 : 0,
Douglas Gregorce056bc2010-02-21 22:15:06 +00001069 &BadAllocType, false, CC_Default);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001070 FunctionDecl *Alloc =
1071 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +00001072 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001073 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001074
1075 if (AddMallocAttr)
1076 Alloc->addAttr(::new (Context) MallocAttr());
1077
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001078 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001079 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001080 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001081 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001082
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001083 // FIXME: Also add this declaration to the IdentifierResolver, but
1084 // make sure it is at the end of the chain to coincide with the
1085 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001086 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001087}
1088
Anders Carlsson78f74552009-11-15 18:45:20 +00001089bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1090 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001091 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001092 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001093 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001094 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001095
John McCalla24dc2e2009-11-17 02:14:36 +00001096 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001097 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001098
1099 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1100 F != FEnd; ++F) {
1101 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1102 if (Delete->isUsualDeallocationFunction()) {
1103 Operator = Delete;
1104 return false;
1105 }
1106 }
1107
1108 // We did find operator delete/operator delete[] declarations, but
1109 // none of them were suitable.
1110 if (!Found.empty()) {
1111 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1112 << Name << RD;
1113
1114 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1115 F != FEnd; ++F) {
1116 Diag((*F)->getLocation(),
1117 diag::note_delete_member_function_declared_here)
1118 << Name;
1119 }
1120
1121 return true;
1122 }
1123
1124 // Look for a global declaration.
1125 DeclareGlobalNewDelete();
1126 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1127
1128 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1129 Expr* DeallocArgs[1];
1130 DeallocArgs[0] = &Null;
1131 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1132 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1133 Operator))
1134 return true;
1135
1136 assert(Operator && "Did not find a deallocation function!");
1137 return false;
1138}
1139
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001140/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1141/// @code ::delete ptr; @endcode
1142/// or
1143/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001144Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001145Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001146 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001147 // C++ [expr.delete]p1:
1148 // The operand shall have a pointer type, or a class type having a single
1149 // conversion function to a pointer type. The result has type void.
1150 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001151 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1152
Anders Carlssond67c4c32009-08-16 20:29:29 +00001153 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Sebastian Redlf53597f2009-03-15 17:47:39 +00001155 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001156 if (!Ex->isTypeDependent()) {
1157 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001158
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001159 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001160 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +00001161 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00001162 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001163
John McCalleec51cf2010-01-20 00:46:10 +00001164 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001165 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001166 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +00001167 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001168 continue;
1169
John McCallba135432009-11-21 08:51:07 +00001170 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001171
1172 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1173 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1174 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001175 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001176 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001177 if (ObjectPtrConversions.size() == 1) {
1178 // We have a single conversion to a pointer-to-object type. Perform
1179 // that conversion.
1180 Operand.release();
1181 if (!PerformImplicitConversion(Ex,
1182 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001183 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001184 Operand = Owned(Ex);
1185 Type = Ex->getType();
1186 }
1187 }
1188 else if (ObjectPtrConversions.size() > 1) {
1189 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1190 << Type << Ex->getSourceRange();
1191 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1192 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +00001193 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001194 }
1195 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001196 }
Sebastian Redl28507842009-02-26 14:39:58 +00001197 }
1198
Sebastian Redlf53597f2009-03-15 17:47:39 +00001199 if (!Type->isPointerType())
1200 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1201 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001202
Ted Kremenek6217b802009-07-29 21:53:49 +00001203 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001204 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001205 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1206 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001207 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001208 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001209 PDiag(diag::warn_delete_incomplete)
1210 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001211 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001212
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001213 // C++ [expr.delete]p2:
1214 // [Note: a pointer to a const type can be the operand of a
1215 // delete-expression; it is not necessary to cast away the constness
1216 // (5.2.11) of the pointer expression before it is used as the operand
1217 // of the delete-expression. ]
1218 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1219 CastExpr::CK_NoOp);
1220
1221 // Update the operand.
1222 Operand.take();
1223 Operand = ExprArg(*this, Ex);
1224
Anders Carlssond67c4c32009-08-16 20:29:29 +00001225 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1226 ArrayForm ? OO_Array_Delete : OO_Delete);
1227
Anders Carlsson78f74552009-11-15 18:45:20 +00001228 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1229 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1230
1231 if (!UseGlobal &&
1232 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001233 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001234
Anders Carlsson78f74552009-11-15 18:45:20 +00001235 if (!RD->hasTrivialDestructor())
1236 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001237 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001238 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001239 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001240
Anders Carlssond67c4c32009-08-16 20:29:29 +00001241 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001242 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001243 DeclareGlobalNewDelete();
1244 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001245 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001246 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001247 OperatorDelete))
1248 return ExprError();
1249 }
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Sebastian Redl28507842009-02-26 14:39:58 +00001251 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001252 }
1253
Sebastian Redlf53597f2009-03-15 17:47:39 +00001254 Operand.release();
1255 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001256 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001257}
1258
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001259/// \brief Check the use of the given variable as a C++ condition in an if,
1260/// while, do-while, or switch statement.
1261Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1262 QualType T = ConditionVar->getType();
1263
1264 // C++ [stmt.select]p2:
1265 // The declarator shall not specify a function or an array.
1266 if (T->isFunctionType())
1267 return ExprError(Diag(ConditionVar->getLocation(),
1268 diag::err_invalid_use_of_function_type)
1269 << ConditionVar->getSourceRange());
1270 else if (T->isArrayType())
1271 return ExprError(Diag(ConditionVar->getLocation(),
1272 diag::err_invalid_use_of_array_type)
1273 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001274
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001275 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1276 ConditionVar->getLocation(),
1277 ConditionVar->getType().getNonReferenceType()));
1278}
1279
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001280/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1281bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1282 // C++ 6.4p4:
1283 // The value of a condition that is an initialized declaration in a statement
1284 // other than a switch statement is the value of the declared variable
1285 // implicitly converted to type bool. If that conversion is ill-formed, the
1286 // program is ill-formed.
1287 // The value of a condition that is an expression is the value of the
1288 // expression, implicitly converted to bool.
1289 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001290 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001291}
Douglas Gregor77a52232008-09-12 00:47:35 +00001292
1293/// Helper function to determine whether this is the (deprecated) C++
1294/// conversion from a string literal to a pointer to non-const char or
1295/// non-const wchar_t (for narrow and wide string literals,
1296/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001297bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001298Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1299 // Look inside the implicit cast, if it exists.
1300 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1301 From = Cast->getSubExpr();
1302
1303 // A string literal (2.13.4) that is not a wide string literal can
1304 // be converted to an rvalue of type "pointer to char"; a wide
1305 // string literal can be converted to an rvalue of type "pointer
1306 // to wchar_t" (C++ 4.2p2).
1307 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001308 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001309 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001310 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001311 // This conversion is considered only when there is an
1312 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001313 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001314 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1315 (!StrLit->isWide() &&
1316 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1317 ToPointeeType->getKind() == BuiltinType::Char_S))))
1318 return true;
1319 }
1320
1321 return false;
1322}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001323
1324/// PerformImplicitConversion - Perform an implicit conversion of the
1325/// expression From to the type ToType. Returns true if there was an
1326/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001327/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001328/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001329/// explicit user-defined conversions are permitted. @p Elidable should be true
1330/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1331/// resolution works differently in that case.
1332bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001333Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001334 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001335 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001336 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001337 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001338 Elidable, ICS);
1339}
1340
1341bool
1342Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001343 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001344 bool Elidable,
1345 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001346 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001347 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001348 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001349 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001350 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001351 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001352 /*ForceRValue=*/true,
1353 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001354 }
John McCall1d318332010-01-12 00:44:57 +00001355 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001356 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001357 /*SuppressUserConversions=*/false,
1358 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001359 /*ForceRValue=*/false,
1360 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001361 }
Douglas Gregor68647482009-12-16 03:45:30 +00001362 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001363}
1364
1365/// PerformImplicitConversion - Perform an implicit conversion of the
1366/// expression From to the type ToType using the pre-computed implicit
1367/// conversion sequence ICS. Returns true if there was an error, false
1368/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001369/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001370/// used in the error message.
1371bool
1372Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1373 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001374 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001375 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001376 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001377 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001378 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001379 return true;
1380 break;
1381
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001382 case ImplicitConversionSequence::UserDefinedConversion: {
1383
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001384 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1385 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001386 QualType BeforeToType;
1387 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001388 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001389
1390 // If the user-defined conversion is specified by a conversion function,
1391 // the initial standard conversion sequence converts the source type to
1392 // the implicit object parameter of the conversion function.
1393 BeforeToType = Context.getTagDeclType(Conv->getParent());
1394 } else if (const CXXConstructorDecl *Ctor =
1395 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001396 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001397 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001398 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001399 // If the user-defined conversion is specified by a constructor, the
1400 // initial standard conversion sequence converts the source type to the
1401 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001402 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1403 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001404 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001405 else
1406 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001407 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001408 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001409 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001410 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001411 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001412 return true;
1413 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001414
Anders Carlsson0aebc812009-09-09 21:33:21 +00001415 OwningExprResult CastArg
1416 = BuildCXXCastArgument(From->getLocStart(),
1417 ToType.getNonReferenceType(),
1418 CastKind, cast<CXXMethodDecl>(FD),
1419 Owned(From));
1420
1421 if (CastArg.isInvalid())
1422 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001423
1424 From = CastArg.takeAs<Expr>();
1425
Eli Friedmand8889622009-11-27 04:41:50 +00001426 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001427 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001428 }
John McCall1d318332010-01-12 00:44:57 +00001429
1430 case ImplicitConversionSequence::AmbiguousConversion:
1431 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1432 PDiag(diag::err_typecheck_ambiguous_condition)
1433 << From->getSourceRange());
1434 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001435
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001436 case ImplicitConversionSequence::EllipsisConversion:
1437 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001438 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001439
1440 case ImplicitConversionSequence::BadConversion:
1441 return true;
1442 }
1443
1444 // Everything went well.
1445 return false;
1446}
1447
1448/// PerformImplicitConversion - Perform an implicit conversion of the
1449/// expression From to the type ToType by following the standard
1450/// conversion sequence SCS. Returns true if there was an error, false
1451/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001452/// expression. Flavor is the context in which we're performing this
1453/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001454bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001455Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001456 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001457 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001458 // Overall FIXME: we are recomputing too many types here and doing far too
1459 // much extra work. What this means is that we need to keep track of more
1460 // information that is computed when we try the implicit conversion initially,
1461 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001462 QualType FromType = From->getType();
1463
Douglas Gregor225c41e2008-11-03 19:09:14 +00001464 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001465 // FIXME: When can ToType be a reference type?
1466 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001467 if (SCS.Second == ICK_Derived_To_Base) {
1468 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1469 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1470 MultiExprArg(*this, (void **)&From, 1),
1471 /*FIXME:ConstructLoc*/SourceLocation(),
1472 ConstructorArgs))
1473 return true;
1474 OwningExprResult FromResult =
1475 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1476 ToType, SCS.CopyConstructor,
1477 move_arg(ConstructorArgs));
1478 if (FromResult.isInvalid())
1479 return true;
1480 From = FromResult.takeAs<Expr>();
1481 return false;
1482 }
Mike Stump1eb44332009-09-09 15:08:12 +00001483 OwningExprResult FromResult =
1484 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1485 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001486 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001488 if (FromResult.isInvalid())
1489 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001491 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001492 return false;
1493 }
1494
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001495 // Perform the first implicit conversion.
1496 switch (SCS.First) {
1497 case ICK_Identity:
1498 case ICK_Lvalue_To_Rvalue:
1499 // Nothing to do.
1500 break;
1501
1502 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001503 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001504 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001505 break;
1506
1507 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001508 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001509 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1510 if (!Fn)
1511 return true;
1512
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001513 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1514 return true;
1515
Anders Carlsson96ad5332009-10-21 17:16:23 +00001516 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001517 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001518
Sebastian Redl759986e2009-10-17 20:50:27 +00001519 // If there's already an address-of operator in the expression, we have
1520 // the right type already, and the code below would just introduce an
1521 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001522 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001523 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001524 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001525 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001526 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001527 break;
1528
1529 default:
1530 assert(false && "Improper first standard conversion");
1531 break;
1532 }
1533
1534 // Perform the second implicit conversion
1535 switch (SCS.Second) {
1536 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001537 // If both sides are functions (or pointers/references to them), there could
1538 // be incompatible exception declarations.
1539 if (CheckExceptionSpecCompatibility(From, ToType))
1540 return true;
1541 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001542 break;
1543
Douglas Gregor43c79c22009-12-09 00:47:37 +00001544 case ICK_NoReturn_Adjustment:
1545 // If both sides are functions (or pointers/references to them), there could
1546 // be incompatible exception declarations.
1547 if (CheckExceptionSpecCompatibility(From, ToType))
1548 return true;
1549
1550 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1551 CastExpr::CK_NoOp);
1552 break;
1553
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001554 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001555 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001556 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1557 break;
1558
1559 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001560 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001561 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1562 break;
1563
1564 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001565 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001566 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1567 break;
1568
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001569 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001570 if (ToType->isFloatingType())
1571 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1572 else
1573 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1574 break;
1575
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001576 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001577 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1578 break;
1579
Douglas Gregorf9201e02009-02-11 23:02:49 +00001580 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001581 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001582 break;
1583
Anders Carlsson61faec12009-09-12 04:46:44 +00001584 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001585 if (SCS.IncompatibleObjC) {
1586 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001587 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001588 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001589 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001590 << From->getSourceRange();
1591 }
1592
Anders Carlsson61faec12009-09-12 04:46:44 +00001593
1594 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001595 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001596 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001597 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001598 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001599 }
1600
1601 case ICK_Pointer_Member: {
1602 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001603 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001604 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001605 if (CheckExceptionSpecCompatibility(From, ToType))
1606 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001607 ImpCastExprToType(From, ToType, Kind);
1608 break;
1609 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001610 case ICK_Boolean_Conversion: {
1611 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1612 if (FromType->isMemberPointerType())
1613 Kind = CastExpr::CK_MemberPointerToBoolean;
1614
1615 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001616 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001617 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001618
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001619 case ICK_Derived_To_Base:
1620 if (CheckDerivedToBaseConversion(From->getType(),
1621 ToType.getNonReferenceType(),
1622 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001623 From->getSourceRange(),
1624 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001625 return true;
1626 ImpCastExprToType(From, ToType.getNonReferenceType(),
1627 CastExpr::CK_DerivedToBase);
1628 break;
1629
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001630 default:
1631 assert(false && "Improper second standard conversion");
1632 break;
1633 }
1634
1635 switch (SCS.Third) {
1636 case ICK_Identity:
1637 // Nothing to do.
1638 break;
1639
1640 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001641 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1642 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001643 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001644 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001645 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001646 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001647
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001648 default:
1649 assert(false && "Improper second standard conversion");
1650 break;
1651 }
1652
1653 return false;
1654}
1655
Sebastian Redl64b45f72009-01-05 20:52:13 +00001656Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1657 SourceLocation KWLoc,
1658 SourceLocation LParen,
1659 TypeTy *Ty,
1660 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001661 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001663 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1664 // all traits except __is_class, __is_enum and __is_union require a the type
1665 // to be complete.
1666 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001667 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001668 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001669 return ExprError();
1670 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001671
1672 // There is no point in eagerly computing the value. The traits are designed
1673 // to be used from type trait templates, so Ty will be a template parameter
1674 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001675 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1676 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001677}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001678
1679QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001680 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001681 const char *OpSpelling = isIndirect ? "->*" : ".*";
1682 // C++ 5.5p2
1683 // The binary operator .* [p3: ->*] binds its second operand, which shall
1684 // be of type "pointer to member of T" (where T is a completely-defined
1685 // class type) [...]
1686 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001687 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001688 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001689 Diag(Loc, diag::err_bad_memptr_rhs)
1690 << OpSpelling << RType << rex->getSourceRange();
1691 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001692 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001693
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001694 QualType Class(MemPtr->getClass(), 0);
1695
1696 // C++ 5.5p2
1697 // [...] to its first operand, which shall be of class T or of a class of
1698 // which T is an unambiguous and accessible base class. [p3: a pointer to
1699 // such a class]
1700 QualType LType = lex->getType();
1701 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001702 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001703 LType = Ptr->getPointeeType().getNonReferenceType();
1704 else {
1705 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001706 << OpSpelling << 1 << LType
1707 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001708 return QualType();
1709 }
1710 }
1711
Douglas Gregora4923eb2009-11-16 21:35:15 +00001712 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001713 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1714 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001715 // FIXME: Would it be useful to print full ambiguity paths, or is that
1716 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001717 if (!IsDerivedFrom(LType, Class, Paths) ||
1718 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1719 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001720 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001721 return QualType();
1722 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001723 // Cast LHS to type of use.
1724 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1725 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1726 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001727 }
1728
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001729 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001730 // Diagnose use of pointer-to-member type which when used as
1731 // the functional cast in a pointer-to-member expression.
1732 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1733 return QualType();
1734 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001735 // C++ 5.5p2
1736 // The result is an object or a function of the type specified by the
1737 // second operand.
1738 // The cv qualifiers are the union of those in the pointer and the left side,
1739 // in accordance with 5.5p5 and 5.2.5.
1740 // FIXME: This returns a dereferenced member function pointer as a normal
1741 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001742 // calling them. There's also a GCC extension to get a function pointer to the
1743 // thing, which is another complication, because this type - unlike the type
1744 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001745 // argument.
1746 // We probably need a "MemberFunctionClosureType" or something like that.
1747 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001748 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001749 return Result;
1750}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001751
1752/// \brief Get the target type of a standard or user-defined conversion.
1753static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001754 switch (ICS.getKind()) {
1755 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001756 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001757 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001758 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001759 case ImplicitConversionSequence::AmbiguousConversion:
1760 return ICS.Ambiguous.getToType();
1761 case ImplicitConversionSequence::EllipsisConversion:
1762 case ImplicitConversionSequence::BadConversion:
1763 llvm_unreachable("function not valid for ellipsis or bad conversions");
1764 }
1765 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001766}
1767
1768/// \brief Try to convert a type to another according to C++0x 5.16p3.
1769///
1770/// This is part of the parameter validation for the ? operator. If either
1771/// value operand is a class type, the two operands are attempted to be
1772/// converted to each other. This function does the conversion in one direction.
1773/// It emits a diagnostic and returns true only if it finds an ambiguous
1774/// conversion.
1775static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1776 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001777 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001778 // C++0x 5.16p3
1779 // The process for determining whether an operand expression E1 of type T1
1780 // can be converted to match an operand expression E2 of type T2 is defined
1781 // as follows:
1782 // -- If E2 is an lvalue:
1783 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1784 // E1 can be converted to match E2 if E1 can be implicitly converted to
1785 // type "lvalue reference to T2", subject to the constraint that in the
1786 // conversion the reference must bind directly to E1.
1787 if (!Self.CheckReferenceInit(From,
1788 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001789 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001790 /*SuppressUserConversions=*/false,
1791 /*AllowExplicit=*/false,
1792 /*ForceRValue=*/false,
1793 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001794 {
John McCall1d318332010-01-12 00:44:57 +00001795 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001796 "expected a definite conversion");
1797 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001798 ICS.isStandard() ? ICS.Standard.DirectBinding
1799 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001800 if (DirectBinding)
1801 return false;
1802 }
1803 }
John McCall1d318332010-01-12 00:44:57 +00001804 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001805 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1806 // -- if E1 and E2 have class type, and the underlying class types are
1807 // the same or one is a base class of the other:
1808 QualType FTy = From->getType();
1809 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001810 const RecordType *FRec = FTy->getAs<RecordType>();
1811 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001812 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1813 if (FRec && TRec && (FRec == TRec ||
1814 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1815 // E1 can be converted to match E2 if the class of T2 is the
1816 // same type as, or a base class of, the class of T1, and
1817 // [cv2 > cv1].
1818 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1819 // Could still fail if there's no copy constructor.
1820 // FIXME: Is this a hard error then, or just a conversion failure? The
1821 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001822 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001823 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001824 /*ForceRValue=*/false,
1825 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001826 }
1827 } else {
1828 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1829 // implicitly converted to the type that expression E2 would have
1830 // if E2 were converted to an rvalue.
1831 // First find the decayed type.
1832 if (TTy->isFunctionType())
1833 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001834 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001835 TTy = Self.Context.getArrayDecayedType(TTy);
1836
1837 // Now try the implicit conversion.
1838 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001839 ICS = Self.TryImplicitConversion(From, TTy,
1840 /*SuppressUserConversions=*/false,
1841 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001842 /*ForceRValue=*/false,
1843 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001844 }
1845 return false;
1846}
1847
1848/// \brief Try to find a common type for two according to C++0x 5.16p5.
1849///
1850/// This is part of the parameter validation for the ? operator. If either
1851/// value operand is a class type, overload resolution is used to find a
1852/// conversion to a common type.
1853static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1854 SourceLocation Loc) {
1855 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00001856 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00001857 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001858
1859 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001860 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001861 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001862 // We found a match. Perform the conversions on the arguments and move on.
1863 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001864 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001865 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001866 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001867 break;
1868 return false;
1869
Douglas Gregor20093b42009-12-09 23:02:17 +00001870 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001871 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1872 << LHS->getType() << RHS->getType()
1873 << LHS->getSourceRange() << RHS->getSourceRange();
1874 return true;
1875
Douglas Gregor20093b42009-12-09 23:02:17 +00001876 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001877 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1878 << LHS->getType() << RHS->getType()
1879 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001880 // FIXME: Print the possible common types by printing the return types of
1881 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001882 break;
1883
Douglas Gregor20093b42009-12-09 23:02:17 +00001884 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001885 assert(false && "Conditional operator has only built-in overloads");
1886 break;
1887 }
1888 return true;
1889}
1890
Sebastian Redl76458502009-04-17 16:30:52 +00001891/// \brief Perform an "extended" implicit conversion as returned by
1892/// TryClassUnification.
1893///
1894/// TryClassUnification generates ICSs that include reference bindings.
1895/// PerformImplicitConversion is not suitable for this; it chokes if the
1896/// second part of a standard conversion is ICK_DerivedToBase. This function
1897/// handles the reference binding specially.
1898static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001899 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001900 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001901 assert(ICS.Standard.DirectBinding &&
1902 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001903 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1904 // redoing all the work.
1905 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001906 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001907 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001908 /*SuppressUserConversions=*/false,
1909 /*AllowExplicit=*/false,
1910 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001911 }
John McCall1d318332010-01-12 00:44:57 +00001912 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001913 assert(ICS.UserDefined.After.DirectBinding &&
1914 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001915 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001916 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001917 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001918 /*SuppressUserConversions=*/false,
1919 /*AllowExplicit=*/false,
1920 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001921 }
Douglas Gregor68647482009-12-16 03:45:30 +00001922 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001923 return true;
1924 return false;
1925}
1926
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001927/// \brief Check the operands of ?: under C++ semantics.
1928///
1929/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1930/// extension. In this case, LHS == Cond. (But they're not aliases.)
1931QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1932 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001933 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1934 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001935
1936 // C++0x 5.16p1
1937 // The first expression is contextually converted to bool.
1938 if (!Cond->isTypeDependent()) {
1939 if (CheckCXXBooleanCondition(Cond))
1940 return QualType();
1941 }
1942
1943 // Either of the arguments dependent?
1944 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1945 return Context.DependentTy;
1946
John McCallb13c87f2009-11-05 09:23:39 +00001947 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1948
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001949 // C++0x 5.16p2
1950 // If either the second or the third operand has type (cv) void, ...
1951 QualType LTy = LHS->getType();
1952 QualType RTy = RHS->getType();
1953 bool LVoid = LTy->isVoidType();
1954 bool RVoid = RTy->isVoidType();
1955 if (LVoid || RVoid) {
1956 // ... then the [l2r] conversions are performed on the second and third
1957 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00001958 DefaultFunctionArrayLvalueConversion(LHS);
1959 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001960 LTy = LHS->getType();
1961 RTy = RHS->getType();
1962
1963 // ... and one of the following shall hold:
1964 // -- The second or the third operand (but not both) is a throw-
1965 // expression; the result is of the type of the other and is an rvalue.
1966 bool LThrow = isa<CXXThrowExpr>(LHS);
1967 bool RThrow = isa<CXXThrowExpr>(RHS);
1968 if (LThrow && !RThrow)
1969 return RTy;
1970 if (RThrow && !LThrow)
1971 return LTy;
1972
1973 // -- Both the second and third operands have type void; the result is of
1974 // type void and is an rvalue.
1975 if (LVoid && RVoid)
1976 return Context.VoidTy;
1977
1978 // Neither holds, error.
1979 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1980 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1981 << LHS->getSourceRange() << RHS->getSourceRange();
1982 return QualType();
1983 }
1984
1985 // Neither is void.
1986
1987 // C++0x 5.16p3
1988 // Otherwise, if the second and third operand have different types, and
1989 // either has (cv) class type, and attempt is made to convert each of those
1990 // operands to the other.
1991 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1992 (LTy->isRecordType() || RTy->isRecordType())) {
1993 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1994 // These return true if a single direction is already ambiguous.
1995 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1996 return QualType();
1997 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1998 return QualType();
1999
John McCall1d318332010-01-12 00:44:57 +00002000 bool HaveL2R = !ICSLeftToRight.isBad();
2001 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002002 // If both can be converted, [...] the program is ill-formed.
2003 if (HaveL2R && HaveR2L) {
2004 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2005 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2006 return QualType();
2007 }
2008
2009 // If exactly one conversion is possible, that conversion is applied to
2010 // the chosen operand and the converted operands are used in place of the
2011 // original operands for the remainder of this section.
2012 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00002013 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002014 return QualType();
2015 LTy = LHS->getType();
2016 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00002017 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002018 return QualType();
2019 RTy = RHS->getType();
2020 }
2021 }
2022
2023 // C++0x 5.16p4
2024 // If the second and third operands are lvalues and have the same type,
2025 // the result is of that type [...]
2026 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
2027 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2028 RHS->isLvalue(Context) == Expr::LV_Valid)
2029 return LTy;
2030
2031 // C++0x 5.16p5
2032 // Otherwise, the result is an rvalue. If the second and third operands
2033 // do not have the same type, and either has (cv) class type, ...
2034 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2035 // ... overload resolution is used to determine the conversions (if any)
2036 // to be applied to the operands. If the overload resolution fails, the
2037 // program is ill-formed.
2038 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2039 return QualType();
2040 }
2041
2042 // C++0x 5.16p6
2043 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2044 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002045 DefaultFunctionArrayLvalueConversion(LHS);
2046 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002047 LTy = LHS->getType();
2048 RTy = RHS->getType();
2049
2050 // After those conversions, one of the following shall hold:
2051 // -- The second and third operands have the same type; the result
2052 // is of that type.
2053 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2054 return LTy;
2055
2056 // -- The second and third operands have arithmetic or enumeration type;
2057 // the usual arithmetic conversions are performed to bring them to a
2058 // common type, and the result is of that type.
2059 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2060 UsualArithmeticConversions(LHS, RHS);
2061 return LHS->getType();
2062 }
2063
2064 // -- The second and third operands have pointer type, or one has pointer
2065 // type and the other is a null pointer constant; pointer conversions
2066 // and qualification conversions are performed to bring them to their
2067 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002068 // -- The second and third operands have pointer to member type, or one has
2069 // pointer to member type and the other is a null pointer constant;
2070 // pointer to member conversions and qualification conversions are
2071 // performed to bring them to a common type, whose cv-qualification
2072 // shall match the cv-qualification of either the second or the third
2073 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002074 QualType Composite = FindCompositePointerType(LHS, RHS);
2075 if (!Composite.isNull())
2076 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00002077
2078 // Similarly, attempt to find composite type of twp objective-c pointers.
2079 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2080 if (!Composite.isNull())
2081 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002082
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002083 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2084 << LHS->getType() << RHS->getType()
2085 << LHS->getSourceRange() << RHS->getSourceRange();
2086 return QualType();
2087}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002088
2089/// \brief Find a merged pointer type and convert the two expressions to it.
2090///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002091/// This finds the composite pointer type (or member pointer type) for @p E1
2092/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2093/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002094/// It does not emit diagnostics.
2095QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
2096 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2097 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002099 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2100 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002101 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002102
2103 // C++0x 5.9p2
2104 // Pointer conversions and qualification conversions are performed on
2105 // pointer operands to bring them to their composite pointer type. If
2106 // one operand is a null pointer constant, the composite pointer type is
2107 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002108 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002109 if (T2->isMemberPointerType())
2110 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2111 else
2112 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002113 return T2;
2114 }
Douglas Gregorce940492009-09-25 04:25:58 +00002115 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002116 if (T1->isMemberPointerType())
2117 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2118 else
2119 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002120 return T1;
2121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Douglas Gregor20b3e992009-08-24 17:42:35 +00002123 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002124 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2125 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002126 return QualType();
2127
2128 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2129 // the other has type "pointer to cv2 T" and the composite pointer type is
2130 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2131 // Otherwise, the composite pointer type is a pointer type similar to the
2132 // type of one of the operands, with a cv-qualification signature that is
2133 // the union of the cv-qualification signatures of the operand types.
2134 // In practice, the first part here is redundant; it's subsumed by the second.
2135 // What we do here is, we build the two possible composite types, and try the
2136 // conversions in both directions. If only one works, or if the two composite
2137 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002138 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002139 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2140 QualifierVector QualifierUnion;
2141 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2142 ContainingClassVector;
2143 ContainingClassVector MemberOfClass;
2144 QualType Composite1 = Context.getCanonicalType(T1),
2145 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002146 do {
2147 const PointerType *Ptr1, *Ptr2;
2148 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2149 (Ptr2 = Composite2->getAs<PointerType>())) {
2150 Composite1 = Ptr1->getPointeeType();
2151 Composite2 = Ptr2->getPointeeType();
2152 QualifierUnion.push_back(
2153 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2154 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2155 continue;
2156 }
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Douglas Gregor20b3e992009-08-24 17:42:35 +00002158 const MemberPointerType *MemPtr1, *MemPtr2;
2159 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2160 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2161 Composite1 = MemPtr1->getPointeeType();
2162 Composite2 = MemPtr2->getPointeeType();
2163 QualifierUnion.push_back(
2164 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2165 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2166 MemPtr2->getClass()));
2167 continue;
2168 }
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Douglas Gregor20b3e992009-08-24 17:42:35 +00002170 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Douglas Gregor20b3e992009-08-24 17:42:35 +00002172 // Cannot unwrap any more types.
2173 break;
2174 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Douglas Gregor20b3e992009-08-24 17:42:35 +00002176 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002177 ContainingClassVector::reverse_iterator MOC
2178 = MemberOfClass.rbegin();
2179 for (QualifierVector::reverse_iterator
2180 I = QualifierUnion.rbegin(),
2181 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002182 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002183 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002184 if (MOC->first && MOC->second) {
2185 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002186 Composite1 = Context.getMemberPointerType(
2187 Context.getQualifiedType(Composite1, Quals),
2188 MOC->first);
2189 Composite2 = Context.getMemberPointerType(
2190 Context.getQualifiedType(Composite2, Quals),
2191 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002192 } else {
2193 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002194 Composite1
2195 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2196 Composite2
2197 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002198 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002199 }
2200
Mike Stump1eb44332009-09-09 15:08:12 +00002201 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002202 TryImplicitConversion(E1, Composite1,
2203 /*SuppressUserConversions=*/false,
2204 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002205 /*ForceRValue=*/false,
2206 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002207 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002208 TryImplicitConversion(E2, Composite1,
2209 /*SuppressUserConversions=*/false,
2210 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002211 /*ForceRValue=*/false,
2212 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002214 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00002215 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00002216 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002217 if (Context.getCanonicalType(Composite1) !=
2218 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002219 E1ToC2 = TryImplicitConversion(E1, Composite2,
2220 /*SuppressUserConversions=*/false,
2221 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002222 /*ForceRValue=*/false,
2223 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002224 E2ToC2 = TryImplicitConversion(E2, Composite2,
2225 /*SuppressUserConversions=*/false,
2226 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002227 /*ForceRValue=*/false,
2228 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002229 }
2230
John McCall1d318332010-01-12 00:44:57 +00002231 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
2232 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002233 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002234 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2235 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002236 return Composite1;
2237 }
2238 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002239 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2240 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002241 return Composite2;
2242 }
2243 return QualType();
2244}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002245
Anders Carlssondef11992009-05-30 20:36:53 +00002246Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002247 if (!Context.getLangOptions().CPlusPlus)
2248 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Douglas Gregor51326552009-12-24 18:51:59 +00002250 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2251
Ted Kremenek6217b802009-07-29 21:53:49 +00002252 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002253 if (!RT)
2254 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002255
John McCall86ff3082010-02-04 22:26:26 +00002256 // If this is the result of a call expression, our source might
2257 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002258 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2259 QualType Ty = CE->getCallee()->getType();
2260 if (const PointerType *PT = Ty->getAs<PointerType>())
2261 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002262 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2263 Ty = BPT->getPointeeType();
2264
John McCall183700f2009-09-21 23:43:11 +00002265 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002266 if (FTy->getResultType()->isReferenceType())
2267 return Owned(E);
2268 }
John McCall86ff3082010-02-04 22:26:26 +00002269
2270 // That should be enough to guarantee that this type is complete.
2271 // If it has a trivial destructor, we can avoid the extra copy.
2272 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2273 if (RD->hasTrivialDestructor())
2274 return Owned(E);
2275
Mike Stump1eb44332009-09-09 15:08:12 +00002276 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002277 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002278 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002279 if (CXXDestructorDecl *Destructor =
2280 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2281 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002282 // FIXME: Add the temporary to the temporaries vector.
2283 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2284}
2285
Anders Carlsson0ece4912009-12-15 20:51:39 +00002286Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002287 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002289 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2290 assert(ExprTemporaries.size() >= FirstTemporary);
2291 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002292 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002294 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002295 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002296 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002297 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2298 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002300 return E;
2301}
2302
Douglas Gregor90f93822009-12-22 22:17:25 +00002303Sema::OwningExprResult
2304Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2305 if (SubExpr.isInvalid())
2306 return ExprError();
2307
2308 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2309}
2310
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002311FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2312 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2313 assert(ExprTemporaries.size() >= FirstTemporary);
2314
2315 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2316 CXXTemporary **Temporaries =
2317 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2318
2319 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2320
2321 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2322 ExprTemporaries.end());
2323
2324 return E;
2325}
2326
Mike Stump1eb44332009-09-09 15:08:12 +00002327Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002328Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002329 tok::TokenKind OpKind, TypeTy *&ObjectType,
2330 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002331 // Since this might be a postfix expression, get rid of ParenListExprs.
2332 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002334 Expr *BaseExpr = (Expr*)Base.get();
2335 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002337 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002338 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002339 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002340 // If we have a pointer to a dependent type and are using the -> operator,
2341 // the object type is the type that the pointer points to. We might still
2342 // have enough information about that type to do something useful.
2343 if (OpKind == tok::arrow)
2344 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2345 BaseType = Ptr->getPointeeType();
2346
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002347 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002348 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002349 return move(Base);
2350 }
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002352 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002353 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002354 // returned, with the original second operand.
2355 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002356 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002357 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002358 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002359 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002360
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002361 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002362 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002363 BaseExpr = (Expr*)Base.get();
2364 if (BaseExpr == NULL)
2365 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002366 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002367 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002368 BaseType = BaseExpr->getType();
2369 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002370 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002371 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002372 for (unsigned i = 0; i < Locations.size(); i++)
2373 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002374 return ExprError();
2375 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002376 }
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Douglas Gregor31658df2009-11-20 19:58:21 +00002378 if (BaseType->isPointerType())
2379 BaseType = BaseType->getPointeeType();
2380 }
Mike Stump1eb44332009-09-09 15:08:12 +00002381
2382 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002383 // vector types or Objective-C interfaces. Just return early and let
2384 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002385 if (!BaseType->isRecordType()) {
2386 // C++ [basic.lookup.classref]p2:
2387 // [...] If the type of the object expression is of pointer to scalar
2388 // type, the unqualified-id is looked up in the context of the complete
2389 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002390 //
2391 // This also indicates that we should be parsing a
2392 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002393 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002394 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002395 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002396 }
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Douglas Gregor03c57052009-11-17 05:17:33 +00002398 // The object type must be complete (or dependent).
2399 if (!BaseType->isDependentType() &&
2400 RequireCompleteType(OpLoc, BaseType,
2401 PDiag(diag::err_incomplete_member_access)))
2402 return ExprError();
2403
Douglas Gregorc68afe22009-09-03 21:38:09 +00002404 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002405 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002406 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002407 // type C (or of pointer to a class type C), the unqualified-id is looked
2408 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002409 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002410 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002411}
2412
Douglas Gregor77549082010-02-24 21:29:12 +00002413Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2414 ExprArg MemExpr) {
2415 Expr *E = (Expr *) MemExpr.get();
2416 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2417 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2418 << isa<CXXPseudoDestructorExpr>(E)
2419 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2420
2421 return ActOnCallExpr(/*Scope*/ 0,
2422 move(MemExpr),
2423 /*LPLoc*/ ExpectedLParenLoc,
2424 Sema::MultiExprArg(*this, 0, 0),
2425 /*CommaLocs*/ 0,
2426 /*RPLoc*/ ExpectedLParenLoc);
2427}
Douglas Gregord4dca082010-02-24 18:44:31 +00002428
Douglas Gregor77549082010-02-24 21:29:12 +00002429Sema::OwningExprResult
2430Sema::ActOnDependentPseudoDestructorExpr(Scope *S,
2431 ExprArg Base,
2432 SourceLocation OpLoc,
2433 tok::TokenKind OpKind,
2434 const CXXScopeSpec &SS,
2435 UnqualifiedId &FirstTypeName,
2436 SourceLocation CCLoc,
2437 SourceLocation TildeLoc,
2438 UnqualifiedId &SecondTypeName,
2439 bool HasTrailingLParen) {
Douglas Gregord4dca082010-02-24 18:44:31 +00002440 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002441 QualType ObjectType = BaseE->getType();
2442 assert(ObjectType->isDependentType());
2443
Douglas Gregord4dca082010-02-24 18:44:31 +00002444 // The nested-name-specifier provided by the parser, then extended
2445 // by the "type-name ::" in the pseudo-destructor-name, if present.
2446 CXXScopeSpec ExtendedSS = SS;
Douglas Gregor77549082010-02-24 21:29:12 +00002447
Douglas Gregord4dca082010-02-24 18:44:31 +00002448 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2449 FirstTypeName.Identifier) {
2450 // We have a pseudo-destructor with a "type-name ::".
2451 // FIXME: As a temporary hack, we go ahead and resolve this to part of
2452 // a nested-name-specifier.
2453 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2454 // Resolve the identifier to a nested-name-specifier.
2455 CXXScopeTy *FinalScope
Douglas Gregor77549082010-02-24 21:29:12 +00002456 = ActOnCXXNestedNameSpecifier(S, SS,
2457 FirstTypeName.StartLocation,
2458 CCLoc,
2459 *FirstTypeName.Identifier,
2460 true,
2461 ObjectType.getAsOpaquePtr(),
2462 false);
Douglas Gregord4dca082010-02-24 18:44:31 +00002463 if (SS.getBeginLoc().isInvalid())
2464 ExtendedSS.setBeginLoc(FirstTypeName.StartLocation);
2465 ExtendedSS.setEndLoc(CCLoc);
2466 ExtendedSS.setScopeRep(FinalScope);
2467 } else {
2468 // Resolve the template-id to a type, and that to a
2469 // nested-name-specifier.
2470 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
2471 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2472 TemplateId->getTemplateArgs(),
2473 TemplateId->NumArgs);
2474 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2475 TemplateId->TemplateNameLoc,
2476 TemplateId->LAngleLoc,
2477 TemplateArgsPtr,
2478 TemplateId->RAngleLoc);
2479 if (!T.isInvalid()) {
2480 CXXScopeTy *FinalScope
Douglas Gregor77549082010-02-24 21:29:12 +00002481 = ActOnCXXNestedNameSpecifier(S, SS, T.get(),
2482 SourceRange(TemplateId->TemplateNameLoc,
2483 TemplateId->RAngleLoc),
2484 CCLoc,
2485 true);
Douglas Gregord4dca082010-02-24 18:44:31 +00002486 if (SS.getBeginLoc().isInvalid())
2487 ExtendedSS.setBeginLoc(TemplateId->TemplateNameLoc);
2488 ExtendedSS.setEndLoc(CCLoc);
2489 ExtendedSS.setScopeRep(FinalScope);
2490 }
2491 }
2492 }
Douglas Gregor77549082010-02-24 21:29:12 +00002493
Douglas Gregord4dca082010-02-24 18:44:31 +00002494 // Produce a destructor name based on the second type-name (which
2495 // follows the tilde).
2496 TypeTy *DestructedType;
2497 SourceLocation EndLoc;
2498 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2499 const CXXScopeSpec *LookupSS = &SS;
2500 bool isDependent = isDependentScopeSpecifier(ExtendedSS);
2501 if (isDependent || computeDeclContext(ExtendedSS))
2502 LookupSS = &ExtendedSS;
Douglas Gregor77549082010-02-24 21:29:12 +00002503
Douglas Gregord4dca082010-02-24 18:44:31 +00002504 DestructedType = getTypeName(*SecondTypeName.Identifier,
2505 SecondTypeName.StartLocation,
2506 S, LookupSS, true, ObjectType.getTypePtr());
2507 if (!DestructedType && isDependent) {
2508 // We didn't find our type, but that's okay: it's dependent
2509 // anyway.
2510 // FIXME: We should not be building a typename type here!
2511 NestedNameSpecifier *NNS = 0;
2512 SourceRange Range;
2513 if (SS.isSet()) {
2514 NNS = (NestedNameSpecifier *)ExtendedSS.getScopeRep();
2515 Range = SourceRange(ExtendedSS.getRange().getBegin(),
2516 SecondTypeName.StartLocation);
2517 } else {
2518 NNS = NestedNameSpecifier::Create(Context, SecondTypeName.Identifier);
2519 Range = SourceRange(SecondTypeName.StartLocation);
2520 }
2521
2522 DestructedType = CheckTypenameType(NNS, *SecondTypeName.Identifier,
2523 Range).getAsOpaquePtr();
2524 if (!DestructedType)
2525 return ExprError();
2526 }
Douglas Gregor77549082010-02-24 21:29:12 +00002527
Douglas Gregord4dca082010-02-24 18:44:31 +00002528 if (!DestructedType) {
2529 // FIXME: Crummy diagnostic.
2530 Diag(SecondTypeName.StartLocation, diag::err_destructor_class_name);
2531 return ExprError();
2532 }
Douglas Gregor77549082010-02-24 21:29:12 +00002533
Douglas Gregord4dca082010-02-24 18:44:31 +00002534 EndLoc = SecondTypeName.EndLocation;
2535 } else {
2536 // Resolve the template-id to a type, and that to a
2537 // nested-name-specifier.
2538 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
2539 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2540 TemplateId->getTemplateArgs(),
Douglas Gregor77549082010-02-24 21:29:12 +00002541 TemplateId->NumArgs);
Douglas Gregord4dca082010-02-24 18:44:31 +00002542 EndLoc = TemplateId->RAngleLoc;
2543 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2544 TemplateId->TemplateNameLoc,
2545 TemplateId->LAngleLoc,
2546 TemplateArgsPtr,
2547 TemplateId->RAngleLoc);
2548 if (T.isInvalid() || !T.get())
2549 return ExprError();
2550
2551 DestructedType = T.get();
2552 }
Douglas Gregor77549082010-02-24 21:29:12 +00002553
Douglas Gregord4dca082010-02-24 18:44:31 +00002554 // Form a (possibly fake) destructor name and let the member access
2555 // expression code deal with this.
2556 // FIXME: Don't do this! It's totally broken!
2557 UnqualifiedId Destructor;
2558 Destructor.setDestructorName(TildeLoc, DestructedType, EndLoc);
2559 return ActOnMemberAccessExpr(S, move(Base), OpLoc, OpKind, ExtendedSS,
2560 Destructor, DeclPtrTy(), HasTrailingLParen);
Douglas Gregor77549082010-02-24 21:29:12 +00002561
2562}
2563
2564Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2565 SourceLocation OpLoc,
2566 tok::TokenKind OpKind,
2567 const CXXScopeSpec &SS,
2568 UnqualifiedId &FirstTypeName,
2569 SourceLocation CCLoc,
2570 SourceLocation TildeLoc,
2571 UnqualifiedId &SecondTypeName,
2572 bool HasTrailingLParen) {
2573 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2574 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2575 "Invalid first type name in pseudo-destructor");
2576 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2577 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2578 "Invalid second type name in pseudo-destructor");
2579
2580 Expr *BaseE = (Expr *)Base.get();
2581 if (BaseE->isTypeDependent())
2582 return ActOnDependentPseudoDestructorExpr(S, move(Base), OpLoc, OpKind,
2583 SS, FirstTypeName, CCLoc,
2584 TildeLoc, SecondTypeName,
2585 HasTrailingLParen);
2586
2587 // C++ [expr.pseudo]p2:
2588 // The left-hand side of the dot operator shall be of scalar type. The
2589 // left-hand side of the arrow operator shall be of pointer to scalar type.
2590 // This scalar type is the object type.
2591 QualType ObjectType = BaseE->getType();
2592 if (OpKind == tok::arrow) {
2593 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2594 ObjectType = Ptr->getPointeeType();
2595 } else {
2596 // The user wrote "p->" when she probably meant "p."; fix it.
2597 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2598 << ObjectType << true
2599 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2600 if (isSFINAEContext())
2601 return ExprError();
2602
2603 OpKind = tok::period;
2604 }
2605 }
2606
2607 if (!ObjectType->isScalarType()) {
2608 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2609 << ObjectType << BaseE->getSourceRange();
2610 return ExprError();
2611 }
2612
2613 //
2614
2615 // C++ [expr.pseudo]p2:
2616 // [...] The cv-unqualified versions of the object type and of the type
2617 // designated by the pseudo-destructor-name shall be the same type.
2618 QualType DestructedType;
2619 TypeSourceInfo *DestructedTypeInfo = 0;
2620 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2621 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2622 SecondTypeName.StartLocation,
2623 S, &SS);
2624 if (!T) {
2625 Diag(SecondTypeName.StartLocation,
2626 diag::err_pseudo_dtor_destructor_non_type)
2627 << SecondTypeName.Identifier << ObjectType;
2628 if (isSFINAEContext())
2629 return ExprError();
2630
2631 // Recover by assuming we had the right type all along.
2632 DestructedType = ObjectType;
2633 } else {
2634 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
2635
2636 if (!DestructedType->isDependentType() &&
2637 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2638 // The types mismatch. Recover by assuming we had the right type
2639 // all along.
2640 Diag(SecondTypeName.StartLocation, diag::err_pseudo_dtor_type_mismatch)
2641 << ObjectType << DestructedType << BaseE->getSourceRange();
2642
2643 DestructedType = ObjectType;
2644 DestructedTypeInfo = 0;
2645 }
2646 }
2647 } else {
2648 // FIXME: C++0x template aliases would allow a template-id here. For now,
2649 // just diagnose this as an error.
2650 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
2651 Diag(TemplateId->TemplateNameLoc, diag::err_pseudo_dtor_template)
2652 << TemplateId->Name << ObjectType
2653 << SourceRange(TemplateId->TemplateNameLoc, TemplateId->RAngleLoc);
2654 if (isSFINAEContext())
2655 return ExprError();
2656
2657 // Recover by assuming we had the right type all along.
2658 DestructedType = ObjectType;
2659 }
2660
2661 // C++ [expr.pseudo]p2:
2662 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2663 // form
2664 //
2665 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2666 //
2667 // shall designate the same scalar type.
2668 QualType ScopeType;
2669 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2670 FirstTypeName.Identifier) {
2671 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2672 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2673 FirstTypeName.StartLocation,
2674 S, &SS);
2675 if (!T) {
2676 Diag(FirstTypeName.StartLocation,
2677 diag::err_pseudo_dtor_destructor_non_type)
2678 << FirstTypeName.Identifier << ObjectType;
2679 if (isSFINAEContext())
2680 return ExprError();
2681 } else {
2682 // FIXME: Drops source-location information.
2683 ScopeType = GetTypeFromParser(T);
2684
2685 if (!ScopeType->isDependentType() &&
2686 !Context.hasSameUnqualifiedType(DestructedType, ScopeType)) {
2687 // The types mismatch. Recover by assuming we don't have a scoping
2688 // type.
2689 Diag(FirstTypeName.StartLocation, diag::err_pseudo_dtor_type_mismatch)
2690 << ObjectType << ScopeType << BaseE->getSourceRange();
2691
2692 ScopeType = QualType();
2693 }
2694 }
2695 } else {
2696 // FIXME: C++0x template aliases would allow a template-id here. For now,
2697 // just diagnose this as an error.
2698 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
2699 Diag(TemplateId->TemplateNameLoc, diag::err_pseudo_dtor_template)
2700 << TemplateId->Name << ObjectType
2701 << SourceRange(TemplateId->TemplateNameLoc, TemplateId->RAngleLoc);
2702 if (isSFINAEContext())
2703 return ExprError();
2704
2705 // Recover by assuming we have no scoping type.
2706 DestructedType = ObjectType;
2707 }
2708 }
2709
2710 // FIXME: Drops the scope type.
2711 OwningExprResult Result
2712 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2713 Base.takeAs<Expr>(),
2714 OpKind == tok::arrow,
2715 OpLoc,
2716 (NestedNameSpecifier *) SS.getScopeRep(),
2717 SS.getRange(),
2718 DestructedType,
2719 SecondTypeName.StartLocation));
2720 if (HasTrailingLParen)
2721 return move(Result);
2722
2723 return DiagnoseDtorReference(SecondTypeName.StartLocation, move(Result));
Douglas Gregord4dca082010-02-24 18:44:31 +00002724}
2725
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002726CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2727 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002728 if (PerformObjectArgumentInitialization(Exp, Method))
2729 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2730
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002731 MemberExpr *ME =
2732 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2733 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002734 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002735 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2736 CXXMemberCallExpr *CE =
2737 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2738 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002739 return CE;
2740}
2741
Anders Carlsson0aebc812009-09-09 21:33:21 +00002742Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2743 QualType Ty,
2744 CastExpr::CastKind Kind,
2745 CXXMethodDecl *Method,
2746 ExprArg Arg) {
2747 Expr *From = Arg.takeAs<Expr>();
2748
2749 switch (Kind) {
2750 default: assert(0 && "Unhandled cast kind!");
2751 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002752 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2753
2754 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2755 MultiExprArg(*this, (void **)&From, 1),
2756 CastLoc, ConstructorArgs))
2757 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002758
2759 OwningExprResult Result =
2760 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2761 move_arg(ConstructorArgs));
2762 if (Result.isInvalid())
2763 return ExprError();
2764
2765 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002766 }
2767
2768 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002769 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002770
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002771 // Create an implicit call expr that calls it.
2772 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002773 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002774 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002775 }
2776}
2777
Anders Carlsson165a0a02009-05-17 18:41:29 +00002778Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2779 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002780 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002781 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002782
Anders Carlsson165a0a02009-05-17 18:41:29 +00002783 return Owned(FullExpr);
2784}