blob: 5f4601961c8e597151f0c44b2a9810c76ecaf5b2 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor124b8782010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
32 Scope *S, const CXXScopeSpec &SS,
33 TypeTy *ObjectTypePtr,
34 bool EnteringContext) {
35 // Determine where to perform name lookup.
36
37 // FIXME: This area of the standard is very messy, and the current
38 // wording is rather unclear about which scopes we search for the
39 // destructor name; see core issues 399 and 555. Issue 399 in
40 // particular shows where the current description of destructor name
41 // lookup is completely out of line with existing practice, e.g.,
42 // this appears to be ill-formed:
43 //
44 // namespace N {
45 // template <typename T> struct S {
46 // ~S();
47 // };
48 // }
49 //
50 // void f(N::S<int>* s) {
51 // s->N::S<int>::~S();
52 // }
53 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000055 QualType SearchType;
56 DeclContext *LookupCtx = 0;
57 bool isDependent = false;
58 bool LookInScope = false;
59
60 // If we have an object type, it's because we are in a
61 // pseudo-destructor-expression or a member access expression, and
62 // we know what type we're looking for.
63 if (ObjectTypePtr)
64 SearchType = GetTypeFromParser(ObjectTypePtr);
65
66 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000067 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69 bool AlreadySearched = false;
70 bool LookAtPrefix = true;
71 if (!getLangOptions().CPlusPlus0x) {
72 // C++ [basic.lookup.qual]p6:
73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74 // the type-names are looked up as types in the scope designated by the
75 // nested-name-specifier. In a qualified-id of the form:
76 //
77 // ::[opt] nested-name-specifier ̃ class-name
78 //
79 // where the nested-name-specifier designates a namespace scope, and in
80 // a qualified-id of the form:
81 //
82 // ::opt nested-name-specifier class-name :: ̃ class-name
83 //
84 // the class-names are looked up as types in the scope designated by
85 // the nested-name-specifier.
86 //
87 // Here, we check the first case (completely) and determine whether the
88 // code below is permitted to look at the prefix of the
89 // nested-name-specifier (as we do in C++0x).
90 DeclContext *DC = computeDeclContext(SS, EnteringContext);
91 if (DC && DC->isFileContext()) {
92 AlreadySearched = true;
93 LookupCtx = DC;
94 isDependent = false;
95 } else if (DC && isa<CXXRecordDecl>(DC))
96 LookAtPrefix = false;
97 }
98
99 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +0000100 // If a pseudo-destructor-name (5.2.4) contains a
101 // nested-name-specifier, the type-names are looked up as types
102 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000104 //
105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106 //
107 // the second class-name is looked up in the same scope as the first.
108 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 // To implement this, we look at the prefix of the
110 // nested-name-specifier we were given, and determine the lookup
111 // context from that.
112 //
113 // We also fold in the second case from the C++03 rules quoted further
114 // above.
115 NestedNameSpecifier *Prefix = 0;
116 if (AlreadySearched) {
117 // Nothing left to do.
118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119 CXXScopeSpec PrefixSS;
120 PrefixSS.setScopeRep(Prefix);
121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(PrefixSS);
123 } else if (getLangOptions().CPlusPlus0x &&
124 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125 if (!LookupCtx->isTranslationUnit())
126 LookupCtx = LookupCtx->getParent();
127 isDependent = LookupCtx && LookupCtx->isDependentContext();
128 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000134 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000135
Douglas Gregoredc90502010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 } else if (ObjectTypePtr) {
138 // C++ [basic.lookup.classref]p3:
139 // If the unqualified-id is ~type-name, the type-name is looked up
140 // in the context of the entire postfix-expression. If the type T
141 // of the object expression is of a class type C, the type-name is
142 // also looked up in the scope of class C. At least one of the
143 // lookups shall find a name that refers to (possibly
144 // cv-qualified) T.
145 LookupCtx = computeDeclContext(SearchType);
146 isDependent = SearchType->isDependentType();
147 assert((isDependent || !SearchType->isIncompleteType()) &&
148 "Caller should have completed object type");
149
150 LookInScope = true;
151 } else {
152 // Perform lookup into the current scope (only).
153 LookInScope = true;
154 }
155
156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157 for (unsigned Step = 0; Step != 2; ++Step) {
158 // Look for the name first in the computed lookup context (if we
159 // have one) and, if that fails to find a match, in the sope (if
160 // we're allowed to look there).
161 Found.clear();
162 if (Step == 0 && LookupCtx)
163 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 LookupName(Found, S);
166 else
167 continue;
168
169 // FIXME: Should we be suppressing ambiguities here?
170 if (Found.isAmbiguous())
171 return 0;
172
173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174 QualType T = Context.getTypeDeclType(Type);
175 // If we found the injected-class-name of a class template, retrieve the
176 // type of that template.
177 // FIXME: We really shouldn't need to do this.
178 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type))
179 if (Record->isInjectedClassName())
180 if (Record->getDescribedClassTemplate())
181 T = Record->getDescribedClassTemplate()
182 ->getInjectedClassNameType(Context);
183
184 if (SearchType.isNull() || SearchType->isDependentType() ||
185 Context.hasSameUnqualifiedType(T, SearchType)) {
186 // We found our type!
187
188 return T.getAsOpaquePtr();
189 }
190 }
191
192 // If the name that we found is a class template name, and it is
193 // the same name as the template name in the last part of the
194 // nested-name-specifier (if present) or the object type, then
195 // this is the destructor for that class.
196 // FIXME: This is a workaround until we get real drafting for core
197 // issue 399, for which there isn't even an obvious direction.
198 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
199 QualType MemberOfType;
200 if (SS.isSet()) {
201 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
202 // Figure out the type of the context, if it has one.
203 if (ClassTemplateSpecializationDecl *Spec
204 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx))
205 MemberOfType = Context.getTypeDeclType(Spec);
206 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
207 if (Record->getDescribedClassTemplate())
208 MemberOfType = Record->getDescribedClassTemplate()
209 ->getInjectedClassNameType(Context);
210 else
211 MemberOfType = Context.getTypeDeclType(Record);
212 }
213 }
214 }
215 if (MemberOfType.isNull())
216 MemberOfType = SearchType;
217
218 if (MemberOfType.isNull())
219 continue;
220
221 // We're referring into a class template specialization. If the
222 // class template we found is the same as the template being
223 // specialized, we found what we are looking for.
224 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
225 if (ClassTemplateSpecializationDecl *Spec
226 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
227 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
228 Template->getCanonicalDecl())
229 return MemberOfType.getAsOpaquePtr();
230 }
231
232 continue;
233 }
234
235 // We're referring to an unresolved class template
236 // specialization. Determine whether we class template we found
237 // is the same as the template being specialized or, if we don't
238 // know which template is being specialized, that it at least
239 // has the same name.
240 if (const TemplateSpecializationType *SpecType
241 = MemberOfType->getAs<TemplateSpecializationType>()) {
242 TemplateName SpecName = SpecType->getTemplateName();
243
244 // The class template we found is the same template being
245 // specialized.
246 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
247 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
248 return MemberOfType.getAsOpaquePtr();
249
250 continue;
251 }
252
253 // The class template we found has the same name as the
254 // (dependent) template name being specialized.
255 if (DependentTemplateName *DepTemplate
256 = SpecName.getAsDependentTemplateName()) {
257 if (DepTemplate->isIdentifier() &&
258 DepTemplate->getIdentifier() == Template->getIdentifier())
259 return MemberOfType.getAsOpaquePtr();
260
261 continue;
262 }
263 }
264 }
265 }
266
267 if (isDependent) {
268 // We didn't find our type, but that's okay: it's dependent
269 // anyway.
270 NestedNameSpecifier *NNS = 0;
271 SourceRange Range;
272 if (SS.isSet()) {
273 NNS = (NestedNameSpecifier *)SS.getScopeRep();
274 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
275 } else {
276 NNS = NestedNameSpecifier::Create(Context, &II);
277 Range = SourceRange(NameLoc);
278 }
279
280 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
281 }
282
283 if (ObjectTypePtr)
284 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
285 << &II;
286 else
287 Diag(NameLoc, diag::err_destructor_class_name);
288
289 return 0;
290}
291
Sebastian Redlc42e1182008-11-11 11:37:55 +0000292/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000293Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000294Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
295 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000296 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000297 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000298
Douglas Gregorf57f2072009-12-23 20:51:04 +0000299 if (isType) {
300 // C++ [expr.typeid]p4:
301 // The top-level cv-qualifiers of the lvalue expression or the type-id
302 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000303 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000304 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000305 QualType T = GetTypeFromParser(TyOrExpr);
306 if (T.isNull())
307 return ExprError();
308
309 // C++ [expr.typeid]p4:
310 // If the type of the type-id is a class type or a reference to a class
311 // type, the class shall be completely-defined.
312 QualType CheckT = T;
313 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
314 CheckT = RefType->getPointeeType();
315
316 if (CheckT->getAs<RecordType>() &&
317 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
318 return ExprError();
319
320 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000321 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000322
Chris Lattner572af492008-11-20 05:51:55 +0000323 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000324 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
325 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000326 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000327 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000328 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000329
330 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
331
Douglas Gregorac7610d2009-06-22 20:57:11 +0000332 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000333 bool isUnevaluatedOperand = true;
334 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000335 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000336 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000337 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000338 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000339 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000340 // [...] If the type of the expression is a class type, the class
341 // shall be completely-defined.
342 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
343 return ExprError();
344
345 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000346 // When typeid is applied to an expression other than an lvalue of a
347 // polymorphic class type [...] [the] expression is an unevaluated
348 // operand. [...]
349 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000350 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000351 }
352
353 // C++ [expr.typeid]p4:
354 // [...] If the type of the type-id is a reference to a possibly
355 // cv-qualified type, the result of the typeid expression refers to a
356 // std::type_info object representing the cv-unqualified referenced
357 // type.
358 if (T.hasQualifiers()) {
359 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
360 E->isLvalue(Context));
361 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000362 }
363 }
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Douglas Gregor2afce722009-11-26 00:44:06 +0000365 // If this is an unevaluated operand, clear out the set of
366 // declaration references we have been computing and eliminate any
367 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000368 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000369 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Sebastian Redlf53597f2009-03-15 17:47:39 +0000372 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
373 TypeInfoType.withConst(),
374 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000375}
376
Steve Naroff1b273c42007-09-16 14:56:35 +0000377/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000378Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000379Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000380 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000382 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
383 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000384}
Chris Lattner50dd2892008-02-26 00:51:44 +0000385
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000386/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
387Action::OwningExprResult
388Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
389 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
390}
391
Chris Lattner50dd2892008-02-26 00:51:44 +0000392/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000393Action::OwningExprResult
394Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000395 Expr *Ex = E.takeAs<Expr>();
396 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
397 return ExprError();
398 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
399}
400
401/// CheckCXXThrowOperand - Validate the operand of a throw.
402bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
403 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000404 // A throw-expression initializes a temporary object, called the exception
405 // object, the type of which is determined by removing any top-level
406 // cv-qualifiers from the static type of the operand of throw and adjusting
407 // the type from "array of T" or "function returning T" to "pointer to T"
408 // or "pointer to function returning T", [...]
409 if (E->getType().hasQualifiers())
410 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
411 E->isLvalue(Context) == Expr::LV_Valid);
412
Sebastian Redl972041f2009-04-27 20:27:31 +0000413 DefaultFunctionArrayConversion(E);
414
415 // If the type of the exception would be an incomplete type or a pointer
416 // to an incomplete type other than (cv) void the program is ill-formed.
417 QualType Ty = E->getType();
418 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000419 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000420 Ty = Ptr->getPointeeType();
421 isPointer = 1;
422 }
423 if (!isPointer || !Ty->isVoidType()) {
424 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000425 PDiag(isPointer ? diag::err_throw_incomplete_ptr
426 : diag::err_throw_incomplete)
427 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000428 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000429
430 // FIXME: This is just a hack to mark the copy constructor referenced.
431 // This should go away when the next FIXME is fixed.
432 const RecordType *RT = Ty->getAs<RecordType>();
433 if (!RT)
434 return false;
435
436 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
437 if (RD->hasTrivialCopyConstructor())
438 return false;
439 CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0);
440 MarkDeclarationReferenced(ThrowLoc, CopyCtor);
Sebastian Redl972041f2009-04-27 20:27:31 +0000441 }
442
443 // FIXME: Construct a temporary here.
444 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000445}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000446
Sebastian Redlf53597f2009-03-15 17:47:39 +0000447Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000448 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
449 /// is a non-lvalue expression whose value is the address of the object for
450 /// which the function is called.
451
Sebastian Redlf53597f2009-03-15 17:47:39 +0000452 if (!isa<FunctionDecl>(CurContext))
453 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000454
455 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
456 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000457 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000458 MD->getThisType(Context),
459 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000460
Sebastian Redlf53597f2009-03-15 17:47:39 +0000461 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000462}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000463
464/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
465/// Can be interpreted either as function-style casting ("int(x)")
466/// or class type construction ("ClassType(x,y,z)")
467/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000468Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000469Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
470 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000471 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000472 SourceLocation *CommaLocs,
473 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000474 if (!TypeRep)
475 return ExprError();
476
John McCall9d125032010-01-15 18:39:57 +0000477 TypeSourceInfo *TInfo;
478 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
479 if (!TInfo)
480 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000481 unsigned NumExprs = exprs.size();
482 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000483 SourceLocation TyBeginLoc = TypeRange.getBegin();
484 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
485
Sebastian Redlf53597f2009-03-15 17:47:39 +0000486 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000487 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000488 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000489
490 return Owned(CXXUnresolvedConstructExpr::Create(Context,
491 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000492 LParenLoc,
493 Exprs, NumExprs,
494 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000495 }
496
Anders Carlssonbb60a502009-08-27 03:53:50 +0000497 if (Ty->isArrayType())
498 return ExprError(Diag(TyBeginLoc,
499 diag::err_value_init_for_array_type) << FullRange);
500 if (!Ty->isVoidType() &&
501 RequireCompleteType(TyBeginLoc, Ty,
502 PDiag(diag::err_invalid_incomplete_type_use)
503 << FullRange))
504 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000505
Anders Carlssonbb60a502009-08-27 03:53:50 +0000506 if (RequireNonAbstractType(TyBeginLoc, Ty,
507 diag::err_allocation_of_abstract_type))
508 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000509
510
Douglas Gregor506ae412009-01-16 18:33:17 +0000511 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000512 // If the expression list is a single expression, the type conversion
513 // expression is equivalent (in definedness, and if defined in meaning) to the
514 // corresponding cast expression.
515 //
516 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000517 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000518 CXXMethodDecl *Method = 0;
519 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
520 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000521 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000522
523 exprs.release();
524 if (Method) {
525 OwningExprResult CastArg
526 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
527 Kind, Method, Owned(Exprs[0]));
528 if (CastArg.isInvalid())
529 return ExprError();
530
531 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000532 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000533
534 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000535 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000536 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000537 }
538
Ted Kremenek6217b802009-07-29 21:53:49 +0000539 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000540 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000541
Mike Stump1eb44332009-09-09 15:08:12 +0000542 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000543 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000544 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
545 InitializationKind Kind
546 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
547 LParenLoc, RParenLoc)
548 : InitializationKind::CreateValue(TypeRange.getBegin(),
549 LParenLoc, RParenLoc);
550 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
551 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
552 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000553
Eli Friedman6997aae2010-01-31 20:58:15 +0000554 // FIXME: Improve AST representation?
555 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000556 }
557
558 // Fall through to value-initialize an object of class type that
559 // doesn't have a user-declared default constructor.
560 }
561
562 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000563 // If the expression list specifies more than a single value, the type shall
564 // be a class with a suitably declared constructor.
565 //
566 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000567 return ExprError(Diag(CommaLocs[0],
568 diag::err_builtin_func_cast_more_than_one_arg)
569 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000570
571 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000572 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000573 // The expression T(), where T is a simple-type-specifier for a non-array
574 // complete object type or the (possibly cv-qualified) void type, creates an
575 // rvalue of the specified type, which is value-initialized.
576 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000577 exprs.release();
578 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000579}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000580
581
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000582/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
583/// @code new (memory) int[size][4] @endcode
584/// or
585/// @code ::new Foo(23, "hello") @endcode
586/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000587Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000588Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000589 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000590 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000591 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000592 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000593 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000594 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000595 // If the specified type is an array, unwrap it and save the expression.
596 if (D.getNumTypeObjects() > 0 &&
597 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
598 DeclaratorChunk &Chunk = D.getTypeObject(0);
599 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000600 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
601 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000602 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000603 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
604 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000605
606 if (ParenTypeId) {
607 // Can't have dynamic array size when the type-id is in parentheses.
608 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
609 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
610 !NumElts->isIntegerConstantExpr(Context)) {
611 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
612 << NumElts->getSourceRange();
613 return ExprError();
614 }
615 }
616
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000617 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000618 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000619 }
620
Douglas Gregor043cad22009-09-11 00:18:58 +0000621 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000622 if (ArraySize) {
623 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000624 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
625 break;
626
627 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
628 if (Expr *NumElts = (Expr *)Array.NumElts) {
629 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
630 !NumElts->isIntegerConstantExpr(Context)) {
631 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
632 << NumElts->getSourceRange();
633 return ExprError();
634 }
635 }
636 }
637 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000638
John McCalla93c9342009-12-07 02:54:59 +0000639 //FIXME: Store TypeSourceInfo in CXXNew expression.
640 TypeSourceInfo *TInfo = 0;
641 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000642 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000643 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000644
Mike Stump1eb44332009-09-09 15:08:12 +0000645 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000646 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000647 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000648 PlacementRParen,
649 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000650 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000651 D.getSourceRange().getBegin(),
652 D.getSourceRange(),
653 Owned(ArraySize),
654 ConstructorLParen,
655 move(ConstructorArgs),
656 ConstructorRParen);
657}
658
Mike Stump1eb44332009-09-09 15:08:12 +0000659Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000660Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
661 SourceLocation PlacementLParen,
662 MultiExprArg PlacementArgs,
663 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000664 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000665 QualType AllocType,
666 SourceLocation TypeLoc,
667 SourceRange TypeRange,
668 ExprArg ArraySizeE,
669 SourceLocation ConstructorLParen,
670 MultiExprArg ConstructorArgs,
671 SourceLocation ConstructorRParen) {
672 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000673 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000674
Douglas Gregor3433cf72009-05-21 00:00:09 +0000675 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000676
677 // That every array dimension except the first is constant was already
678 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000679
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000680 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
681 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000682 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000683 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000684 QualType SizeType = ArraySize->getType();
685 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000686 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
687 diag::err_array_size_not_integral)
688 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000689 // Let's see if this is a constant < 0. If so, we reject it out of hand.
690 // We don't care about special rules, so we tell the machinery it's not
691 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000692 if (!ArraySize->isValueDependent()) {
693 llvm::APSInt Value;
694 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
695 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000696 llvm::APInt::getNullValue(Value.getBitWidth()),
697 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000698 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
699 diag::err_typecheck_negative_array_size)
700 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000701 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000702 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000703
Eli Friedman73c39ab2009-10-20 08:27:19 +0000704 ImpCastExprToType(ArraySize, Context.getSizeType(),
705 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000706 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000707
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000708 FunctionDecl *OperatorNew = 0;
709 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000710 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
711 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000712
Sebastian Redl28507842009-02-26 14:39:58 +0000713 if (!AllocType->isDependentType() &&
714 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
715 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000716 SourceRange(PlacementLParen, PlacementRParen),
717 UseGlobal, AllocType, ArraySize, PlaceArgs,
718 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000719 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000720 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000721 if (OperatorNew) {
722 // Add default arguments, if any.
723 const FunctionProtoType *Proto =
724 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000725 VariadicCallType CallType =
726 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000727 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
728 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000729 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000730 if (Invalid)
731 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000732
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000733 NumPlaceArgs = AllPlaceArgs.size();
734 if (NumPlaceArgs > 0)
735 PlaceArgs = &AllPlaceArgs[0];
736 }
737
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000738 bool Init = ConstructorLParen.isValid();
739 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000740 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000741 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
742 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000743 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
744
Douglas Gregor99a2e602009-12-16 01:38:02 +0000745 if (!AllocType->isDependentType() &&
746 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
747 // C++0x [expr.new]p15:
748 // A new-expression that creates an object of type T initializes that
749 // object as follows:
750 InitializationKind Kind
751 // - If the new-initializer is omitted, the object is default-
752 // initialized (8.5); if no initialization is performed,
753 // the object has indeterminate value
754 = !Init? InitializationKind::CreateDefault(TypeLoc)
755 // - Otherwise, the new-initializer is interpreted according to the
756 // initialization rules of 8.5 for direct-initialization.
757 : InitializationKind::CreateDirect(TypeLoc,
758 ConstructorLParen,
759 ConstructorRParen);
760
Douglas Gregor99a2e602009-12-16 01:38:02 +0000761 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000762 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000763 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000764 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
765 move(ConstructorArgs));
766 if (FullInit.isInvalid())
767 return ExprError();
768
769 // FullInit is our initializer; walk through it to determine if it's a
770 // constructor call, which CXXNewExpr handles directly.
771 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
772 if (CXXBindTemporaryExpr *Binder
773 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
774 FullInitExpr = Binder->getSubExpr();
775 if (CXXConstructExpr *Construct
776 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
777 Constructor = Construct->getConstructor();
778 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
779 AEnd = Construct->arg_end();
780 A != AEnd; ++A)
781 ConvertedConstructorArgs.push_back(A->Retain());
782 } else {
783 // Take the converted initializer.
784 ConvertedConstructorArgs.push_back(FullInit.release());
785 }
786 } else {
787 // No initialization required.
788 }
789
790 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000791 NumConsArgs = ConvertedConstructorArgs.size();
792 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000793 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000794
Douglas Gregor6d908702010-02-26 05:06:18 +0000795 // Mark the new and delete operators as referenced.
796 if (OperatorNew)
797 MarkDeclarationReferenced(StartLoc, OperatorNew);
798 if (OperatorDelete)
799 MarkDeclarationReferenced(StartLoc, OperatorDelete);
800
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000801 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000802
Sebastian Redlf53597f2009-03-15 17:47:39 +0000803 PlacementArgs.release();
804 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000805 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000806 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
807 PlaceArgs, NumPlaceArgs, ParenTypeId,
808 ArraySize, Constructor, Init,
809 ConsArgs, NumConsArgs, OperatorDelete,
810 ResultType, StartLoc,
811 Init ? ConstructorRParen :
812 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000813}
814
815/// CheckAllocatedType - Checks that a type is suitable as the allocated type
816/// in a new-expression.
817/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000818bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000819 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000820 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
821 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000822 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000823 return Diag(Loc, diag::err_bad_new_type)
824 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000825 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000826 return Diag(Loc, diag::err_bad_new_type)
827 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000828 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000829 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000830 PDiag(diag::err_new_incomplete_type)
831 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000832 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000833 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000834 diag::err_allocation_of_abstract_type))
835 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000836
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000837 return false;
838}
839
Douglas Gregor6d908702010-02-26 05:06:18 +0000840/// \brief Determine whether the given function is a non-placement
841/// deallocation function.
842static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
843 if (FD->isInvalidDecl())
844 return false;
845
846 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
847 return Method->isUsualDeallocationFunction();
848
849 return ((FD->getOverloadedOperator() == OO_Delete ||
850 FD->getOverloadedOperator() == OO_Array_Delete) &&
851 FD->getNumParams() == 1);
852}
853
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000854/// FindAllocationFunctions - Finds the overloads of operator new and delete
855/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000856bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
857 bool UseGlobal, QualType AllocType,
858 bool IsArray, Expr **PlaceArgs,
859 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000860 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000861 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000862 // --- Choosing an allocation function ---
863 // C++ 5.3.4p8 - 14 & 18
864 // 1) If UseGlobal is true, only look in the global scope. Else, also look
865 // in the scope of the allocated class.
866 // 2) If an array size is given, look for operator new[], else look for
867 // operator new.
868 // 3) The first argument is always size_t. Append the arguments from the
869 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000870
871 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
872 // We don't care about the actual value of this argument.
873 // FIXME: Should the Sema create the expression and embed it in the syntax
874 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000875 IntegerLiteral Size(llvm::APInt::getNullValue(
876 Context.Target.getPointerWidth(0)),
877 Context.getSizeType(),
878 SourceLocation());
879 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000880 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
881
Douglas Gregor6d908702010-02-26 05:06:18 +0000882 // C++ [expr.new]p8:
883 // If the allocated type is a non-array type, the allocation
884 // function’s name is operator new and the deallocation function’s
885 // name is operator delete. If the allocated type is an array
886 // type, the allocation function’s name is operator new[] and the
887 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000888 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
889 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000890 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
891 IsArray ? OO_Array_Delete : OO_Delete);
892
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000893 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000894 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000895 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000896 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000897 AllocArgs.size(), Record, /*AllowMissing=*/true,
898 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000899 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000900 }
901 if (!OperatorNew) {
902 // Didn't find a member overload. Look for a global one.
903 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000904 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000905 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000906 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
907 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000908 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000909 }
910
Anders Carlssond9583892009-05-31 20:26:12 +0000911 // FindAllocationOverload can change the passed in arguments, so we need to
912 // copy them back.
913 if (NumPlaceArgs > 0)
914 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregor6d908702010-02-26 05:06:18 +0000916 // C++ [expr.new]p19:
917 //
918 // If the new-expression begins with a unary :: operator, the
919 // deallocation function’s name is looked up in the global
920 // scope. Otherwise, if the allocated type is a class type T or an
921 // array thereof, the deallocation function’s name is looked up in
922 // the scope of T. If this lookup fails to find the name, or if
923 // the allocated type is not a class type or array thereof, the
924 // deallocation function’s name is looked up in the global scope.
925 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
926 if (AllocType->isRecordType() && !UseGlobal) {
927 CXXRecordDecl *RD
928 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
929 LookupQualifiedName(FoundDelete, RD);
930 }
931
932 if (FoundDelete.empty()) {
933 DeclareGlobalNewDelete();
934 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
935 }
936
937 FoundDelete.suppressDiagnostics();
938 llvm::SmallVector<NamedDecl *, 4> Matches;
939 if (NumPlaceArgs > 1) {
940 // C++ [expr.new]p20:
941 // A declaration of a placement deallocation function matches the
942 // declaration of a placement allocation function if it has the
943 // same number of parameters and, after parameter transformations
944 // (8.3.5), all parameter types except the first are
945 // identical. [...]
946 //
947 // To perform this comparison, we compute the function type that
948 // the deallocation function should have, and use that type both
949 // for template argument deduction and for comparison purposes.
950 QualType ExpectedFunctionType;
951 {
952 const FunctionProtoType *Proto
953 = OperatorNew->getType()->getAs<FunctionProtoType>();
954 llvm::SmallVector<QualType, 4> ArgTypes;
955 ArgTypes.push_back(Context.VoidPtrTy);
956 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
957 ArgTypes.push_back(Proto->getArgType(I));
958
959 ExpectedFunctionType
960 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
961 ArgTypes.size(),
962 Proto->isVariadic(),
963 0, false, false, 0, 0, false, CC_Default);
964 }
965
966 for (LookupResult::iterator D = FoundDelete.begin(),
967 DEnd = FoundDelete.end();
968 D != DEnd; ++D) {
969 FunctionDecl *Fn = 0;
970 if (FunctionTemplateDecl *FnTmpl
971 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
972 // Perform template argument deduction to try to match the
973 // expected function type.
974 TemplateDeductionInfo Info(Context, StartLoc);
975 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
976 continue;
977 } else
978 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
979
980 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
981 Matches.push_back(Fn);
982 }
983 } else {
984 // C++ [expr.new]p20:
985 // [...] Any non-placement deallocation function matches a
986 // non-placement allocation function. [...]
987 for (LookupResult::iterator D = FoundDelete.begin(),
988 DEnd = FoundDelete.end();
989 D != DEnd; ++D) {
990 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
991 if (isNonPlacementDeallocationFunction(Fn))
992 Matches.push_back(*D);
993 }
994 }
995
996 // C++ [expr.new]p20:
997 // [...] If the lookup finds a single matching deallocation
998 // function, that function will be called; otherwise, no
999 // deallocation function will be called.
1000 if (Matches.size() == 1) {
1001 // FIXME: Drops access, using-declaration info!
1002 OperatorDelete = cast<FunctionDecl>(Matches[0]->getUnderlyingDecl());
1003
1004 // C++0x [expr.new]p20:
1005 // If the lookup finds the two-parameter form of a usual
1006 // deallocation function (3.7.4.2) and that function, considered
1007 // as a placement deallocation function, would have been
1008 // selected as a match for the allocation function, the program
1009 // is ill-formed.
1010 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1011 isNonPlacementDeallocationFunction(OperatorDelete)) {
1012 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1013 << SourceRange(PlaceArgs[0]->getLocStart(),
1014 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1015 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1016 << DeleteName;
1017 }
1018 }
1019
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001020 return false;
1021}
1022
Sebastian Redl7f662392008-12-04 22:20:51 +00001023/// FindAllocationOverload - Find an fitting overload for the allocation
1024/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001025bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1026 DeclarationName Name, Expr** Args,
1027 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001028 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001029 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1030 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001031 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001032 if (AllowMissing)
1033 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001034 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001035 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001036 }
1037
John McCallf36e02d2009-10-09 21:13:30 +00001038 // FIXME: handle ambiguity
1039
John McCall5769d612010-02-08 23:07:23 +00001040 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001041 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1042 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001043 // Even member operator new/delete are implicitly treated as
1044 // static, so don't use AddMemberCandidate.
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001045
1046 if (FunctionTemplateDecl *FnTemplate =
1047 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
1048 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
1049 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1050 Candidates,
1051 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001052 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001053 }
1054
1055 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
1056 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
1057 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001058 }
1059
1060 // Do the resolution.
1061 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001062 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001063 case OR_Success: {
1064 // Got one!
1065 FunctionDecl *FnDecl = Best->Function;
1066 // The first argument is size_t, and the first parameter must be size_t,
1067 // too. This is checked on declaration and can be assumed. (It can't be
1068 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001069 // Whatch out for variadic allocator function.
1070 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1071 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +00001072 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +00001073 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001074 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +00001075 return true;
1076 }
1077 Operator = FnDecl;
1078 return false;
1079 }
1080
1081 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001082 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001083 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001084 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001085 return true;
1086
1087 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001088 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001089 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001090 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001091 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001092
1093 case OR_Deleted:
1094 Diag(StartLoc, diag::err_ovl_deleted_call)
1095 << Best->Function->isDeleted()
1096 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001097 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001098 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001099 }
1100 assert(false && "Unreachable, bad result from BestViableFunction");
1101 return true;
1102}
1103
1104
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001105/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1106/// delete. These are:
1107/// @code
1108/// void* operator new(std::size_t) throw(std::bad_alloc);
1109/// void* operator new[](std::size_t) throw(std::bad_alloc);
1110/// void operator delete(void *) throw();
1111/// void operator delete[](void *) throw();
1112/// @endcode
1113/// Note that the placement and nothrow forms of new are *not* implicitly
1114/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001115void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001116 if (GlobalNewDeleteDeclared)
1117 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001118
1119 // C++ [basic.std.dynamic]p2:
1120 // [...] The following allocation and deallocation functions (18.4) are
1121 // implicitly declared in global scope in each translation unit of a
1122 // program
1123 //
1124 // void* operator new(std::size_t) throw(std::bad_alloc);
1125 // void* operator new[](std::size_t) throw(std::bad_alloc);
1126 // void operator delete(void*) throw();
1127 // void operator delete[](void*) throw();
1128 //
1129 // These implicit declarations introduce only the function names operator
1130 // new, operator new[], operator delete, operator delete[].
1131 //
1132 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1133 // "std" or "bad_alloc" as necessary to form the exception specification.
1134 // However, we do not make these implicit declarations visible to name
1135 // lookup.
1136 if (!StdNamespace) {
1137 // The "std" namespace has not yet been defined, so build one implicitly.
1138 StdNamespace = NamespaceDecl::Create(Context,
1139 Context.getTranslationUnitDecl(),
1140 SourceLocation(),
1141 &PP.getIdentifierTable().get("std"));
1142 StdNamespace->setImplicit(true);
1143 }
1144
1145 if (!StdBadAlloc) {
1146 // The "std::bad_alloc" class has not yet been declared, so build it
1147 // implicitly.
1148 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1149 StdNamespace,
1150 SourceLocation(),
1151 &PP.getIdentifierTable().get("bad_alloc"),
1152 SourceLocation(), 0);
1153 StdBadAlloc->setImplicit(true);
1154 }
1155
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001156 GlobalNewDeleteDeclared = true;
1157
1158 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1159 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001160 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001161
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001162 DeclareGlobalAllocationFunction(
1163 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001164 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001165 DeclareGlobalAllocationFunction(
1166 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001167 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001168 DeclareGlobalAllocationFunction(
1169 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1170 Context.VoidTy, VoidPtr);
1171 DeclareGlobalAllocationFunction(
1172 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1173 Context.VoidTy, VoidPtr);
1174}
1175
1176/// DeclareGlobalAllocationFunction - Declares a single implicit global
1177/// allocation function if it doesn't already exist.
1178void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001179 QualType Return, QualType Argument,
1180 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001181 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1182
1183 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001184 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001185 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001186 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001187 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001188 // Only look at non-template functions, as it is the predefined,
1189 // non-templated allocation function we are trying to declare here.
1190 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1191 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001192 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001193 Func->getParamDecl(0)->getType().getUnqualifiedType());
1194 // FIXME: Do we need to check for default arguments here?
1195 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1196 return;
1197 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001198 }
1199 }
1200
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001201 QualType BadAllocType;
1202 bool HasBadAllocExceptionSpec
1203 = (Name.getCXXOverloadedOperator() == OO_New ||
1204 Name.getCXXOverloadedOperator() == OO_Array_New);
1205 if (HasBadAllocExceptionSpec) {
1206 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1207 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1208 }
1209
1210 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1211 true, false,
1212 HasBadAllocExceptionSpec? 1 : 0,
Douglas Gregorce056bc2010-02-21 22:15:06 +00001213 &BadAllocType, false, CC_Default);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001214 FunctionDecl *Alloc =
1215 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +00001216 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001217 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001218
1219 if (AddMallocAttr)
1220 Alloc->addAttr(::new (Context) MallocAttr());
1221
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001222 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001223 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001224 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001225 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001226
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001227 // FIXME: Also add this declaration to the IdentifierResolver, but
1228 // make sure it is at the end of the chain to coincide with the
1229 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001230 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001231}
1232
Anders Carlsson78f74552009-11-15 18:45:20 +00001233bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1234 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001235 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001236 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001237 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001238 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001239
John McCalla24dc2e2009-11-17 02:14:36 +00001240 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001241 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001242
1243 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1244 F != FEnd; ++F) {
1245 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1246 if (Delete->isUsualDeallocationFunction()) {
1247 Operator = Delete;
1248 return false;
1249 }
1250 }
1251
1252 // We did find operator delete/operator delete[] declarations, but
1253 // none of them were suitable.
1254 if (!Found.empty()) {
1255 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1256 << Name << RD;
1257
1258 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1259 F != FEnd; ++F) {
1260 Diag((*F)->getLocation(),
1261 diag::note_delete_member_function_declared_here)
1262 << Name;
1263 }
1264
1265 return true;
1266 }
1267
1268 // Look for a global declaration.
1269 DeclareGlobalNewDelete();
1270 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1271
1272 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1273 Expr* DeallocArgs[1];
1274 DeallocArgs[0] = &Null;
1275 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1276 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1277 Operator))
1278 return true;
1279
1280 assert(Operator && "Did not find a deallocation function!");
1281 return false;
1282}
1283
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001284/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1285/// @code ::delete ptr; @endcode
1286/// or
1287/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001288Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001289Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001290 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001291 // C++ [expr.delete]p1:
1292 // The operand shall have a pointer type, or a class type having a single
1293 // conversion function to a pointer type. The result has type void.
1294 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001295 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1296
Anders Carlssond67c4c32009-08-16 20:29:29 +00001297 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Sebastian Redlf53597f2009-03-15 17:47:39 +00001299 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001300 if (!Ex->isTypeDependent()) {
1301 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001302
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001303 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001304 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +00001305 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00001306 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001307
John McCalleec51cf2010-01-20 00:46:10 +00001308 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001309 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001310 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +00001311 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001312 continue;
1313
John McCallba135432009-11-21 08:51:07 +00001314 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001315
1316 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1317 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1318 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001319 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001320 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001321 if (ObjectPtrConversions.size() == 1) {
1322 // We have a single conversion to a pointer-to-object type. Perform
1323 // that conversion.
1324 Operand.release();
1325 if (!PerformImplicitConversion(Ex,
1326 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001327 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001328 Operand = Owned(Ex);
1329 Type = Ex->getType();
1330 }
1331 }
1332 else if (ObjectPtrConversions.size() > 1) {
1333 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1334 << Type << Ex->getSourceRange();
1335 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1336 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +00001337 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001338 }
1339 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001340 }
Sebastian Redl28507842009-02-26 14:39:58 +00001341 }
1342
Sebastian Redlf53597f2009-03-15 17:47:39 +00001343 if (!Type->isPointerType())
1344 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1345 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001346
Ted Kremenek6217b802009-07-29 21:53:49 +00001347 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001348 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001349 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1350 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001351 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001352 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001353 PDiag(diag::warn_delete_incomplete)
1354 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001355 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001356
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001357 // C++ [expr.delete]p2:
1358 // [Note: a pointer to a const type can be the operand of a
1359 // delete-expression; it is not necessary to cast away the constness
1360 // (5.2.11) of the pointer expression before it is used as the operand
1361 // of the delete-expression. ]
1362 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1363 CastExpr::CK_NoOp);
1364
1365 // Update the operand.
1366 Operand.take();
1367 Operand = ExprArg(*this, Ex);
1368
Anders Carlssond67c4c32009-08-16 20:29:29 +00001369 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1370 ArrayForm ? OO_Array_Delete : OO_Delete);
1371
Anders Carlsson78f74552009-11-15 18:45:20 +00001372 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1373 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1374
1375 if (!UseGlobal &&
1376 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001377 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001378
Anders Carlsson78f74552009-11-15 18:45:20 +00001379 if (!RD->hasTrivialDestructor())
1380 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001381 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001382 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001383 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001384
Anders Carlssond67c4c32009-08-16 20:29:29 +00001385 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001386 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001387 DeclareGlobalNewDelete();
1388 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001389 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001390 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001391 OperatorDelete))
1392 return ExprError();
1393 }
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Sebastian Redl28507842009-02-26 14:39:58 +00001395 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001396 }
1397
Sebastian Redlf53597f2009-03-15 17:47:39 +00001398 Operand.release();
1399 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001400 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001401}
1402
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001403/// \brief Check the use of the given variable as a C++ condition in an if,
1404/// while, do-while, or switch statement.
1405Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1406 QualType T = ConditionVar->getType();
1407
1408 // C++ [stmt.select]p2:
1409 // The declarator shall not specify a function or an array.
1410 if (T->isFunctionType())
1411 return ExprError(Diag(ConditionVar->getLocation(),
1412 diag::err_invalid_use_of_function_type)
1413 << ConditionVar->getSourceRange());
1414 else if (T->isArrayType())
1415 return ExprError(Diag(ConditionVar->getLocation(),
1416 diag::err_invalid_use_of_array_type)
1417 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001418
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001419 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1420 ConditionVar->getLocation(),
1421 ConditionVar->getType().getNonReferenceType()));
1422}
1423
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001424/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1425bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1426 // C++ 6.4p4:
1427 // The value of a condition that is an initialized declaration in a statement
1428 // other than a switch statement is the value of the declared variable
1429 // implicitly converted to type bool. If that conversion is ill-formed, the
1430 // program is ill-formed.
1431 // The value of a condition that is an expression is the value of the
1432 // expression, implicitly converted to bool.
1433 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001434 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001435}
Douglas Gregor77a52232008-09-12 00:47:35 +00001436
1437/// Helper function to determine whether this is the (deprecated) C++
1438/// conversion from a string literal to a pointer to non-const char or
1439/// non-const wchar_t (for narrow and wide string literals,
1440/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001441bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001442Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1443 // Look inside the implicit cast, if it exists.
1444 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1445 From = Cast->getSubExpr();
1446
1447 // A string literal (2.13.4) that is not a wide string literal can
1448 // be converted to an rvalue of type "pointer to char"; a wide
1449 // string literal can be converted to an rvalue of type "pointer
1450 // to wchar_t" (C++ 4.2p2).
1451 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001452 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001453 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001454 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001455 // This conversion is considered only when there is an
1456 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001457 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001458 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1459 (!StrLit->isWide() &&
1460 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1461 ToPointeeType->getKind() == BuiltinType::Char_S))))
1462 return true;
1463 }
1464
1465 return false;
1466}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001467
1468/// PerformImplicitConversion - Perform an implicit conversion of the
1469/// expression From to the type ToType. Returns true if there was an
1470/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001471/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001472/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001473/// explicit user-defined conversions are permitted. @p Elidable should be true
1474/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1475/// resolution works differently in that case.
1476bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001477Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001478 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001479 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001480 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001481 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001482 Elidable, ICS);
1483}
1484
1485bool
1486Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001487 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001488 bool Elidable,
1489 ImplicitConversionSequence& ICS) {
John McCallb1bdc622010-02-25 01:37:24 +00001490 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001491 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001492 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001493 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001494 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001495 /*ForceRValue=*/true,
1496 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001497 }
John McCall1d318332010-01-12 00:44:57 +00001498 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001499 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001500 /*SuppressUserConversions=*/false,
1501 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001502 /*ForceRValue=*/false,
1503 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001504 }
Douglas Gregor68647482009-12-16 03:45:30 +00001505 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001506}
1507
1508/// PerformImplicitConversion - Perform an implicit conversion of the
1509/// expression From to the type ToType using the pre-computed implicit
1510/// conversion sequence ICS. Returns true if there was an error, false
1511/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001512/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001513/// used in the error message.
1514bool
1515Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1516 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001517 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001518 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001519 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001520 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001521 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001522 return true;
1523 break;
1524
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001525 case ImplicitConversionSequence::UserDefinedConversion: {
1526
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001527 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1528 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001529 QualType BeforeToType;
1530 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001531 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001532
1533 // If the user-defined conversion is specified by a conversion function,
1534 // the initial standard conversion sequence converts the source type to
1535 // the implicit object parameter of the conversion function.
1536 BeforeToType = Context.getTagDeclType(Conv->getParent());
1537 } else if (const CXXConstructorDecl *Ctor =
1538 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001539 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001540 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001541 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001542 // If the user-defined conversion is specified by a constructor, the
1543 // initial standard conversion sequence converts the source type to the
1544 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001545 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1546 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001547 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001548 else
1549 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001550 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001551 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001552 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001553 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001554 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001555 return true;
1556 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001557
Anders Carlsson0aebc812009-09-09 21:33:21 +00001558 OwningExprResult CastArg
1559 = BuildCXXCastArgument(From->getLocStart(),
1560 ToType.getNonReferenceType(),
1561 CastKind, cast<CXXMethodDecl>(FD),
1562 Owned(From));
1563
1564 if (CastArg.isInvalid())
1565 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001566
1567 From = CastArg.takeAs<Expr>();
1568
Eli Friedmand8889622009-11-27 04:41:50 +00001569 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001570 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001571 }
John McCall1d318332010-01-12 00:44:57 +00001572
1573 case ImplicitConversionSequence::AmbiguousConversion:
1574 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1575 PDiag(diag::err_typecheck_ambiguous_condition)
1576 << From->getSourceRange());
1577 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001578
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001579 case ImplicitConversionSequence::EllipsisConversion:
1580 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001581 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001582
1583 case ImplicitConversionSequence::BadConversion:
1584 return true;
1585 }
1586
1587 // Everything went well.
1588 return false;
1589}
1590
1591/// PerformImplicitConversion - Perform an implicit conversion of the
1592/// expression From to the type ToType by following the standard
1593/// conversion sequence SCS. Returns true if there was an error, false
1594/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001595/// expression. Flavor is the context in which we're performing this
1596/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001597bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001598Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001599 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001600 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001601 // Overall FIXME: we are recomputing too many types here and doing far too
1602 // much extra work. What this means is that we need to keep track of more
1603 // information that is computed when we try the implicit conversion initially,
1604 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001605 QualType FromType = From->getType();
1606
Douglas Gregor225c41e2008-11-03 19:09:14 +00001607 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001608 // FIXME: When can ToType be a reference type?
1609 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001610 if (SCS.Second == ICK_Derived_To_Base) {
1611 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1612 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1613 MultiExprArg(*this, (void **)&From, 1),
1614 /*FIXME:ConstructLoc*/SourceLocation(),
1615 ConstructorArgs))
1616 return true;
1617 OwningExprResult FromResult =
1618 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1619 ToType, SCS.CopyConstructor,
1620 move_arg(ConstructorArgs));
1621 if (FromResult.isInvalid())
1622 return true;
1623 From = FromResult.takeAs<Expr>();
1624 return false;
1625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626 OwningExprResult FromResult =
1627 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1628 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001629 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001631 if (FromResult.isInvalid())
1632 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001634 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001635 return false;
1636 }
1637
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001638 // Perform the first implicit conversion.
1639 switch (SCS.First) {
1640 case ICK_Identity:
1641 case ICK_Lvalue_To_Rvalue:
1642 // Nothing to do.
1643 break;
1644
1645 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001646 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001647 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001648 break;
1649
1650 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001651 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001652 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1653 if (!Fn)
1654 return true;
1655
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001656 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1657 return true;
1658
Anders Carlsson96ad5332009-10-21 17:16:23 +00001659 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001660 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001661
Sebastian Redl759986e2009-10-17 20:50:27 +00001662 // If there's already an address-of operator in the expression, we have
1663 // the right type already, and the code below would just introduce an
1664 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001665 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001666 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001667 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001668 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001669 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001670 break;
1671
1672 default:
1673 assert(false && "Improper first standard conversion");
1674 break;
1675 }
1676
1677 // Perform the second implicit conversion
1678 switch (SCS.Second) {
1679 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001680 // If both sides are functions (or pointers/references to them), there could
1681 // be incompatible exception declarations.
1682 if (CheckExceptionSpecCompatibility(From, ToType))
1683 return true;
1684 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001685 break;
1686
Douglas Gregor43c79c22009-12-09 00:47:37 +00001687 case ICK_NoReturn_Adjustment:
1688 // If both sides are functions (or pointers/references to them), there could
1689 // be incompatible exception declarations.
1690 if (CheckExceptionSpecCompatibility(From, ToType))
1691 return true;
1692
1693 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1694 CastExpr::CK_NoOp);
1695 break;
1696
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001697 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001698 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001699 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1700 break;
1701
1702 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001703 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001704 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1705 break;
1706
1707 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001708 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001709 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1710 break;
1711
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001712 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001713 if (ToType->isFloatingType())
1714 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1715 else
1716 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1717 break;
1718
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001719 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001720 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1721 break;
1722
Douglas Gregorf9201e02009-02-11 23:02:49 +00001723 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001724 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001725 break;
1726
Anders Carlsson61faec12009-09-12 04:46:44 +00001727 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001728 if (SCS.IncompatibleObjC) {
1729 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001730 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001731 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001732 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001733 << From->getSourceRange();
1734 }
1735
Anders Carlsson61faec12009-09-12 04:46:44 +00001736
1737 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001738 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001739 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001740 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001741 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001742 }
1743
1744 case ICK_Pointer_Member: {
1745 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001746 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001747 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001748 if (CheckExceptionSpecCompatibility(From, ToType))
1749 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001750 ImpCastExprToType(From, ToType, Kind);
1751 break;
1752 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001753 case ICK_Boolean_Conversion: {
1754 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1755 if (FromType->isMemberPointerType())
1756 Kind = CastExpr::CK_MemberPointerToBoolean;
1757
1758 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001759 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001760 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001761
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001762 case ICK_Derived_To_Base:
1763 if (CheckDerivedToBaseConversion(From->getType(),
1764 ToType.getNonReferenceType(),
1765 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001766 From->getSourceRange(),
1767 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001768 return true;
1769 ImpCastExprToType(From, ToType.getNonReferenceType(),
1770 CastExpr::CK_DerivedToBase);
1771 break;
1772
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001773 default:
1774 assert(false && "Improper second standard conversion");
1775 break;
1776 }
1777
1778 switch (SCS.Third) {
1779 case ICK_Identity:
1780 // Nothing to do.
1781 break;
1782
1783 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001784 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1785 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001786 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001787 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001788 ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001789
1790 if (SCS.DeprecatedStringLiteralToCharPtr)
1791 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1792 << ToType.getNonReferenceType();
1793
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001794 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001795
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001796 default:
1797 assert(false && "Improper second standard conversion");
1798 break;
1799 }
1800
1801 return false;
1802}
1803
Sebastian Redl64b45f72009-01-05 20:52:13 +00001804Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1805 SourceLocation KWLoc,
1806 SourceLocation LParen,
1807 TypeTy *Ty,
1808 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001809 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001811 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1812 // all traits except __is_class, __is_enum and __is_union require a the type
1813 // to be complete.
1814 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001815 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001816 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001817 return ExprError();
1818 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001819
1820 // There is no point in eagerly computing the value. The traits are designed
1821 // to be used from type trait templates, so Ty will be a template parameter
1822 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001823 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1824 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001825}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001826
1827QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001828 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001829 const char *OpSpelling = isIndirect ? "->*" : ".*";
1830 // C++ 5.5p2
1831 // The binary operator .* [p3: ->*] binds its second operand, which shall
1832 // be of type "pointer to member of T" (where T is a completely-defined
1833 // class type) [...]
1834 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001835 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001836 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001837 Diag(Loc, diag::err_bad_memptr_rhs)
1838 << OpSpelling << RType << rex->getSourceRange();
1839 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001840 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001841
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001842 QualType Class(MemPtr->getClass(), 0);
1843
1844 // C++ 5.5p2
1845 // [...] to its first operand, which shall be of class T or of a class of
1846 // which T is an unambiguous and accessible base class. [p3: a pointer to
1847 // such a class]
1848 QualType LType = lex->getType();
1849 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001850 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001851 LType = Ptr->getPointeeType().getNonReferenceType();
1852 else {
1853 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001854 << OpSpelling << 1 << LType
1855 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001856 return QualType();
1857 }
1858 }
1859
Douglas Gregora4923eb2009-11-16 21:35:15 +00001860 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001861 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1862 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001863 // FIXME: Would it be useful to print full ambiguity paths, or is that
1864 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001865 if (!IsDerivedFrom(LType, Class, Paths) ||
1866 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1867 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001868 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001869 return QualType();
1870 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001871 // Cast LHS to type of use.
1872 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1873 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1874 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001875 }
1876
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001877 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001878 // Diagnose use of pointer-to-member type which when used as
1879 // the functional cast in a pointer-to-member expression.
1880 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1881 return QualType();
1882 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001883 // C++ 5.5p2
1884 // The result is an object or a function of the type specified by the
1885 // second operand.
1886 // The cv qualifiers are the union of those in the pointer and the left side,
1887 // in accordance with 5.5p5 and 5.2.5.
1888 // FIXME: This returns a dereferenced member function pointer as a normal
1889 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001890 // calling them. There's also a GCC extension to get a function pointer to the
1891 // thing, which is another complication, because this type - unlike the type
1892 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001893 // argument.
1894 // We probably need a "MemberFunctionClosureType" or something like that.
1895 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001896 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001897 return Result;
1898}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001899
1900/// \brief Get the target type of a standard or user-defined conversion.
1901static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001902 switch (ICS.getKind()) {
1903 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001904 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001905 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001906 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001907 case ImplicitConversionSequence::AmbiguousConversion:
1908 return ICS.Ambiguous.getToType();
John McCallb1bdc622010-02-25 01:37:24 +00001909
John McCall1d318332010-01-12 00:44:57 +00001910 case ImplicitConversionSequence::EllipsisConversion:
1911 case ImplicitConversionSequence::BadConversion:
1912 llvm_unreachable("function not valid for ellipsis or bad conversions");
1913 }
1914 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001915}
1916
1917/// \brief Try to convert a type to another according to C++0x 5.16p3.
1918///
1919/// This is part of the parameter validation for the ? operator. If either
1920/// value operand is a class type, the two operands are attempted to be
1921/// converted to each other. This function does the conversion in one direction.
1922/// It emits a diagnostic and returns true only if it finds an ambiguous
1923/// conversion.
1924static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1925 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001926 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001927 // C++0x 5.16p3
1928 // The process for determining whether an operand expression E1 of type T1
1929 // can be converted to match an operand expression E2 of type T2 is defined
1930 // as follows:
1931 // -- If E2 is an lvalue:
1932 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1933 // E1 can be converted to match E2 if E1 can be implicitly converted to
1934 // type "lvalue reference to T2", subject to the constraint that in the
1935 // conversion the reference must bind directly to E1.
1936 if (!Self.CheckReferenceInit(From,
1937 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001938 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001939 /*SuppressUserConversions=*/false,
1940 /*AllowExplicit=*/false,
1941 /*ForceRValue=*/false,
1942 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001943 {
John McCall1d318332010-01-12 00:44:57 +00001944 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001945 "expected a definite conversion");
1946 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001947 ICS.isStandard() ? ICS.Standard.DirectBinding
1948 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001949 if (DirectBinding)
1950 return false;
1951 }
1952 }
John McCallb1bdc622010-02-25 01:37:24 +00001953
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001954 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1955 // -- if E1 and E2 have class type, and the underlying class types are
1956 // the same or one is a base class of the other:
1957 QualType FTy = From->getType();
1958 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001959 const RecordType *FRec = FTy->getAs<RecordType>();
1960 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001961 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1962 if (FRec && TRec && (FRec == TRec ||
1963 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1964 // E1 can be converted to match E2 if the class of T2 is the
1965 // same type as, or a base class of, the class of T1, and
1966 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00001967 if (FRec == TRec || FDerivedFromT) {
1968 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
1969 // Could still fail if there's no copy constructor.
1970 // FIXME: Is this a hard error then, or just a conversion failure? The
1971 // standard doesn't say.
1972 ICS = Self.TryCopyInitialization(From, TTy,
1973 /*SuppressUserConversions=*/false,
1974 /*ForceRValue=*/false,
1975 /*InOverloadResolution=*/false);
1976 } else {
1977 ICS.setBad(BadConversionSequence::bad_qualifiers, From, TTy);
1978 }
1979 } else {
1980 // Can't implicitly convert FTy to a derived class TTy.
1981 // TODO: more specific error for this.
1982 ICS.setBad(BadConversionSequence::no_conversion, From, TTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001983 }
1984 } else {
1985 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1986 // implicitly converted to the type that expression E2 would have
1987 // if E2 were converted to an rvalue.
1988 // First find the decayed type.
1989 if (TTy->isFunctionType())
1990 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001991 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001992 TTy = Self.Context.getArrayDecayedType(TTy);
1993
1994 // Now try the implicit conversion.
1995 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001996 ICS = Self.TryImplicitConversion(From, TTy,
1997 /*SuppressUserConversions=*/false,
1998 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001999 /*ForceRValue=*/false,
2000 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002001 }
2002 return false;
2003}
2004
2005/// \brief Try to find a common type for two according to C++0x 5.16p5.
2006///
2007/// This is part of the parameter validation for the ? operator. If either
2008/// value operand is a class type, overload resolution is used to find a
2009/// conversion to a common type.
2010static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2011 SourceLocation Loc) {
2012 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002013 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002014 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002015
2016 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002017 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002018 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002019 // We found a match. Perform the conversions on the arguments and move on.
2020 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002021 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002022 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002023 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002024 break;
2025 return false;
2026
Douglas Gregor20093b42009-12-09 23:02:17 +00002027 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002028 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2029 << LHS->getType() << RHS->getType()
2030 << LHS->getSourceRange() << RHS->getSourceRange();
2031 return true;
2032
Douglas Gregor20093b42009-12-09 23:02:17 +00002033 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002034 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2035 << LHS->getType() << RHS->getType()
2036 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002037 // FIXME: Print the possible common types by printing the return types of
2038 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002039 break;
2040
Douglas Gregor20093b42009-12-09 23:02:17 +00002041 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002042 assert(false && "Conditional operator has only built-in overloads");
2043 break;
2044 }
2045 return true;
2046}
2047
Sebastian Redl76458502009-04-17 16:30:52 +00002048/// \brief Perform an "extended" implicit conversion as returned by
2049/// TryClassUnification.
2050///
2051/// TryClassUnification generates ICSs that include reference bindings.
2052/// PerformImplicitConversion is not suitable for this; it chokes if the
2053/// second part of a standard conversion is ICK_DerivedToBase. This function
2054/// handles the reference binding specially.
2055static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00002056 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00002057 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00002058 assert(ICS.Standard.DirectBinding &&
2059 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00002060 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
2061 // redoing all the work.
2062 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002063 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00002064 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002065 /*SuppressUserConversions=*/false,
2066 /*AllowExplicit=*/false,
2067 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00002068 }
John McCall1d318332010-01-12 00:44:57 +00002069 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00002070 assert(ICS.UserDefined.After.DirectBinding &&
2071 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00002072 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002073 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00002074 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002075 /*SuppressUserConversions=*/false,
2076 /*AllowExplicit=*/false,
2077 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00002078 }
Douglas Gregor68647482009-12-16 03:45:30 +00002079 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00002080 return true;
2081 return false;
2082}
2083
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002084/// \brief Check the operands of ?: under C++ semantics.
2085///
2086/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2087/// extension. In this case, LHS == Cond. (But they're not aliases.)
2088QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2089 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002090 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2091 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002092
2093 // C++0x 5.16p1
2094 // The first expression is contextually converted to bool.
2095 if (!Cond->isTypeDependent()) {
2096 if (CheckCXXBooleanCondition(Cond))
2097 return QualType();
2098 }
2099
2100 // Either of the arguments dependent?
2101 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2102 return Context.DependentTy;
2103
John McCallb13c87f2009-11-05 09:23:39 +00002104 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
2105
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002106 // C++0x 5.16p2
2107 // If either the second or the third operand has type (cv) void, ...
2108 QualType LTy = LHS->getType();
2109 QualType RTy = RHS->getType();
2110 bool LVoid = LTy->isVoidType();
2111 bool RVoid = RTy->isVoidType();
2112 if (LVoid || RVoid) {
2113 // ... then the [l2r] conversions are performed on the second and third
2114 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002115 DefaultFunctionArrayLvalueConversion(LHS);
2116 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002117 LTy = LHS->getType();
2118 RTy = RHS->getType();
2119
2120 // ... and one of the following shall hold:
2121 // -- The second or the third operand (but not both) is a throw-
2122 // expression; the result is of the type of the other and is an rvalue.
2123 bool LThrow = isa<CXXThrowExpr>(LHS);
2124 bool RThrow = isa<CXXThrowExpr>(RHS);
2125 if (LThrow && !RThrow)
2126 return RTy;
2127 if (RThrow && !LThrow)
2128 return LTy;
2129
2130 // -- Both the second and third operands have type void; the result is of
2131 // type void and is an rvalue.
2132 if (LVoid && RVoid)
2133 return Context.VoidTy;
2134
2135 // Neither holds, error.
2136 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2137 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2138 << LHS->getSourceRange() << RHS->getSourceRange();
2139 return QualType();
2140 }
2141
2142 // Neither is void.
2143
2144 // C++0x 5.16p3
2145 // Otherwise, if the second and third operand have different types, and
2146 // either has (cv) class type, and attempt is made to convert each of those
2147 // operands to the other.
2148 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
2149 (LTy->isRecordType() || RTy->isRecordType())) {
2150 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2151 // These return true if a single direction is already ambiguous.
2152 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
2153 return QualType();
2154 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
2155 return QualType();
2156
John McCall1d318332010-01-12 00:44:57 +00002157 bool HaveL2R = !ICSLeftToRight.isBad();
2158 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002159 // If both can be converted, [...] the program is ill-formed.
2160 if (HaveL2R && HaveR2L) {
2161 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2162 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2163 return QualType();
2164 }
2165
2166 // If exactly one conversion is possible, that conversion is applied to
2167 // the chosen operand and the converted operands are used in place of the
2168 // original operands for the remainder of this section.
2169 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00002170 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002171 return QualType();
2172 LTy = LHS->getType();
2173 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00002174 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002175 return QualType();
2176 RTy = RHS->getType();
2177 }
2178 }
2179
2180 // C++0x 5.16p4
2181 // If the second and third operands are lvalues and have the same type,
2182 // the result is of that type [...]
2183 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
2184 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2185 RHS->isLvalue(Context) == Expr::LV_Valid)
2186 return LTy;
2187
2188 // C++0x 5.16p5
2189 // Otherwise, the result is an rvalue. If the second and third operands
2190 // do not have the same type, and either has (cv) class type, ...
2191 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2192 // ... overload resolution is used to determine the conversions (if any)
2193 // to be applied to the operands. If the overload resolution fails, the
2194 // program is ill-formed.
2195 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2196 return QualType();
2197 }
2198
2199 // C++0x 5.16p6
2200 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2201 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002202 DefaultFunctionArrayLvalueConversion(LHS);
2203 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002204 LTy = LHS->getType();
2205 RTy = RHS->getType();
2206
2207 // After those conversions, one of the following shall hold:
2208 // -- The second and third operands have the same type; the result
2209 // is of that type.
2210 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2211 return LTy;
2212
2213 // -- The second and third operands have arithmetic or enumeration type;
2214 // the usual arithmetic conversions are performed to bring them to a
2215 // common type, and the result is of that type.
2216 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2217 UsualArithmeticConversions(LHS, RHS);
2218 return LHS->getType();
2219 }
2220
2221 // -- The second and third operands have pointer type, or one has pointer
2222 // type and the other is a null pointer constant; pointer conversions
2223 // and qualification conversions are performed to bring them to their
2224 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002225 // -- The second and third operands have pointer to member type, or one has
2226 // pointer to member type and the other is a null pointer constant;
2227 // pointer to member conversions and qualification conversions are
2228 // performed to bring them to a common type, whose cv-qualification
2229 // shall match the cv-qualification of either the second or the third
2230 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002231 bool NonStandardCompositeType = false;
2232 QualType Composite = FindCompositePointerType(LHS, RHS,
2233 isSFINAEContext()? 0 : &NonStandardCompositeType);
2234 if (!Composite.isNull()) {
2235 if (NonStandardCompositeType)
2236 Diag(QuestionLoc,
2237 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2238 << LTy << RTy << Composite
2239 << LHS->getSourceRange() << RHS->getSourceRange();
2240
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002241 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002242 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002243
2244 // Similarly, attempt to find composite type of twp objective-c pointers.
2245 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2246 if (!Composite.isNull())
2247 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002248
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002249 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2250 << LHS->getType() << RHS->getType()
2251 << LHS->getSourceRange() << RHS->getSourceRange();
2252 return QualType();
2253}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002254
2255/// \brief Find a merged pointer type and convert the two expressions to it.
2256///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002257/// This finds the composite pointer type (or member pointer type) for @p E1
2258/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2259/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002260/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002261///
2262/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2263/// a non-standard (but still sane) composite type to which both expressions
2264/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2265/// will be set true.
2266QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2,
2267 bool *NonStandardCompositeType) {
2268 if (NonStandardCompositeType)
2269 *NonStandardCompositeType = false;
2270
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002271 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2272 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002274 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2275 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002276 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002277
2278 // C++0x 5.9p2
2279 // Pointer conversions and qualification conversions are performed on
2280 // pointer operands to bring them to their composite pointer type. If
2281 // one operand is a null pointer constant, the composite pointer type is
2282 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002283 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002284 if (T2->isMemberPointerType())
2285 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2286 else
2287 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002288 return T2;
2289 }
Douglas Gregorce940492009-09-25 04:25:58 +00002290 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002291 if (T1->isMemberPointerType())
2292 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2293 else
2294 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002295 return T1;
2296 }
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Douglas Gregor20b3e992009-08-24 17:42:35 +00002298 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002299 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2300 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002301 return QualType();
2302
2303 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2304 // the other has type "pointer to cv2 T" and the composite pointer type is
2305 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2306 // Otherwise, the composite pointer type is a pointer type similar to the
2307 // type of one of the operands, with a cv-qualification signature that is
2308 // the union of the cv-qualification signatures of the operand types.
2309 // In practice, the first part here is redundant; it's subsumed by the second.
2310 // What we do here is, we build the two possible composite types, and try the
2311 // conversions in both directions. If only one works, or if the two composite
2312 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002313 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002314 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2315 QualifierVector QualifierUnion;
2316 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2317 ContainingClassVector;
2318 ContainingClassVector MemberOfClass;
2319 QualType Composite1 = Context.getCanonicalType(T1),
2320 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002321 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002322 do {
2323 const PointerType *Ptr1, *Ptr2;
2324 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2325 (Ptr2 = Composite2->getAs<PointerType>())) {
2326 Composite1 = Ptr1->getPointeeType();
2327 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002328
2329 // If we're allowed to create a non-standard composite type, keep track
2330 // of where we need to fill in additional 'const' qualifiers.
2331 if (NonStandardCompositeType &&
2332 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2333 NeedConstBefore = QualifierUnion.size();
2334
Douglas Gregor20b3e992009-08-24 17:42:35 +00002335 QualifierUnion.push_back(
2336 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2337 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2338 continue;
2339 }
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Douglas Gregor20b3e992009-08-24 17:42:35 +00002341 const MemberPointerType *MemPtr1, *MemPtr2;
2342 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2343 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2344 Composite1 = MemPtr1->getPointeeType();
2345 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002346
2347 // If we're allowed to create a non-standard composite type, keep track
2348 // of where we need to fill in additional 'const' qualifiers.
2349 if (NonStandardCompositeType &&
2350 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2351 NeedConstBefore = QualifierUnion.size();
2352
Douglas Gregor20b3e992009-08-24 17:42:35 +00002353 QualifierUnion.push_back(
2354 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2355 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2356 MemPtr2->getClass()));
2357 continue;
2358 }
Mike Stump1eb44332009-09-09 15:08:12 +00002359
Douglas Gregor20b3e992009-08-24 17:42:35 +00002360 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregor20b3e992009-08-24 17:42:35 +00002362 // Cannot unwrap any more types.
2363 break;
2364 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002366 if (NeedConstBefore && NonStandardCompositeType) {
2367 // Extension: Add 'const' to qualifiers that come before the first qualifier
2368 // mismatch, so that our (non-standard!) composite type meets the
2369 // requirements of C++ [conv.qual]p4 bullet 3.
2370 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2371 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2372 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2373 *NonStandardCompositeType = true;
2374 }
2375 }
2376 }
2377
Douglas Gregor20b3e992009-08-24 17:42:35 +00002378 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002379 ContainingClassVector::reverse_iterator MOC
2380 = MemberOfClass.rbegin();
2381 for (QualifierVector::reverse_iterator
2382 I = QualifierUnion.rbegin(),
2383 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002384 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002385 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002386 if (MOC->first && MOC->second) {
2387 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002388 Composite1 = Context.getMemberPointerType(
2389 Context.getQualifiedType(Composite1, Quals),
2390 MOC->first);
2391 Composite2 = Context.getMemberPointerType(
2392 Context.getQualifiedType(Composite2, Quals),
2393 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002394 } else {
2395 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002396 Composite1
2397 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2398 Composite2
2399 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002400 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002401 }
2402
Mike Stump1eb44332009-09-09 15:08:12 +00002403 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002404 TryImplicitConversion(E1, Composite1,
2405 /*SuppressUserConversions=*/false,
2406 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002407 /*ForceRValue=*/false,
2408 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002409 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002410 TryImplicitConversion(E2, Composite1,
2411 /*SuppressUserConversions=*/false,
2412 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002413 /*ForceRValue=*/false,
2414 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002415
John McCallb1bdc622010-02-25 01:37:24 +00002416 bool ToC2Viable = false;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002417 ImplicitConversionSequence E1ToC2, E2ToC2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002418 if (Context.getCanonicalType(Composite1) !=
2419 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002420 E1ToC2 = TryImplicitConversion(E1, Composite2,
2421 /*SuppressUserConversions=*/false,
2422 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002423 /*ForceRValue=*/false,
2424 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002425 E2ToC2 = TryImplicitConversion(E2, Composite2,
2426 /*SuppressUserConversions=*/false,
2427 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002428 /*ForceRValue=*/false,
2429 /*InOverloadResolution=*/false);
John McCallb1bdc622010-02-25 01:37:24 +00002430 ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002431 }
2432
John McCall1d318332010-01-12 00:44:57 +00002433 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002434 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002435 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2436 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002437 return Composite1;
2438 }
2439 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002440 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2441 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002442 return Composite2;
2443 }
2444 return QualType();
2445}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002446
Anders Carlssondef11992009-05-30 20:36:53 +00002447Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002448 if (!Context.getLangOptions().CPlusPlus)
2449 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Douglas Gregor51326552009-12-24 18:51:59 +00002451 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2452
Ted Kremenek6217b802009-07-29 21:53:49 +00002453 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002454 if (!RT)
2455 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002456
John McCall86ff3082010-02-04 22:26:26 +00002457 // If this is the result of a call expression, our source might
2458 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002459 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2460 QualType Ty = CE->getCallee()->getType();
2461 if (const PointerType *PT = Ty->getAs<PointerType>())
2462 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002463 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2464 Ty = BPT->getPointeeType();
2465
John McCall183700f2009-09-21 23:43:11 +00002466 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002467 if (FTy->getResultType()->isReferenceType())
2468 return Owned(E);
2469 }
John McCall86ff3082010-02-04 22:26:26 +00002470
2471 // That should be enough to guarantee that this type is complete.
2472 // If it has a trivial destructor, we can avoid the extra copy.
2473 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2474 if (RD->hasTrivialDestructor())
2475 return Owned(E);
2476
Mike Stump1eb44332009-09-09 15:08:12 +00002477 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002478 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002479 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002480 if (CXXDestructorDecl *Destructor =
2481 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2482 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002483 // FIXME: Add the temporary to the temporaries vector.
2484 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2485}
2486
Anders Carlsson0ece4912009-12-15 20:51:39 +00002487Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002488 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002490 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2491 assert(ExprTemporaries.size() >= FirstTemporary);
2492 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002493 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002495 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002496 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002497 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002498 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2499 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002501 return E;
2502}
2503
Douglas Gregor90f93822009-12-22 22:17:25 +00002504Sema::OwningExprResult
2505Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2506 if (SubExpr.isInvalid())
2507 return ExprError();
2508
2509 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2510}
2511
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002512FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2513 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2514 assert(ExprTemporaries.size() >= FirstTemporary);
2515
2516 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2517 CXXTemporary **Temporaries =
2518 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2519
2520 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2521
2522 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2523 ExprTemporaries.end());
2524
2525 return E;
2526}
2527
Mike Stump1eb44332009-09-09 15:08:12 +00002528Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002529Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002530 tok::TokenKind OpKind, TypeTy *&ObjectType,
2531 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002532 // Since this might be a postfix expression, get rid of ParenListExprs.
2533 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002535 Expr *BaseExpr = (Expr*)Base.get();
2536 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002538 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002539 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002540 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002541 // If we have a pointer to a dependent type and are using the -> operator,
2542 // the object type is the type that the pointer points to. We might still
2543 // have enough information about that type to do something useful.
2544 if (OpKind == tok::arrow)
2545 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2546 BaseType = Ptr->getPointeeType();
2547
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002548 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002549 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002550 return move(Base);
2551 }
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002553 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002554 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002555 // returned, with the original second operand.
2556 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002557 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002558 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002559 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002560 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002561
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002562 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002563 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002564 BaseExpr = (Expr*)Base.get();
2565 if (BaseExpr == NULL)
2566 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002567 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002568 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002569 BaseType = BaseExpr->getType();
2570 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002571 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002572 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002573 for (unsigned i = 0; i < Locations.size(); i++)
2574 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002575 return ExprError();
2576 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002577 }
Mike Stump1eb44332009-09-09 15:08:12 +00002578
Douglas Gregor31658df2009-11-20 19:58:21 +00002579 if (BaseType->isPointerType())
2580 BaseType = BaseType->getPointeeType();
2581 }
Mike Stump1eb44332009-09-09 15:08:12 +00002582
2583 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002584 // vector types or Objective-C interfaces. Just return early and let
2585 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002586 if (!BaseType->isRecordType()) {
2587 // C++ [basic.lookup.classref]p2:
2588 // [...] If the type of the object expression is of pointer to scalar
2589 // type, the unqualified-id is looked up in the context of the complete
2590 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002591 //
2592 // This also indicates that we should be parsing a
2593 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002594 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002595 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002596 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002597 }
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Douglas Gregor03c57052009-11-17 05:17:33 +00002599 // The object type must be complete (or dependent).
2600 if (!BaseType->isDependentType() &&
2601 RequireCompleteType(OpLoc, BaseType,
2602 PDiag(diag::err_incomplete_member_access)))
2603 return ExprError();
2604
Douglas Gregorc68afe22009-09-03 21:38:09 +00002605 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002606 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002607 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002608 // type C (or of pointer to a class type C), the unqualified-id is looked
2609 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002610 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002611 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002612}
2613
Douglas Gregor77549082010-02-24 21:29:12 +00002614Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2615 ExprArg MemExpr) {
2616 Expr *E = (Expr *) MemExpr.get();
2617 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2618 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2619 << isa<CXXPseudoDestructorExpr>(E)
2620 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2621
2622 return ActOnCallExpr(/*Scope*/ 0,
2623 move(MemExpr),
2624 /*LPLoc*/ ExpectedLParenLoc,
2625 Sema::MultiExprArg(*this, 0, 0),
2626 /*CommaLocs*/ 0,
2627 /*RPLoc*/ ExpectedLParenLoc);
2628}
Douglas Gregord4dca082010-02-24 18:44:31 +00002629
Douglas Gregorb57fb492010-02-24 22:38:50 +00002630Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2631 SourceLocation OpLoc,
2632 tok::TokenKind OpKind,
2633 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002634 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002635 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002636 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002637 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002638 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002639 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002640
2641 // C++ [expr.pseudo]p2:
2642 // The left-hand side of the dot operator shall be of scalar type. The
2643 // left-hand side of the arrow operator shall be of pointer to scalar type.
2644 // This scalar type is the object type.
2645 Expr *BaseE = (Expr *)Base.get();
2646 QualType ObjectType = BaseE->getType();
2647 if (OpKind == tok::arrow) {
2648 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2649 ObjectType = Ptr->getPointeeType();
2650 } else if (!BaseE->isTypeDependent()) {
2651 // The user wrote "p->" when she probably meant "p."; fix it.
2652 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2653 << ObjectType << true
2654 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2655 if (isSFINAEContext())
2656 return ExprError();
2657
2658 OpKind = tok::period;
2659 }
2660 }
2661
2662 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2663 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2664 << ObjectType << BaseE->getSourceRange();
2665 return ExprError();
2666 }
2667
2668 // C++ [expr.pseudo]p2:
2669 // [...] The cv-unqualified versions of the object type and of the type
2670 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002671 if (DestructedTypeInfo) {
2672 QualType DestructedType = DestructedTypeInfo->getType();
2673 SourceLocation DestructedTypeStart
2674 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2675 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2676 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2677 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2678 << ObjectType << DestructedType << BaseE->getSourceRange()
2679 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2680
2681 // Recover by setting the destructed type to the object type.
2682 DestructedType = ObjectType;
2683 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2684 DestructedTypeStart);
2685 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2686 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002687 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002688
Douglas Gregorb57fb492010-02-24 22:38:50 +00002689 // C++ [expr.pseudo]p2:
2690 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2691 // form
2692 //
2693 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2694 //
2695 // shall designate the same scalar type.
2696 if (ScopeTypeInfo) {
2697 QualType ScopeType = ScopeTypeInfo->getType();
2698 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2699 !Context.hasSameType(ScopeType, ObjectType)) {
2700
2701 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2702 diag::err_pseudo_dtor_type_mismatch)
2703 << ObjectType << ScopeType << BaseE->getSourceRange()
2704 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2705
2706 ScopeType = QualType();
2707 ScopeTypeInfo = 0;
2708 }
2709 }
2710
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 ScopeTypeInfo,
2719 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002720 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002721 Destructed));
2722
Douglas Gregorb57fb492010-02-24 22:38:50 +00002723 if (HasTrailingLParen)
2724 return move(Result);
2725
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002726 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002727}
2728
2729Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2730 SourceLocation OpLoc,
2731 tok::TokenKind OpKind,
2732 const CXXScopeSpec &SS,
2733 UnqualifiedId &FirstTypeName,
2734 SourceLocation CCLoc,
2735 SourceLocation TildeLoc,
2736 UnqualifiedId &SecondTypeName,
2737 bool HasTrailingLParen) {
2738 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2739 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2740 "Invalid first type name in pseudo-destructor");
2741 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2742 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2743 "Invalid second type name in pseudo-destructor");
2744
2745 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002746
2747 // C++ [expr.pseudo]p2:
2748 // The left-hand side of the dot operator shall be of scalar type. The
2749 // left-hand side of the arrow operator shall be of pointer to scalar type.
2750 // This scalar type is the object type.
2751 QualType ObjectType = BaseE->getType();
2752 if (OpKind == tok::arrow) {
2753 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2754 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002755 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002756 // The user wrote "p->" when she probably meant "p."; fix it.
2757 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002758 << ObjectType << true
2759 << CodeModificationHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002760 if (isSFINAEContext())
2761 return ExprError();
2762
2763 OpKind = tok::period;
2764 }
2765 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002766
2767 // Compute the object type that we should use for name lookup purposes. Only
2768 // record types and dependent types matter.
2769 void *ObjectTypePtrForLookup = 0;
2770 if (!SS.isSet()) {
2771 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2772 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2773 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2774 }
Douglas Gregor77549082010-02-24 21:29:12 +00002775
Douglas Gregorb57fb492010-02-24 22:38:50 +00002776 // Convert the name of the type being destructed (following the ~) into a
2777 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002778 QualType DestructedType;
2779 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002780 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002781 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2782 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2783 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002784 S, &SS, true, ObjectTypePtrForLookup);
2785 if (!T &&
2786 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2787 (!SS.isSet() && ObjectType->isDependentType()))) {
2788 // The name of the type being destroyed is a dependent name, and we
2789 // couldn't find anything useful in scope. Just store the identifier and
2790 // it's location, and we'll perform (qualified) name lookup again at
2791 // template instantiation time.
2792 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2793 SecondTypeName.StartLocation);
2794 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002795 Diag(SecondTypeName.StartLocation,
2796 diag::err_pseudo_dtor_destructor_non_type)
2797 << SecondTypeName.Identifier << ObjectType;
2798 if (isSFINAEContext())
2799 return ExprError();
2800
2801 // Recover by assuming we had the right type all along.
2802 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002803 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002804 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002805 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002806 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002807 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002808 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2809 TemplateId->getTemplateArgs(),
2810 TemplateId->NumArgs);
2811 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2812 TemplateId->TemplateNameLoc,
2813 TemplateId->LAngleLoc,
2814 TemplateArgsPtr,
2815 TemplateId->RAngleLoc);
2816 if (T.isInvalid() || !T.get()) {
2817 // Recover by assuming we had the right type all along.
2818 DestructedType = ObjectType;
2819 } else
2820 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002821 }
2822
Douglas Gregorb57fb492010-02-24 22:38:50 +00002823 // If we've performed some kind of recovery, (re-)build the type source
2824 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002825 if (!DestructedType.isNull()) {
2826 if (!DestructedTypeInfo)
2827 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002828 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002829 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2830 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002831
2832 // Convert the name of the scope type (the type prior to '::') into a type.
2833 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002834 QualType ScopeType;
2835 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2836 FirstTypeName.Identifier) {
2837 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2838 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2839 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002840 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002841 if (!T) {
2842 Diag(FirstTypeName.StartLocation,
2843 diag::err_pseudo_dtor_destructor_non_type)
2844 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002845
Douglas Gregorb57fb492010-02-24 22:38:50 +00002846 if (isSFINAEContext())
2847 return ExprError();
2848
2849 // Just drop this type. It's unnecessary anyway.
2850 ScopeType = QualType();
2851 } else
2852 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002853 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002854 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002855 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002856 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2857 TemplateId->getTemplateArgs(),
2858 TemplateId->NumArgs);
2859 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2860 TemplateId->TemplateNameLoc,
2861 TemplateId->LAngleLoc,
2862 TemplateArgsPtr,
2863 TemplateId->RAngleLoc);
2864 if (T.isInvalid() || !T.get()) {
2865 // Recover by dropping this type.
2866 ScopeType = QualType();
2867 } else
2868 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002869 }
2870 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002871
2872 if (!ScopeType.isNull() && !ScopeTypeInfo)
2873 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2874 FirstTypeName.StartLocation);
2875
2876
Douglas Gregorb57fb492010-02-24 22:38:50 +00002877 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002878 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002879 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002880}
2881
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002882CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2883 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002884 if (PerformObjectArgumentInitialization(Exp, Method))
2885 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2886
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002887 MemberExpr *ME =
2888 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2889 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002890 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002891 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2892 CXXMemberCallExpr *CE =
2893 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2894 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002895 return CE;
2896}
2897
Anders Carlsson0aebc812009-09-09 21:33:21 +00002898Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2899 QualType Ty,
2900 CastExpr::CastKind Kind,
2901 CXXMethodDecl *Method,
2902 ExprArg Arg) {
2903 Expr *From = Arg.takeAs<Expr>();
2904
2905 switch (Kind) {
2906 default: assert(0 && "Unhandled cast kind!");
2907 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002908 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2909
2910 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2911 MultiExprArg(*this, (void **)&From, 1),
2912 CastLoc, ConstructorArgs))
2913 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002914
2915 OwningExprResult Result =
2916 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2917 move_arg(ConstructorArgs));
2918 if (Result.isInvalid())
2919 return ExprError();
2920
2921 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002922 }
2923
2924 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002925 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002926
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002927 // Create an implicit call expr that calls it.
2928 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002929 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002930 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002931 }
2932}
2933
Anders Carlsson165a0a02009-05-17 18:41:29 +00002934Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2935 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002936 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002937 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002938
Anders Carlsson165a0a02009-05-17 18:41:29 +00002939 return Owned(FullExpr);
2940}