1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/DeclSpec.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "clang/Sema/TemplateDeduction.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/CXXInheritance.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "llvm/ADT/STLExtras.h"
30 using namespace clang;
33 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
35 SourceLocation NameLoc,
36 Scope *S, CXXScopeSpec &SS,
37 ParsedType ObjectTypePtr,
38 bool EnteringContext) {
39 // Determine where to perform name lookup.
41 // FIXME: This area of the standard is very messy, and the current
42 // wording is rather unclear about which scopes we search for the
43 // destructor name; see core issues 399 and 555. Issue 399 in
44 // particular shows where the current description of destructor name
45 // lookup is completely out of line with existing practice, e.g.,
46 // this appears to be ill-formed:
49 // template <typename T> struct S {
54 // void f(N::S<int>* s) {
55 // s->N::S<int>::~S();
58 // See also PR6358 and PR6359.
59 // For this reason, we're currently only doing the C++03 version of this
60 // code; the C++0x version has to wait until we get a proper spec.
62 DeclContext *LookupCtx = 0;
63 bool isDependent = false;
64 bool LookInScope = false;
66 // If we have an object type, it's because we are in a
67 // pseudo-destructor-expression or a member access expression, and
68 // we know what type we're looking for.
70 SearchType = GetTypeFromParser(ObjectTypePtr);
73 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
75 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
77 // C++ [basic.lookup.qual]p6:
78 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
79 // the type-names are looked up as types in the scope designated by the
80 // nested-name-specifier. In a qualified-id of the form:
82 // ::[opt] nested-name-specifier ̃ class-name
84 // where the nested-name-specifier designates a namespace scope, and in
85 // a qualified-id of the form:
87 // ::opt nested-name-specifier class-name :: ̃ class-name
89 // the class-names are looked up as types in the scope designated by
90 // the nested-name-specifier.
92 // Here, we check the first case (completely) and determine whether the
93 // code below is permitted to look at the prefix of the
94 // nested-name-specifier.
95 DeclContext *DC = computeDeclContext(SS, EnteringContext);
96 if (DC && DC->isFileContext()) {
97 AlreadySearched = true;
100 } else if (DC && isa<CXXRecordDecl>(DC))
101 LookAtPrefix = false;
103 // The second case from the C++03 rules quoted further above.
104 NestedNameSpecifier *Prefix = 0;
105 if (AlreadySearched) {
106 // Nothing left to do.
107 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
108 CXXScopeSpec PrefixSS;
109 PrefixSS.setScopeRep(Prefix);
110 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
111 isDependent = isDependentScopeSpecifier(PrefixSS);
112 } else if (ObjectTypePtr) {
113 LookupCtx = computeDeclContext(SearchType);
114 isDependent = SearchType->isDependentType();
116 LookupCtx = computeDeclContext(SS, EnteringContext);
117 isDependent = LookupCtx && LookupCtx->isDependentContext();
121 } else if (ObjectTypePtr) {
122 // C++ [basic.lookup.classref]p3:
123 // If the unqualified-id is ~type-name, the type-name is looked up
124 // in the context of the entire postfix-expression. If the type T
125 // of the object expression is of a class type C, the type-name is
126 // also looked up in the scope of class C. At least one of the
127 // lookups shall find a name that refers to (possibly
129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 assert((isDependent || !SearchType->isIncompleteType()) &&
132 "Caller should have completed object type");
136 // Perform lookup into the current scope (only).
140 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
141 for (unsigned Step = 0; Step != 2; ++Step) {
142 // Look for the name first in the computed lookup context (if we
143 // have one) and, if that fails to find a match, in the sope (if
144 // we're allowed to look there).
146 if (Step == 0 && LookupCtx)
147 LookupQualifiedName(Found, LookupCtx);
148 else if (Step == 1 && LookInScope && S)
149 LookupName(Found, S);
153 // FIXME: Should we be suppressing ambiguities here?
154 if (Found.isAmbiguous())
157 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
158 QualType T = Context.getTypeDeclType(Type);
160 if (SearchType.isNull() || SearchType->isDependentType() ||
161 Context.hasSameUnqualifiedType(T, SearchType)) {
162 // We found our type!
164 return ParsedType::make(T);
168 // If the name that we found is a class template name, and it is
169 // the same name as the template name in the last part of the
170 // nested-name-specifier (if present) or the object type, then
171 // this is the destructor for that class.
172 // FIXME: This is a workaround until we get real drafting for core
173 // issue 399, for which there isn't even an obvious direction.
174 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
175 QualType MemberOfType;
177 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
178 // Figure out the type of the context, if it has one.
179 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
180 MemberOfType = Context.getTypeDeclType(Record);
183 if (MemberOfType.isNull())
184 MemberOfType = SearchType;
186 if (MemberOfType.isNull())
189 // We're referring into a class template specialization. If the
190 // class template we found is the same as the template being
191 // specialized, we found what we are looking for.
192 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
193 if (ClassTemplateSpecializationDecl *Spec
194 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
195 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
196 Template->getCanonicalDecl())
197 return ParsedType::make(MemberOfType);
203 // We're referring to an unresolved class template
204 // specialization. Determine whether we class template we found
205 // is the same as the template being specialized or, if we don't
206 // know which template is being specialized, that it at least
207 // has the same name.
208 if (const TemplateSpecializationType *SpecType
209 = MemberOfType->getAs<TemplateSpecializationType>()) {
210 TemplateName SpecName = SpecType->getTemplateName();
212 // The class template we found is the same template being
214 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
215 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
216 return ParsedType::make(MemberOfType);
221 // The class template we found has the same name as the
222 // (dependent) template name being specialized.
223 if (DependentTemplateName *DepTemplate
224 = SpecName.getAsDependentTemplateName()) {
225 if (DepTemplate->isIdentifier() &&
226 DepTemplate->getIdentifier() == Template->getIdentifier())
227 return ParsedType::make(MemberOfType);
236 // We didn't find our type, but that's okay: it's dependent
238 NestedNameSpecifier *NNS = 0;
241 NNS = (NestedNameSpecifier *)SS.getScopeRep();
242 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
244 NNS = NestedNameSpecifier::Create(Context, &II);
245 Range = SourceRange(NameLoc);
248 QualType T = CheckTypenameType(ETK_None, NNS, II,
251 return ParsedType::make(T);
255 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
258 Diag(NameLoc, diag::err_destructor_class_name);
263 /// \brief Build a C++ typeid expression with a type operand.
264 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
265 SourceLocation TypeidLoc,
266 TypeSourceInfo *Operand,
267 SourceLocation RParenLoc) {
268 // C++ [expr.typeid]p4:
269 // The top-level cv-qualifiers of the lvalue expression or the type-id
270 // that is the operand of typeid are always ignored.
271 // If the type of the type-id is a class type or a reference to a class
272 // type, the class shall be completely-defined.
275 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
277 if (T->getAs<RecordType>() &&
278 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
281 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
283 SourceRange(TypeidLoc, RParenLoc)));
286 /// \brief Build a C++ typeid expression with an expression operand.
287 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
288 SourceLocation TypeidLoc,
290 SourceLocation RParenLoc) {
291 bool isUnevaluatedOperand = true;
292 if (E && !E->isTypeDependent()) {
293 QualType T = E->getType();
294 if (const RecordType *RecordT = T->getAs<RecordType>()) {
295 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
296 // C++ [expr.typeid]p3:
297 // [...] If the type of the expression is a class type, the class
298 // shall be completely-defined.
299 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
302 // C++ [expr.typeid]p3:
303 // When typeid is applied to an expression other than an glvalue of a
304 // polymorphic class type [...] [the] expression is an unevaluated
306 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
307 isUnevaluatedOperand = false;
309 // We require a vtable to query the type at run time.
310 MarkVTableUsed(TypeidLoc, RecordD);
314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
320 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
321 if (!Context.hasSameType(T, UnqualT)) {
323 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
327 // If this is an unevaluated operand, clear out the set of
328 // declaration references we have been computing and eliminate any
329 // temporaries introduced in its computation.
330 if (isUnevaluatedOperand)
331 ExprEvalContexts.back().Context = Unevaluated;
333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
335 SourceRange(TypeidLoc, RParenLoc)));
338 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
340 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
341 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
342 // Find the std::type_info type.
344 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
346 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
347 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
348 LookupQualifiedName(R, getStdNamespace());
349 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
350 if (!TypeInfoRecordDecl)
351 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
353 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
356 // The operand is a type; handle it as such.
357 TypeSourceInfo *TInfo = 0;
358 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
364 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
366 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
369 // The operand is an expression.
370 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
373 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
375 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
376 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
377 "Unknown C++ Boolean value!");
378 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
379 Context.BoolTy, OpLoc));
382 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
384 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
385 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
388 /// ActOnCXXThrow - Parse throw expressions.
390 Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
391 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
393 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
396 /// CheckCXXThrowOperand - Validate the operand of a throw.
397 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
398 // C++ [except.throw]p3:
399 // A throw-expression initializes a temporary object, called the exception
400 // object, the type of which is determined by removing any top-level
401 // cv-qualifiers from the static type of the operand of throw and adjusting
402 // the type from "array of T" or "function returning T" to "pointer to T"
403 // or "pointer to function returning T", [...]
404 if (E->getType().hasQualifiers())
405 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
408 DefaultFunctionArrayConversion(E);
410 // If the type of the exception would be an incomplete type or a pointer
411 // to an incomplete type other than (cv) void the program is ill-formed.
412 QualType Ty = E->getType();
413 bool isPointer = false;
414 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
415 Ty = Ptr->getPointeeType();
418 if (!isPointer || !Ty->isVoidType()) {
419 if (RequireCompleteType(ThrowLoc, Ty,
420 PDiag(isPointer ? diag::err_throw_incomplete_ptr
421 : diag::err_throw_incomplete)
422 << E->getSourceRange()))
425 if (RequireNonAbstractType(ThrowLoc, E->getType(),
426 PDiag(diag::err_throw_abstract_type)
427 << E->getSourceRange()))
431 // Initialize the exception result. This implicitly weeds out
432 // abstract types or types with inaccessible copy constructors.
433 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
434 InitializedEntity Entity =
435 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
437 ExprResult Res = PerformCopyInitialization(Entity,
442 E = Res.takeAs<Expr>();
444 // If the exception has class type, we need additional handling.
445 const RecordType *RecordTy = Ty->getAs<RecordType>();
448 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
450 // If we are throwing a polymorphic class type or pointer thereof,
451 // exception handling will make use of the vtable.
452 MarkVTableUsed(ThrowLoc, RD);
454 // If the class has a non-trivial destructor, we must be able to call it.
455 if (RD->hasTrivialDestructor())
458 CXXDestructorDecl *Destructor
459 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
463 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
464 CheckDestructorAccess(E->getExprLoc(), Destructor,
465 PDiag(diag::err_access_dtor_exception) << Ty);
469 ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
470 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
471 /// is a non-lvalue expression whose value is the address of the object for
472 /// which the function is called.
474 DeclContext *DC = getFunctionLevelDeclContext();
475 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
476 if (MD->isInstance())
477 return Owned(new (Context) CXXThisExpr(ThisLoc,
478 MD->getThisType(Context),
479 /*isImplicit=*/false));
481 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
484 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
485 /// Can be interpreted either as function-style casting ("int(x)")
486 /// or class type construction ("ClassType(x,y,z)")
487 /// or creation of a value-initialized type ("int()").
489 Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, ParsedType TypeRep,
490 SourceLocation LParenLoc,
492 SourceLocation *CommaLocs,
493 SourceLocation RParenLoc) {
497 TypeSourceInfo *TInfo;
498 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
500 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
501 unsigned NumExprs = exprs.size();
502 Expr **Exprs = (Expr**)exprs.get();
503 SourceLocation TyBeginLoc = TypeRange.getBegin();
504 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
506 if (Ty->isDependentType() ||
507 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
510 return Owned(CXXUnresolvedConstructExpr::Create(Context,
511 TypeRange.getBegin(), Ty,
517 if (Ty->isArrayType())
518 return ExprError(Diag(TyBeginLoc,
519 diag::err_value_init_for_array_type) << FullRange);
520 if (!Ty->isVoidType() &&
521 RequireCompleteType(TyBeginLoc, Ty,
522 PDiag(diag::err_invalid_incomplete_type_use)
526 if (RequireNonAbstractType(TyBeginLoc, Ty,
527 diag::err_allocation_of_abstract_type))
531 // C++ [expr.type.conv]p1:
532 // If the expression list is a single expression, the type conversion
533 // expression is equivalent (in definedness, and if defined in meaning) to the
534 // corresponding cast expression.
537 CastKind Kind = CK_Unknown;
538 CXXCastPath BasePath;
539 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
540 /*FunctionalStyle=*/true))
545 return Owned(CXXFunctionalCastExpr::Create(Context,
546 Ty.getNonLValueExprType(Context),
547 TInfo, TyBeginLoc, Kind,
552 if (Ty->isRecordType()) {
553 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
554 InitializationKind Kind
555 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
556 LParenLoc, RParenLoc)
557 : InitializationKind::CreateValue(TypeRange.getBegin(),
558 LParenLoc, RParenLoc);
559 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
560 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
563 // FIXME: Improve AST representation?
567 // C++ [expr.type.conv]p1:
568 // If the expression list specifies more than a single value, the type shall
569 // be a class with a suitably declared constructor.
572 return ExprError(Diag(CommaLocs[0],
573 diag::err_builtin_func_cast_more_than_one_arg)
576 assert(NumExprs == 0 && "Expected 0 expressions");
577 // C++ [expr.type.conv]p2:
578 // The expression T(), where T is a simple-type-specifier for a non-array
579 // complete object type or the (possibly cv-qualified) void type, creates an
580 // rvalue of the specified type, which is value-initialized.
583 return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc));
587 /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
588 /// @code new (memory) int[size][4] @endcode
590 /// @code ::new Foo(23, "hello") @endcode
591 /// For the interpretation of this heap of arguments, consult the base version.
593 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
594 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
595 SourceLocation PlacementRParen, SourceRange TypeIdParens,
596 Declarator &D, SourceLocation ConstructorLParen,
597 MultiExprArg ConstructorArgs,
598 SourceLocation ConstructorRParen) {
600 // If the specified type is an array, unwrap it and save the expression.
601 if (D.getNumTypeObjects() > 0 &&
602 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
603 DeclaratorChunk &Chunk = D.getTypeObject(0);
604 if (Chunk.Arr.hasStatic)
605 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
606 << D.getSourceRange());
607 if (!Chunk.Arr.NumElts)
608 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
609 << D.getSourceRange());
611 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
612 D.DropFirstTypeObject();
615 // Every dimension shall be of constant size.
617 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
618 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
621 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
622 if (Expr *NumElts = (Expr *)Array.NumElts) {
623 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
624 !NumElts->isIntegerConstantExpr(Context)) {
625 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
626 << NumElts->getSourceRange();
633 //FIXME: Store TypeSourceInfo in CXXNew expression.
634 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
635 QualType AllocType = TInfo->getType();
636 if (D.isInvalidType())
639 SourceRange R = TInfo->getTypeLoc().getSourceRange();
640 return BuildCXXNew(StartLoc, UseGlobal,
646 D.getSourceRange().getBegin(),
650 move(ConstructorArgs),
655 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
656 SourceLocation PlacementLParen,
657 MultiExprArg PlacementArgs,
658 SourceLocation PlacementRParen,
659 SourceRange TypeIdParens,
661 SourceLocation TypeLoc,
662 SourceRange TypeRange,
664 SourceLocation ConstructorLParen,
665 MultiExprArg ConstructorArgs,
666 SourceLocation ConstructorRParen) {
667 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
670 // Per C++0x [expr.new]p5, the type being constructed may be a
671 // typedef of an array type.
673 if (const ConstantArrayType *Array
674 = Context.getAsConstantArrayType(AllocType)) {
675 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
676 Context.getSizeType(),
678 AllocType = Array->getElementType();
682 QualType ResultType = Context.getPointerType(AllocType);
684 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
685 // or enumeration type with a non-negative value."
686 if (ArraySize && !ArraySize->isTypeDependent()) {
688 QualType SizeType = ArraySize->getType();
690 ExprResult ConvertedSize
691 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
692 PDiag(diag::err_array_size_not_integral),
693 PDiag(diag::err_array_size_incomplete_type)
694 << ArraySize->getSourceRange(),
695 PDiag(diag::err_array_size_explicit_conversion),
696 PDiag(diag::note_array_size_conversion),
697 PDiag(diag::err_array_size_ambiguous_conversion),
698 PDiag(diag::note_array_size_conversion),
699 PDiag(getLangOptions().CPlusPlus0x? 0
700 : diag::ext_array_size_conversion));
701 if (ConvertedSize.isInvalid())
704 ArraySize = ConvertedSize.take();
705 SizeType = ArraySize->getType();
706 if (!SizeType->isIntegralOrEnumerationType())
709 // Let's see if this is a constant < 0. If so, we reject it out of hand.
710 // We don't care about special rules, so we tell the machinery it's not
711 // evaluated - it gives us a result in more cases.
712 if (!ArraySize->isValueDependent()) {
714 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
715 if (Value < llvm::APSInt(
716 llvm::APInt::getNullValue(Value.getBitWidth()),
718 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
719 diag::err_typecheck_negative_array_size)
720 << ArraySize->getSourceRange());
722 if (!AllocType->isDependentType()) {
723 unsigned ActiveSizeBits
724 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
725 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
726 Diag(ArraySize->getSourceRange().getBegin(),
727 diag::err_array_too_large)
728 << Value.toString(10)
729 << ArraySize->getSourceRange();
733 } else if (TypeIdParens.isValid()) {
734 // Can't have dynamic array size when the type-id is in parentheses.
735 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
736 << ArraySize->getSourceRange()
737 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
738 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
740 TypeIdParens = SourceRange();
744 ImpCastExprToType(ArraySize, Context.getSizeType(),
748 FunctionDecl *OperatorNew = 0;
749 FunctionDecl *OperatorDelete = 0;
750 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
751 unsigned NumPlaceArgs = PlacementArgs.size();
753 if (!AllocType->isDependentType() &&
754 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
755 FindAllocationFunctions(StartLoc,
756 SourceRange(PlacementLParen, PlacementRParen),
757 UseGlobal, AllocType, ArraySize, PlaceArgs,
758 NumPlaceArgs, OperatorNew, OperatorDelete))
760 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
762 // Add default arguments, if any.
763 const FunctionProtoType *Proto =
764 OperatorNew->getType()->getAs<FunctionProtoType>();
765 VariadicCallType CallType =
766 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
768 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
769 Proto, 1, PlaceArgs, NumPlaceArgs,
770 AllPlaceArgs, CallType))
773 NumPlaceArgs = AllPlaceArgs.size();
774 if (NumPlaceArgs > 0)
775 PlaceArgs = &AllPlaceArgs[0];
778 bool Init = ConstructorLParen.isValid();
779 // --- Choosing a constructor ---
780 CXXConstructorDecl *Constructor = 0;
781 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
782 unsigned NumConsArgs = ConstructorArgs.size();
783 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
785 // Array 'new' can't have any initializers.
786 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
787 SourceRange InitRange(ConsArgs[0]->getLocStart(),
788 ConsArgs[NumConsArgs - 1]->getLocEnd());
790 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
794 if (!AllocType->isDependentType() &&
795 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
796 // C++0x [expr.new]p15:
797 // A new-expression that creates an object of type T initializes that
798 // object as follows:
799 InitializationKind Kind
800 // - If the new-initializer is omitted, the object is default-
801 // initialized (8.5); if no initialization is performed,
802 // the object has indeterminate value
803 = !Init? InitializationKind::CreateDefault(TypeLoc)
804 // - Otherwise, the new-initializer is interpreted according to the
805 // initialization rules of 8.5 for direct-initialization.
806 : InitializationKind::CreateDirect(TypeLoc,
810 InitializedEntity Entity
811 = InitializedEntity::InitializeNew(StartLoc, AllocType);
812 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
813 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
814 move(ConstructorArgs));
815 if (FullInit.isInvalid())
818 // FullInit is our initializer; walk through it to determine if it's a
819 // constructor call, which CXXNewExpr handles directly.
820 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
821 if (CXXBindTemporaryExpr *Binder
822 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
823 FullInitExpr = Binder->getSubExpr();
824 if (CXXConstructExpr *Construct
825 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
826 Constructor = Construct->getConstructor();
827 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
828 AEnd = Construct->arg_end();
830 ConvertedConstructorArgs.push_back(A->Retain());
832 // Take the converted initializer.
833 ConvertedConstructorArgs.push_back(FullInit.release());
836 // No initialization required.
839 // Take the converted arguments and use them for the new expression.
840 NumConsArgs = ConvertedConstructorArgs.size();
841 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
844 // Mark the new and delete operators as referenced.
846 MarkDeclarationReferenced(StartLoc, OperatorNew);
848 MarkDeclarationReferenced(StartLoc, OperatorDelete);
850 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
852 PlacementArgs.release();
853 ConstructorArgs.release();
855 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
856 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
857 PlaceArgs, NumPlaceArgs, TypeIdParens,
858 ArraySize, Constructor, Init,
859 ConsArgs, NumConsArgs, OperatorDelete,
860 ResultType, StartLoc,
861 Init ? ConstructorRParen :
862 TypeRange.getEnd()));
865 /// CheckAllocatedType - Checks that a type is suitable as the allocated type
866 /// in a new-expression.
867 /// dimension off and stores the size expression in ArraySize.
868 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
870 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
871 // abstract class type or array thereof.
872 if (AllocType->isFunctionType())
873 return Diag(Loc, diag::err_bad_new_type)
874 << AllocType << 0 << R;
875 else if (AllocType->isReferenceType())
876 return Diag(Loc, diag::err_bad_new_type)
877 << AllocType << 1 << R;
878 else if (!AllocType->isDependentType() &&
879 RequireCompleteType(Loc, AllocType,
880 PDiag(diag::err_new_incomplete_type)
883 else if (RequireNonAbstractType(Loc, AllocType,
884 diag::err_allocation_of_abstract_type))
890 /// \brief Determine whether the given function is a non-placement
891 /// deallocation function.
892 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
893 if (FD->isInvalidDecl())
896 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
897 return Method->isUsualDeallocationFunction();
899 return ((FD->getOverloadedOperator() == OO_Delete ||
900 FD->getOverloadedOperator() == OO_Array_Delete) &&
901 FD->getNumParams() == 1);
904 /// FindAllocationFunctions - Finds the overloads of operator new and delete
905 /// that are appropriate for the allocation.
906 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
907 bool UseGlobal, QualType AllocType,
908 bool IsArray, Expr **PlaceArgs,
909 unsigned NumPlaceArgs,
910 FunctionDecl *&OperatorNew,
911 FunctionDecl *&OperatorDelete) {
912 // --- Choosing an allocation function ---
913 // C++ 5.3.4p8 - 14 & 18
914 // 1) If UseGlobal is true, only look in the global scope. Else, also look
915 // in the scope of the allocated class.
916 // 2) If an array size is given, look for operator new[], else look for
918 // 3) The first argument is always size_t. Append the arguments from the
921 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
922 // We don't care about the actual value of this argument.
923 // FIXME: Should the Sema create the expression and embed it in the syntax
924 // tree? Or should the consumer just recalculate the value?
925 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
926 Context.Target.getPointerWidth(0)),
927 Context.getSizeType(),
929 AllocArgs[0] = &Size;
930 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
933 // If the allocated type is a non-array type, the allocation
934 // function’s name is operator new and the deallocation function’s
935 // name is operator delete. If the allocated type is an array
936 // type, the allocation function’s name is operator new[] and the
937 // deallocation function’s name is operator delete[].
938 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
939 IsArray ? OO_Array_New : OO_New);
940 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
941 IsArray ? OO_Array_Delete : OO_Delete);
943 QualType AllocElemType = Context.getBaseElementType(AllocType);
945 if (AllocElemType->isRecordType() && !UseGlobal) {
946 CXXRecordDecl *Record
947 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
948 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
949 AllocArgs.size(), Record, /*AllowMissing=*/true,
954 // Didn't find a member overload. Look for a global one.
955 DeclareGlobalNewDelete();
956 DeclContext *TUDecl = Context.getTranslationUnitDecl();
957 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
958 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
963 // We don't need an operator delete if we're running under
965 if (!getLangOptions().Exceptions) {
970 // FindAllocationOverload can change the passed in arguments, so we need to
972 if (NumPlaceArgs > 0)
973 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
975 // C++ [expr.new]p19:
977 // If the new-expression begins with a unary :: operator, the
978 // deallocation function’s name is looked up in the global
979 // scope. Otherwise, if the allocated type is a class type T or an
980 // array thereof, the deallocation function’s name is looked up in
981 // the scope of T. If this lookup fails to find the name, or if
982 // the allocated type is not a class type or array thereof, the
983 // deallocation function’s name is looked up in the global scope.
984 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
985 if (AllocElemType->isRecordType() && !UseGlobal) {
987 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
988 LookupQualifiedName(FoundDelete, RD);
990 if (FoundDelete.isAmbiguous())
991 return true; // FIXME: clean up expressions?
993 if (FoundDelete.empty()) {
994 DeclareGlobalNewDelete();
995 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
998 FoundDelete.suppressDiagnostics();
1000 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1002 if (NumPlaceArgs > 0) {
1003 // C++ [expr.new]p20:
1004 // A declaration of a placement deallocation function matches the
1005 // declaration of a placement allocation function if it has the
1006 // same number of parameters and, after parameter transformations
1007 // (8.3.5), all parameter types except the first are
1010 // To perform this comparison, we compute the function type that
1011 // the deallocation function should have, and use that type both
1012 // for template argument deduction and for comparison purposes.
1013 QualType ExpectedFunctionType;
1015 const FunctionProtoType *Proto
1016 = OperatorNew->getType()->getAs<FunctionProtoType>();
1017 llvm::SmallVector<QualType, 4> ArgTypes;
1018 ArgTypes.push_back(Context.VoidPtrTy);
1019 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1020 ArgTypes.push_back(Proto->getArgType(I));
1022 ExpectedFunctionType
1023 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1025 Proto->isVariadic(),
1026 0, false, false, 0, 0,
1027 FunctionType::ExtInfo());
1030 for (LookupResult::iterator D = FoundDelete.begin(),
1031 DEnd = FoundDelete.end();
1033 FunctionDecl *Fn = 0;
1034 if (FunctionTemplateDecl *FnTmpl
1035 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1036 // Perform template argument deduction to try to match the
1037 // expected function type.
1038 TemplateDeductionInfo Info(Context, StartLoc);
1039 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1042 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1044 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1045 Matches.push_back(std::make_pair(D.getPair(), Fn));
1048 // C++ [expr.new]p20:
1049 // [...] Any non-placement deallocation function matches a
1050 // non-placement allocation function. [...]
1051 for (LookupResult::iterator D = FoundDelete.begin(),
1052 DEnd = FoundDelete.end();
1054 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1055 if (isNonPlacementDeallocationFunction(Fn))
1056 Matches.push_back(std::make_pair(D.getPair(), Fn));
1060 // C++ [expr.new]p20:
1061 // [...] If the lookup finds a single matching deallocation
1062 // function, that function will be called; otherwise, no
1063 // deallocation function will be called.
1064 if (Matches.size() == 1) {
1065 OperatorDelete = Matches[0].second;
1067 // C++0x [expr.new]p20:
1068 // If the lookup finds the two-parameter form of a usual
1069 // deallocation function (3.7.4.2) and that function, considered
1070 // as a placement deallocation function, would have been
1071 // selected as a match for the allocation function, the program
1073 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1074 isNonPlacementDeallocationFunction(OperatorDelete)) {
1075 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1076 << SourceRange(PlaceArgs[0]->getLocStart(),
1077 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1078 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1081 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1089 /// FindAllocationOverload - Find an fitting overload for the allocation
1090 /// function in the specified scope.
1091 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1092 DeclarationName Name, Expr** Args,
1093 unsigned NumArgs, DeclContext *Ctx,
1094 bool AllowMissing, FunctionDecl *&Operator) {
1095 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1096 LookupQualifiedName(R, Ctx);
1100 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1104 if (R.isAmbiguous())
1107 R.suppressDiagnostics();
1109 OverloadCandidateSet Candidates(StartLoc);
1110 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1111 Alloc != AllocEnd; ++Alloc) {
1112 // Even member operator new/delete are implicitly treated as
1113 // static, so don't use AddMemberCandidate.
1114 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1116 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1117 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1118 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1120 /*SuppressUserConversions=*/false);
1124 FunctionDecl *Fn = cast<FunctionDecl>(D);
1125 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1126 /*SuppressUserConversions=*/false);
1129 // Do the resolution.
1130 OverloadCandidateSet::iterator Best;
1131 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1134 FunctionDecl *FnDecl = Best->Function;
1135 // The first argument is size_t, and the first parameter must be size_t,
1136 // too. This is checked on declaration and can be assumed. (It can't be
1137 // asserted on, though, since invalid decls are left in there.)
1138 // Watch out for variadic allocator function.
1139 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1140 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1142 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1143 FnDecl->getParamDecl(i)),
1145 Owned(Args[i]->Retain()));
1146 if (Result.isInvalid())
1149 Args[i] = Result.takeAs<Expr>();
1152 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1156 case OR_No_Viable_Function:
1157 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1159 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1163 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1165 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1169 Diag(StartLoc, diag::err_ovl_deleted_call)
1170 << Best->Function->isDeleted()
1172 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1175 assert(false && "Unreachable, bad result from BestViableFunction");
1180 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1181 /// delete. These are:
1183 /// void* operator new(std::size_t) throw(std::bad_alloc);
1184 /// void* operator new[](std::size_t) throw(std::bad_alloc);
1185 /// void operator delete(void *) throw();
1186 /// void operator delete[](void *) throw();
1188 /// Note that the placement and nothrow forms of new are *not* implicitly
1189 /// declared. Their use requires including \<new\>.
1190 void Sema::DeclareGlobalNewDelete() {
1191 if (GlobalNewDeleteDeclared)
1194 // C++ [basic.std.dynamic]p2:
1195 // [...] The following allocation and deallocation functions (18.4) are
1196 // implicitly declared in global scope in each translation unit of a
1199 // void* operator new(std::size_t) throw(std::bad_alloc);
1200 // void* operator new[](std::size_t) throw(std::bad_alloc);
1201 // void operator delete(void*) throw();
1202 // void operator delete[](void*) throw();
1204 // These implicit declarations introduce only the function names operator
1205 // new, operator new[], operator delete, operator delete[].
1207 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1208 // "std" or "bad_alloc" as necessary to form the exception specification.
1209 // However, we do not make these implicit declarations visible to name
1212 // The "std::bad_alloc" class has not yet been declared, so build it
1214 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1215 getOrCreateStdNamespace(),
1217 &PP.getIdentifierTable().get("bad_alloc"),
1218 SourceLocation(), 0);
1219 getStdBadAlloc()->setImplicit(true);
1222 GlobalNewDeleteDeclared = true;
1224 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1225 QualType SizeT = Context.getSizeType();
1226 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1228 DeclareGlobalAllocationFunction(
1229 Context.DeclarationNames.getCXXOperatorName(OO_New),
1230 VoidPtr, SizeT, AssumeSaneOperatorNew);
1231 DeclareGlobalAllocationFunction(
1232 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1233 VoidPtr, SizeT, AssumeSaneOperatorNew);
1234 DeclareGlobalAllocationFunction(
1235 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1236 Context.VoidTy, VoidPtr);
1237 DeclareGlobalAllocationFunction(
1238 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1239 Context.VoidTy, VoidPtr);
1242 /// DeclareGlobalAllocationFunction - Declares a single implicit global
1243 /// allocation function if it doesn't already exist.
1244 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1245 QualType Return, QualType Argument,
1246 bool AddMallocAttr) {
1247 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1249 // Check if this function is already declared.
1251 DeclContext::lookup_iterator Alloc, AllocEnd;
1252 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1253 Alloc != AllocEnd; ++Alloc) {
1254 // Only look at non-template functions, as it is the predefined,
1255 // non-templated allocation function we are trying to declare here.
1256 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1257 QualType InitialParamType =
1258 Context.getCanonicalType(
1259 Func->getParamDecl(0)->getType().getUnqualifiedType());
1260 // FIXME: Do we need to check for default arguments here?
1261 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1262 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1263 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1270 QualType BadAllocType;
1271 bool HasBadAllocExceptionSpec
1272 = (Name.getCXXOverloadedOperator() == OO_New ||
1273 Name.getCXXOverloadedOperator() == OO_Array_New);
1274 if (HasBadAllocExceptionSpec) {
1275 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1276 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1279 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1281 HasBadAllocExceptionSpec? 1 : 0,
1283 FunctionType::ExtInfo());
1284 FunctionDecl *Alloc =
1285 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
1286 FnType, /*TInfo=*/0, SC_None,
1287 SC_None, false, true);
1288 Alloc->setImplicit();
1291 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1293 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1294 0, Argument, /*TInfo=*/0,
1297 Alloc->setParams(&Param, 1);
1299 // FIXME: Also add this declaration to the IdentifierResolver, but
1300 // make sure it is at the end of the chain to coincide with the
1302 Context.getTranslationUnitDecl()->addDecl(Alloc);
1305 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1306 DeclarationName Name,
1307 FunctionDecl* &Operator) {
1308 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1309 // Try to find operator delete/operator delete[] in class scope.
1310 LookupQualifiedName(Found, RD);
1312 if (Found.isAmbiguous())
1315 Found.suppressDiagnostics();
1317 llvm::SmallVector<DeclAccessPair,4> Matches;
1318 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1320 NamedDecl *ND = (*F)->getUnderlyingDecl();
1322 // Ignore template operator delete members from the check for a usual
1323 // deallocation function.
1324 if (isa<FunctionTemplateDecl>(ND))
1327 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1328 Matches.push_back(F.getPair());
1331 // There's exactly one suitable operator; pick it.
1332 if (Matches.size() == 1) {
1333 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1334 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1338 // We found multiple suitable operators; complain about the ambiguity.
1339 } else if (!Matches.empty()) {
1340 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1343 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1344 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1345 Diag((*F)->getUnderlyingDecl()->getLocation(),
1346 diag::note_member_declared_here) << Name;
1350 // We did find operator delete/operator delete[] declarations, but
1351 // none of them were suitable.
1352 if (!Found.empty()) {
1353 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1356 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1358 Diag((*F)->getUnderlyingDecl()->getLocation(),
1359 diag::note_member_declared_here) << Name;
1364 // Look for a global declaration.
1365 DeclareGlobalNewDelete();
1366 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1368 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1369 Expr* DeallocArgs[1];
1370 DeallocArgs[0] = &Null;
1371 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1372 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1376 assert(Operator && "Did not find a deallocation function!");
1380 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1381 /// @code ::delete ptr; @endcode
1383 /// @code delete [] ptr; @endcode
1385 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1386 bool ArrayForm, Expr *Ex) {
1387 // C++ [expr.delete]p1:
1388 // The operand shall have a pointer type, or a class type having a single
1389 // conversion function to a pointer type. The result has type void.
1391 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1393 FunctionDecl *OperatorDelete = 0;
1395 if (!Ex->isTypeDependent()) {
1396 QualType Type = Ex->getType();
1398 if (const RecordType *Record = Type->getAs<RecordType>()) {
1399 if (RequireCompleteType(StartLoc, Type,
1400 PDiag(diag::err_delete_incomplete_class_type)))
1403 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1405 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1406 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1407 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1408 E = Conversions->end(); I != E; ++I) {
1409 NamedDecl *D = I.getDecl();
1410 if (isa<UsingShadowDecl>(D))
1411 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1413 // Skip over templated conversion functions; they aren't considered.
1414 if (isa<FunctionTemplateDecl>(D))
1417 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1419 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1420 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1421 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1422 ObjectPtrConversions.push_back(Conv);
1424 if (ObjectPtrConversions.size() == 1) {
1425 // We have a single conversion to a pointer-to-object type. Perform
1427 // TODO: don't redo the conversion calculation.
1428 if (!PerformImplicitConversion(Ex,
1429 ObjectPtrConversions.front()->getConversionType(),
1431 Type = Ex->getType();
1434 else if (ObjectPtrConversions.size() > 1) {
1435 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1436 << Type << Ex->getSourceRange();
1437 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1438 NoteOverloadCandidate(ObjectPtrConversions[i]);
1443 if (!Type->isPointerType())
1444 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1445 << Type << Ex->getSourceRange());
1447 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1448 if (Pointee->isVoidType() && !isSFINAEContext()) {
1449 // The C++ standard bans deleting a pointer to a non-object type, which
1450 // effectively bans deletion of "void*". However, most compilers support
1451 // this, so we treat it as a warning unless we're in a SFINAE context.
1452 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1453 << Type << Ex->getSourceRange();
1454 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1455 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1456 << Type << Ex->getSourceRange());
1457 else if (!Pointee->isDependentType() &&
1458 RequireCompleteType(StartLoc, Pointee,
1459 PDiag(diag::warn_delete_incomplete)
1460 << Ex->getSourceRange()))
1463 // C++ [expr.delete]p2:
1464 // [Note: a pointer to a const type can be the operand of a
1465 // delete-expression; it is not necessary to cast away the constness
1466 // (5.2.11) of the pointer expression before it is used as the operand
1467 // of the delete-expression. ]
1468 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1471 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1472 ArrayForm ? OO_Array_Delete : OO_Delete);
1474 QualType PointeeElem = Context.getBaseElementType(Pointee);
1475 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1476 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1479 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1482 if (!RD->hasTrivialDestructor())
1483 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
1484 MarkDeclarationReferenced(StartLoc,
1485 const_cast<CXXDestructorDecl*>(Dtor));
1488 if (!OperatorDelete) {
1489 // Look for a global declaration.
1490 DeclareGlobalNewDelete();
1491 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1492 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1493 &Ex, 1, TUDecl, /*AllowMissing=*/false,
1498 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1500 // FIXME: Check access and ambiguity of operator delete and destructor.
1503 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1504 OperatorDelete, Ex, StartLoc));
1507 /// \brief Check the use of the given variable as a C++ condition in an if,
1508 /// while, do-while, or switch statement.
1509 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1510 SourceLocation StmtLoc,
1511 bool ConvertToBoolean) {
1512 QualType T = ConditionVar->getType();
1514 // C++ [stmt.select]p2:
1515 // The declarator shall not specify a function or an array.
1516 if (T->isFunctionType())
1517 return ExprError(Diag(ConditionVar->getLocation(),
1518 diag::err_invalid_use_of_function_type)
1519 << ConditionVar->getSourceRange());
1520 else if (T->isArrayType())
1521 return ExprError(Diag(ConditionVar->getLocation(),
1522 diag::err_invalid_use_of_array_type)
1523 << ConditionVar->getSourceRange());
1525 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1526 ConditionVar->getLocation(),
1527 ConditionVar->getType().getNonReferenceType());
1528 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
1531 return Owned(Condition);
1534 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1535 bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1537 // The value of a condition that is an initialized declaration in a statement
1538 // other than a switch statement is the value of the declared variable
1539 // implicitly converted to type bool. If that conversion is ill-formed, the
1540 // program is ill-formed.
1541 // The value of a condition that is an expression is the value of the
1542 // expression, implicitly converted to bool.
1544 return PerformContextuallyConvertToBool(CondExpr);
1547 /// Helper function to determine whether this is the (deprecated) C++
1548 /// conversion from a string literal to a pointer to non-const char or
1549 /// non-const wchar_t (for narrow and wide string literals,
1552 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1553 // Look inside the implicit cast, if it exists.
1554 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1555 From = Cast->getSubExpr();
1557 // A string literal (2.13.4) that is not a wide string literal can
1558 // be converted to an rvalue of type "pointer to char"; a wide
1559 // string literal can be converted to an rvalue of type "pointer
1560 // to wchar_t" (C++ 4.2p2).
1561 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
1562 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1563 if (const BuiltinType *ToPointeeType
1564 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1565 // This conversion is considered only when there is an
1566 // explicit appropriate pointer target type (C++ 4.2p2).
1567 if (!ToPtrType->getPointeeType().hasQualifiers() &&
1568 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1569 (!StrLit->isWide() &&
1570 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1571 ToPointeeType->getKind() == BuiltinType::Char_S))))
1578 static ExprResult BuildCXXCastArgument(Sema &S,
1579 SourceLocation CastLoc,
1582 CXXMethodDecl *Method,
1585 default: assert(0 && "Unhandled cast kind!");
1586 case CK_ConstructorConversion: {
1587 ASTOwningVector<Expr*> ConstructorArgs(S);
1589 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1590 MultiExprArg(&From, 1),
1591 CastLoc, ConstructorArgs))
1595 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1596 move_arg(ConstructorArgs),
1597 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete);
1598 if (Result.isInvalid())
1601 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1604 case CK_UserDefinedConversion: {
1605 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1607 // Create an implicit call expr that calls it.
1608 // FIXME: pass the FoundDecl for the user-defined conversion here
1609 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1610 return S.MaybeBindToTemporary(CE);
1615 /// PerformImplicitConversion - Perform an implicit conversion of the
1616 /// expression From to the type ToType using the pre-computed implicit
1617 /// conversion sequence ICS. Returns true if there was an error, false
1618 /// otherwise. The expression From is replaced with the converted
1619 /// expression. Action is the kind of conversion we're performing,
1620 /// used in the error message.
1622 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1623 const ImplicitConversionSequence &ICS,
1624 AssignmentAction Action, bool IgnoreBaseAccess) {
1625 switch (ICS.getKind()) {
1626 case ImplicitConversionSequence::StandardConversion:
1627 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
1632 case ImplicitConversionSequence::UserDefinedConversion: {
1634 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1635 CastKind CastKind = CK_Unknown;
1636 QualType BeforeToType;
1637 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1638 CastKind = CK_UserDefinedConversion;
1640 // If the user-defined conversion is specified by a conversion function,
1641 // the initial standard conversion sequence converts the source type to
1642 // the implicit object parameter of the conversion function.
1643 BeforeToType = Context.getTagDeclType(Conv->getParent());
1644 } else if (const CXXConstructorDecl *Ctor =
1645 dyn_cast<CXXConstructorDecl>(FD)) {
1646 CastKind = CK_ConstructorConversion;
1647 // Do no conversion if dealing with ... for the first conversion.
1648 if (!ICS.UserDefined.EllipsisConversion) {
1649 // If the user-defined conversion is specified by a constructor, the
1650 // initial standard conversion sequence converts the source type to the
1651 // type required by the argument of the constructor
1652 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1656 assert(0 && "Unknown conversion function kind!");
1657 // Whatch out for elipsis conversion.
1658 if (!ICS.UserDefined.EllipsisConversion) {
1659 if (PerformImplicitConversion(From, BeforeToType,
1660 ICS.UserDefined.Before, AA_Converting,
1666 = BuildCXXCastArgument(*this,
1667 From->getLocStart(),
1668 ToType.getNonReferenceType(),
1669 CastKind, cast<CXXMethodDecl>(FD),
1672 if (CastArg.isInvalid())
1675 From = CastArg.takeAs<Expr>();
1677 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1678 AA_Converting, IgnoreBaseAccess);
1681 case ImplicitConversionSequence::AmbiguousConversion:
1682 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
1683 PDiag(diag::err_typecheck_ambiguous_condition)
1684 << From->getSourceRange());
1687 case ImplicitConversionSequence::EllipsisConversion:
1688 assert(false && "Cannot perform an ellipsis conversion");
1691 case ImplicitConversionSequence::BadConversion:
1695 // Everything went well.
1699 /// PerformImplicitConversion - Perform an implicit conversion of the
1700 /// expression From to the type ToType by following the standard
1701 /// conversion sequence SCS. Returns true if there was an error, false
1702 /// otherwise. The expression From is replaced with the converted
1703 /// expression. Flavor is the context in which we're performing this
1704 /// conversion, for use in error messages.
1706 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1707 const StandardConversionSequence& SCS,
1708 AssignmentAction Action, bool IgnoreBaseAccess) {
1709 // Overall FIXME: we are recomputing too many types here and doing far too
1710 // much extra work. What this means is that we need to keep track of more
1711 // information that is computed when we try the implicit conversion initially,
1712 // so that we don't need to recompute anything here.
1713 QualType FromType = From->getType();
1715 if (SCS.CopyConstructor) {
1716 // FIXME: When can ToType be a reference type?
1717 assert(!ToType->isReferenceType());
1718 if (SCS.Second == ICK_Derived_To_Base) {
1719 ASTOwningVector<Expr*> ConstructorArgs(*this);
1720 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1721 MultiExprArg(*this, &From, 1),
1722 /*FIXME:ConstructLoc*/SourceLocation(),
1725 ExprResult FromResult =
1726 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1727 ToType, SCS.CopyConstructor,
1728 move_arg(ConstructorArgs),
1730 CXXConstructExpr::CK_Complete);
1731 if (FromResult.isInvalid())
1733 From = FromResult.takeAs<Expr>();
1736 ExprResult FromResult =
1737 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1738 ToType, SCS.CopyConstructor,
1739 MultiExprArg(*this, &From, 1),
1741 CXXConstructExpr::CK_Complete);
1743 if (FromResult.isInvalid())
1746 From = FromResult.takeAs<Expr>();
1750 // Resolve overloaded function references.
1751 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1752 DeclAccessPair Found;
1753 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1758 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1761 From = FixOverloadedFunctionReference(From, Found, Fn);
1762 FromType = From->getType();
1765 // Perform the first implicit conversion.
1766 switch (SCS.First) {
1768 case ICK_Lvalue_To_Rvalue:
1772 case ICK_Array_To_Pointer:
1773 FromType = Context.getArrayDecayedType(FromType);
1774 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
1777 case ICK_Function_To_Pointer:
1778 FromType = Context.getPointerType(FromType);
1779 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
1783 assert(false && "Improper first standard conversion");
1787 // Perform the second implicit conversion
1788 switch (SCS.Second) {
1790 // If both sides are functions (or pointers/references to them), there could
1791 // be incompatible exception declarations.
1792 if (CheckExceptionSpecCompatibility(From, ToType))
1794 // Nothing else to do.
1797 case ICK_NoReturn_Adjustment:
1798 // If both sides are functions (or pointers/references to them), there could
1799 // be incompatible exception declarations.
1800 if (CheckExceptionSpecCompatibility(From, ToType))
1803 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1807 case ICK_Integral_Promotion:
1808 case ICK_Integral_Conversion:
1809 ImpCastExprToType(From, ToType, CK_IntegralCast);
1812 case ICK_Floating_Promotion:
1813 case ICK_Floating_Conversion:
1814 ImpCastExprToType(From, ToType, CK_FloatingCast);
1817 case ICK_Complex_Promotion:
1818 case ICK_Complex_Conversion:
1819 ImpCastExprToType(From, ToType, CK_Unknown);
1822 case ICK_Floating_Integral:
1823 if (ToType->isRealFloatingType())
1824 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
1826 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
1829 case ICK_Compatible_Conversion:
1830 ImpCastExprToType(From, ToType, CK_NoOp);
1833 case ICK_Pointer_Conversion: {
1834 if (SCS.IncompatibleObjC) {
1835 // Diagnose incompatible Objective-C conversions
1836 Diag(From->getSourceRange().getBegin(),
1837 diag::ext_typecheck_convert_incompatible_pointer)
1838 << From->getType() << ToType << Action
1839 << From->getSourceRange();
1843 CastKind Kind = CK_Unknown;
1844 CXXCastPath BasePath;
1845 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
1847 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
1851 case ICK_Pointer_Member: {
1852 CastKind Kind = CK_Unknown;
1853 CXXCastPath BasePath;
1854 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1857 if (CheckExceptionSpecCompatibility(From, ToType))
1859 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
1862 case ICK_Boolean_Conversion: {
1863 CastKind Kind = CK_Unknown;
1864 if (FromType->isMemberPointerType())
1865 Kind = CK_MemberPointerToBoolean;
1867 ImpCastExprToType(From, Context.BoolTy, Kind);
1871 case ICK_Derived_To_Base: {
1872 CXXCastPath BasePath;
1873 if (CheckDerivedToBaseConversion(From->getType(),
1874 ToType.getNonReferenceType(),
1875 From->getLocStart(),
1876 From->getSourceRange(),
1881 ImpCastExprToType(From, ToType.getNonReferenceType(),
1882 CK_DerivedToBase, CastCategory(From),
1887 case ICK_Vector_Conversion:
1888 ImpCastExprToType(From, ToType, CK_BitCast);
1891 case ICK_Vector_Splat:
1892 ImpCastExprToType(From, ToType, CK_VectorSplat);
1895 case ICK_Complex_Real:
1896 ImpCastExprToType(From, ToType, CK_Unknown);
1899 case ICK_Lvalue_To_Rvalue:
1900 case ICK_Array_To_Pointer:
1901 case ICK_Function_To_Pointer:
1902 case ICK_Qualification:
1903 case ICK_Num_Conversion_Kinds:
1904 assert(false && "Improper second standard conversion");
1908 switch (SCS.Third) {
1913 case ICK_Qualification: {
1914 // The qualification keeps the category of the inner expression, unless the
1915 // target type isn't a reference.
1916 ExprValueKind VK = ToType->isReferenceType() ?
1917 CastCategory(From) : VK_RValue;
1918 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
1921 if (SCS.DeprecatedStringLiteralToCharPtr)
1922 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1923 << ToType.getNonReferenceType();
1929 assert(false && "Improper third standard conversion");
1936 ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1937 SourceLocation KWLoc,
1938 SourceLocation LParen,
1940 SourceLocation RParen) {
1941 QualType T = GetTypeFromParser(Ty);
1943 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1944 // all traits except __is_class, __is_enum and __is_union require a the type
1946 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1947 if (RequireCompleteType(KWLoc, T,
1948 diag::err_incomplete_type_used_in_type_trait_expr))
1952 // There is no point in eagerly computing the value. The traits are designed
1953 // to be used from type trait templates, so Ty will be a template parameter
1955 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1956 RParen, Context.BoolTy));
1959 QualType Sema::CheckPointerToMemberOperands(
1960 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1961 const char *OpSpelling = isIndirect ? "->*" : ".*";
1963 // The binary operator .* [p3: ->*] binds its second operand, which shall
1964 // be of type "pointer to member of T" (where T is a completely-defined
1965 // class type) [...]
1966 QualType RType = rex->getType();
1967 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1969 Diag(Loc, diag::err_bad_memptr_rhs)
1970 << OpSpelling << RType << rex->getSourceRange();
1974 QualType Class(MemPtr->getClass(), 0);
1976 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1980 // [...] to its first operand, which shall be of class T or of a class of
1981 // which T is an unambiguous and accessible base class. [p3: a pointer to
1983 QualType LType = lex->getType();
1985 if (const PointerType *Ptr = LType->getAs<PointerType>())
1986 LType = Ptr->getPointeeType().getNonReferenceType();
1988 Diag(Loc, diag::err_bad_memptr_lhs)
1989 << OpSpelling << 1 << LType
1990 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
1995 if (!Context.hasSameUnqualifiedType(Class, LType)) {
1996 // If we want to check the hierarchy, we need a complete type.
1997 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1998 << OpSpelling << (int)isIndirect)) {
2001 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2002 /*DetectVirtual=*/false);
2003 // FIXME: Would it be useful to print full ambiguity paths, or is that
2005 if (!IsDerivedFrom(LType, Class, Paths) ||
2006 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2007 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
2008 << (int)isIndirect << lex->getType();
2011 // Cast LHS to type of use.
2012 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
2014 isIndirect ? VK_RValue : CastCategory(lex);
2016 CXXCastPath BasePath;
2017 BuildBasePathArray(Paths, BasePath);
2018 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
2021 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
2022 // Diagnose use of pointer-to-member type which when used as
2023 // the functional cast in a pointer-to-member expression.
2024 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2028 // The result is an object or a function of the type specified by the
2030 // The cv qualifiers are the union of those in the pointer and the left side,
2031 // in accordance with 5.5p5 and 5.2.5.
2032 // FIXME: This returns a dereferenced member function pointer as a normal
2033 // function type. However, the only operation valid on such functions is
2034 // calling them. There's also a GCC extension to get a function pointer to the
2035 // thing, which is another complication, because this type - unlike the type
2036 // that is the result of this expression - takes the class as the first
2038 // We probably need a "MemberFunctionClosureType" or something like that.
2039 QualType Result = MemPtr->getPointeeType();
2040 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
2044 /// \brief Try to convert a type to another according to C++0x 5.16p3.
2046 /// This is part of the parameter validation for the ? operator. If either
2047 /// value operand is a class type, the two operands are attempted to be
2048 /// converted to each other. This function does the conversion in one direction.
2049 /// It returns true if the program is ill-formed and has already been diagnosed
2051 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2052 SourceLocation QuestionLoc,
2053 bool &HaveConversion,
2055 HaveConversion = false;
2056 ToType = To->getType();
2058 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2061 // The process for determining whether an operand expression E1 of type T1
2062 // can be converted to match an operand expression E2 of type T2 is defined
2064 // -- If E2 is an lvalue:
2065 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2067 // E1 can be converted to match E2 if E1 can be implicitly converted to
2068 // type "lvalue reference to T2", subject to the constraint that in the
2069 // conversion the reference must bind directly to E1.
2070 QualType T = Self.Context.getLValueReferenceType(ToType);
2071 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2073 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2074 if (InitSeq.isDirectReferenceBinding()) {
2076 HaveConversion = true;
2080 if (InitSeq.isAmbiguous())
2081 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2084 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2085 // -- if E1 and E2 have class type, and the underlying class types are
2086 // the same or one is a base class of the other:
2087 QualType FTy = From->getType();
2088 QualType TTy = To->getType();
2089 const RecordType *FRec = FTy->getAs<RecordType>();
2090 const RecordType *TRec = TTy->getAs<RecordType>();
2091 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2092 Self.IsDerivedFrom(FTy, TTy);
2094 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
2095 // E1 can be converted to match E2 if the class of T2 is the
2096 // same type as, or a base class of, the class of T1, and
2098 if (FRec == TRec || FDerivedFromT) {
2099 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
2100 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2101 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2102 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2103 HaveConversion = true;
2107 if (InitSeq.isAmbiguous())
2108 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2115 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2116 // implicitly converted to the type that expression E2 would have
2117 // if E2 were converted to an rvalue (or the type it has, if E2 is
2120 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2121 // to the array-to-pointer or function-to-pointer conversions.
2122 if (!TTy->getAs<TagType>())
2123 TTy = TTy.getUnqualifiedType();
2125 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2126 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2127 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2129 if (InitSeq.isAmbiguous())
2130 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2135 /// \brief Try to find a common type for two according to C++0x 5.16p5.
2137 /// This is part of the parameter validation for the ? operator. If either
2138 /// value operand is a class type, overload resolution is used to find a
2139 /// conversion to a common type.
2140 static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2141 SourceLocation Loc) {
2142 Expr *Args[2] = { LHS, RHS };
2143 OverloadCandidateSet CandidateSet(Loc);
2144 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
2146 OverloadCandidateSet::iterator Best;
2147 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
2149 // We found a match. Perform the conversions on the arguments and move on.
2150 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
2151 Best->Conversions[0], Sema::AA_Converting) ||
2152 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
2153 Best->Conversions[1], Sema::AA_Converting))
2157 case OR_No_Viable_Function:
2158 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2159 << LHS->getType() << RHS->getType()
2160 << LHS->getSourceRange() << RHS->getSourceRange();
2164 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2165 << LHS->getType() << RHS->getType()
2166 << LHS->getSourceRange() << RHS->getSourceRange();
2167 // FIXME: Print the possible common types by printing the return types of
2168 // the viable candidates.
2172 assert(false && "Conditional operator has only built-in overloads");
2178 /// \brief Perform an "extended" implicit conversion as returned by
2179 /// TryClassUnification.
2180 static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2181 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2182 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2184 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2185 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
2186 if (Result.isInvalid())
2189 E = Result.takeAs<Expr>();
2193 /// \brief Check the operands of ?: under C++ semantics.
2195 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2196 /// extension. In this case, LHS == Cond. (But they're not aliases.)
2197 QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2198 SourceLocation QuestionLoc) {
2199 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2200 // interface pointers.
2203 // The first expression is contextually converted to bool.
2204 if (!Cond->isTypeDependent()) {
2205 if (CheckCXXBooleanCondition(Cond))
2209 // Either of the arguments dependent?
2210 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2211 return Context.DependentTy;
2214 // If either the second or the third operand has type (cv) void, ...
2215 QualType LTy = LHS->getType();
2216 QualType RTy = RHS->getType();
2217 bool LVoid = LTy->isVoidType();
2218 bool RVoid = RTy->isVoidType();
2219 if (LVoid || RVoid) {
2220 // ... then the [l2r] conversions are performed on the second and third
2222 DefaultFunctionArrayLvalueConversion(LHS);
2223 DefaultFunctionArrayLvalueConversion(RHS);
2224 LTy = LHS->getType();
2225 RTy = RHS->getType();
2227 // ... and one of the following shall hold:
2228 // -- The second or the third operand (but not both) is a throw-
2229 // expression; the result is of the type of the other and is an rvalue.
2230 bool LThrow = isa<CXXThrowExpr>(LHS);
2231 bool RThrow = isa<CXXThrowExpr>(RHS);
2232 if (LThrow && !RThrow)
2234 if (RThrow && !LThrow)
2237 // -- Both the second and third operands have type void; the result is of
2238 // type void and is an rvalue.
2240 return Context.VoidTy;
2242 // Neither holds, error.
2243 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2244 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2245 << LHS->getSourceRange() << RHS->getSourceRange();
2252 // Otherwise, if the second and third operand have different types, and
2253 // either has (cv) class type, and attempt is made to convert each of those
2254 // operands to the other.
2255 if (!Context.hasSameType(LTy, RTy) &&
2256 (LTy->isRecordType() || RTy->isRecordType())) {
2257 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2258 // These return true if a single direction is already ambiguous.
2259 QualType L2RType, R2LType;
2260 bool HaveL2R, HaveR2L;
2261 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
2263 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
2266 // If both can be converted, [...] the program is ill-formed.
2267 if (HaveL2R && HaveR2L) {
2268 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2269 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2273 // If exactly one conversion is possible, that conversion is applied to
2274 // the chosen operand and the converted operands are used in place of the
2275 // original operands for the remainder of this section.
2277 if (ConvertForConditional(*this, LHS, L2RType))
2279 LTy = LHS->getType();
2280 } else if (HaveR2L) {
2281 if (ConvertForConditional(*this, RHS, R2LType))
2283 RTy = RHS->getType();
2288 // If the second and third operands are lvalues and have the same type,
2289 // the result is of that type [...]
2290 bool Same = Context.hasSameType(LTy, RTy);
2291 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2292 RHS->isLvalue(Context) == Expr::LV_Valid)
2296 // Otherwise, the result is an rvalue. If the second and third operands
2297 // do not have the same type, and either has (cv) class type, ...
2298 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2299 // ... overload resolution is used to determine the conversions (if any)
2300 // to be applied to the operands. If the overload resolution fails, the
2301 // program is ill-formed.
2302 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2307 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2308 // conversions are performed on the second and third operands.
2309 DefaultFunctionArrayLvalueConversion(LHS);
2310 DefaultFunctionArrayLvalueConversion(RHS);
2311 LTy = LHS->getType();
2312 RTy = RHS->getType();
2314 // After those conversions, one of the following shall hold:
2315 // -- The second and third operands have the same type; the result
2316 // is of that type. If the operands have class type, the result
2317 // is a prvalue temporary of the result type, which is
2318 // copy-initialized from either the second operand or the third
2319 // operand depending on the value of the first operand.
2320 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2321 if (LTy->isRecordType()) {
2322 // The operands have class type. Make a temporary copy.
2323 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2324 ExprResult LHSCopy = PerformCopyInitialization(Entity,
2327 if (LHSCopy.isInvalid())
2330 ExprResult RHSCopy = PerformCopyInitialization(Entity,
2333 if (RHSCopy.isInvalid())
2336 LHS = LHSCopy.takeAs<Expr>();
2337 RHS = RHSCopy.takeAs<Expr>();
2343 // Extension: conditional operator involving vector types.
2344 if (LTy->isVectorType() || RTy->isVectorType())
2345 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2347 // -- The second and third operands have arithmetic or enumeration type;
2348 // the usual arithmetic conversions are performed to bring them to a
2349 // common type, and the result is of that type.
2350 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2351 UsualArithmeticConversions(LHS, RHS);
2352 return LHS->getType();
2355 // -- The second and third operands have pointer type, or one has pointer
2356 // type and the other is a null pointer constant; pointer conversions
2357 // and qualification conversions are performed to bring them to their
2358 // composite pointer type. The result is of the composite pointer type.
2359 // -- The second and third operands have pointer to member type, or one has
2360 // pointer to member type and the other is a null pointer constant;
2361 // pointer to member conversions and qualification conversions are
2362 // performed to bring them to a common type, whose cv-qualification
2363 // shall match the cv-qualification of either the second or the third
2364 // operand. The result is of the common type.
2365 bool NonStandardCompositeType = false;
2366 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
2367 isSFINAEContext()? 0 : &NonStandardCompositeType);
2368 if (!Composite.isNull()) {
2369 if (NonStandardCompositeType)
2371 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2372 << LTy << RTy << Composite
2373 << LHS->getSourceRange() << RHS->getSourceRange();
2378 // Similarly, attempt to find composite type of two objective-c pointers.
2379 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2380 if (!Composite.isNull())
2383 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2384 << LHS->getType() << RHS->getType()
2385 << LHS->getSourceRange() << RHS->getSourceRange();
2389 /// \brief Find a merged pointer type and convert the two expressions to it.
2391 /// This finds the composite pointer type (or member pointer type) for @p E1
2392 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2393 /// type and returns it.
2394 /// It does not emit diagnostics.
2396 /// \param Loc The location of the operator requiring these two expressions to
2397 /// be converted to the composite pointer type.
2399 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2400 /// a non-standard (but still sane) composite type to which both expressions
2401 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2402 /// will be set true.
2403 QualType Sema::FindCompositePointerType(SourceLocation Loc,
2404 Expr *&E1, Expr *&E2,
2405 bool *NonStandardCompositeType) {
2406 if (NonStandardCompositeType)
2407 *NonStandardCompositeType = false;
2409 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2410 QualType T1 = E1->getType(), T2 = E2->getType();
2412 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2413 !T2->isAnyPointerType() && !T2->isMemberPointerType())
2417 // Pointer conversions and qualification conversions are performed on
2418 // pointer operands to bring them to their composite pointer type. If
2419 // one operand is a null pointer constant, the composite pointer type is
2420 // the type of the other operand.
2421 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2422 if (T2->isMemberPointerType())
2423 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
2425 ImpCastExprToType(E1, T2, CK_IntegralToPointer);
2428 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2429 if (T1->isMemberPointerType())
2430 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
2432 ImpCastExprToType(E2, T1, CK_IntegralToPointer);
2436 // Now both have to be pointers or member pointers.
2437 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2438 (!T2->isPointerType() && !T2->isMemberPointerType()))
2441 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2442 // the other has type "pointer to cv2 T" and the composite pointer type is
2443 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2444 // Otherwise, the composite pointer type is a pointer type similar to the
2445 // type of one of the operands, with a cv-qualification signature that is
2446 // the union of the cv-qualification signatures of the operand types.
2447 // In practice, the first part here is redundant; it's subsumed by the second.
2448 // What we do here is, we build the two possible composite types, and try the
2449 // conversions in both directions. If only one works, or if the two composite
2450 // types are the same, we have succeeded.
2451 // FIXME: extended qualifiers?
2452 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2453 QualifierVector QualifierUnion;
2454 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2455 ContainingClassVector;
2456 ContainingClassVector MemberOfClass;
2457 QualType Composite1 = Context.getCanonicalType(T1),
2458 Composite2 = Context.getCanonicalType(T2);
2459 unsigned NeedConstBefore = 0;
2461 const PointerType *Ptr1, *Ptr2;
2462 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2463 (Ptr2 = Composite2->getAs<PointerType>())) {
2464 Composite1 = Ptr1->getPointeeType();
2465 Composite2 = Ptr2->getPointeeType();
2467 // If we're allowed to create a non-standard composite type, keep track
2468 // of where we need to fill in additional 'const' qualifiers.
2469 if (NonStandardCompositeType &&
2470 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2471 NeedConstBefore = QualifierUnion.size();
2473 QualifierUnion.push_back(
2474 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2475 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2479 const MemberPointerType *MemPtr1, *MemPtr2;
2480 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2481 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2482 Composite1 = MemPtr1->getPointeeType();
2483 Composite2 = MemPtr2->getPointeeType();
2485 // If we're allowed to create a non-standard composite type, keep track
2486 // of where we need to fill in additional 'const' qualifiers.
2487 if (NonStandardCompositeType &&
2488 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2489 NeedConstBefore = QualifierUnion.size();
2491 QualifierUnion.push_back(
2492 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2493 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2494 MemPtr2->getClass()));
2498 // FIXME: block pointer types?
2500 // Cannot unwrap any more types.
2504 if (NeedConstBefore && NonStandardCompositeType) {
2505 // Extension: Add 'const' to qualifiers that come before the first qualifier
2506 // mismatch, so that our (non-standard!) composite type meets the
2507 // requirements of C++ [conv.qual]p4 bullet 3.
2508 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2509 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2510 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2511 *NonStandardCompositeType = true;
2516 // Rewrap the composites as pointers or member pointers with the union CVRs.
2517 ContainingClassVector::reverse_iterator MOC
2518 = MemberOfClass.rbegin();
2519 for (QualifierVector::reverse_iterator
2520 I = QualifierUnion.rbegin(),
2521 E = QualifierUnion.rend();
2522 I != E; (void)++I, ++MOC) {
2523 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
2524 if (MOC->first && MOC->second) {
2525 // Rebuild member pointer type
2526 Composite1 = Context.getMemberPointerType(
2527 Context.getQualifiedType(Composite1, Quals),
2529 Composite2 = Context.getMemberPointerType(
2530 Context.getQualifiedType(Composite2, Quals),
2533 // Rebuild pointer type
2535 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2537 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
2541 // Try to convert to the first composite pointer type.
2542 InitializedEntity Entity1
2543 = InitializedEntity::InitializeTemporary(Composite1);
2544 InitializationKind Kind
2545 = InitializationKind::CreateCopy(Loc, SourceLocation());
2546 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2547 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
2549 if (E1ToC1 && E2ToC1) {
2550 // Conversion to Composite1 is viable.
2551 if (!Context.hasSameType(Composite1, Composite2)) {
2552 // Composite2 is a different type from Composite1. Check whether
2553 // Composite2 is also viable.
2554 InitializedEntity Entity2
2555 = InitializedEntity::InitializeTemporary(Composite2);
2556 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2557 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2558 if (E1ToC2 && E2ToC2) {
2559 // Both Composite1 and Composite2 are viable and are different;
2560 // this is an ambiguity.
2565 // Convert E1 to Composite1
2567 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
2568 if (E1Result.isInvalid())
2570 E1 = E1Result.takeAs<Expr>();
2572 // Convert E2 to Composite1
2574 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
2575 if (E2Result.isInvalid())
2577 E2 = E2Result.takeAs<Expr>();
2582 // Check whether Composite2 is viable.
2583 InitializedEntity Entity2
2584 = InitializedEntity::InitializeTemporary(Composite2);
2585 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2586 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2587 if (!E1ToC2 || !E2ToC2)
2590 // Convert E1 to Composite2
2592 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
2593 if (E1Result.isInvalid())
2595 E1 = E1Result.takeAs<Expr>();
2597 // Convert E2 to Composite2
2599 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
2600 if (E2Result.isInvalid())
2602 E2 = E2Result.takeAs<Expr>();
2607 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
2608 if (!Context.getLangOptions().CPlusPlus)
2611 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2613 const RecordType *RT = E->getType()->getAs<RecordType>();
2617 // If this is the result of a call or an Objective-C message send expression,
2618 // our source might actually be a reference, in which case we shouldn't bind.
2619 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2620 if (CE->getCallReturnType()->isReferenceType())
2622 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2623 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2624 if (MD->getResultType()->isReferenceType())
2629 // That should be enough to guarantee that this type is complete.
2630 // If it has a trivial destructor, we can avoid the extra copy.
2631 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2632 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
2635 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
2636 ExprTemporaries.push_back(Temp);
2637 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
2638 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
2639 CheckDestructorAccess(E->getExprLoc(), Destructor,
2640 PDiag(diag::err_access_dtor_temp)
2643 // FIXME: Add the temporary to the temporaries vector.
2644 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2647 Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
2648 assert(SubExpr && "sub expression can't be null!");
2650 // Check any implicit conversions within the expression.
2651 CheckImplicitConversions(SubExpr);
2653 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2654 assert(ExprTemporaries.size() >= FirstTemporary);
2655 if (ExprTemporaries.size() == FirstTemporary)
2658 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
2659 &ExprTemporaries[FirstTemporary],
2660 ExprTemporaries.size() - FirstTemporary);
2661 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2662 ExprTemporaries.end());
2668 Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) {
2669 if (SubExpr.isInvalid())
2672 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2675 FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2676 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2677 assert(ExprTemporaries.size() >= FirstTemporary);
2679 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2680 CXXTemporary **Temporaries =
2681 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2683 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2685 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2686 ExprTemporaries.end());
2692 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
2693 tok::TokenKind OpKind, ParsedType &ObjectType,
2694 bool &MayBePseudoDestructor) {
2695 // Since this might be a postfix expression, get rid of ParenListExprs.
2696 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2697 if (Result.isInvalid()) return ExprError();
2698 Base = Result.get();
2700 QualType BaseType = Base->getType();
2701 MayBePseudoDestructor = false;
2702 if (BaseType->isDependentType()) {
2703 // If we have a pointer to a dependent type and are using the -> operator,
2704 // the object type is the type that the pointer points to. We might still
2705 // have enough information about that type to do something useful.
2706 if (OpKind == tok::arrow)
2707 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2708 BaseType = Ptr->getPointeeType();
2710 ObjectType = ParsedType::make(BaseType);
2711 MayBePseudoDestructor = true;
2715 // C++ [over.match.oper]p8:
2716 // [...] When operator->returns, the operator-> is applied to the value
2717 // returned, with the original second operand.
2718 if (OpKind == tok::arrow) {
2719 // The set of types we've considered so far.
2720 llvm::SmallPtrSet<CanQualType,8> CTypes;
2721 llvm::SmallVector<SourceLocation, 8> Locations;
2722 CTypes.insert(Context.getCanonicalType(BaseType));
2724 while (BaseType->isRecordType()) {
2725 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
2726 if (Result.isInvalid())
2728 Base = Result.get();
2729 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
2730 Locations.push_back(OpCall->getDirectCallee()->getLocation());
2731 BaseType = Base->getType();
2732 CanQualType CBaseType = Context.getCanonicalType(BaseType);
2733 if (!CTypes.insert(CBaseType)) {
2734 Diag(OpLoc, diag::err_operator_arrow_circular);
2735 for (unsigned i = 0; i < Locations.size(); i++)
2736 Diag(Locations[i], diag::note_declared_at);
2741 if (BaseType->isPointerType())
2742 BaseType = BaseType->getPointeeType();
2745 // We could end up with various non-record types here, such as extended
2746 // vector types or Objective-C interfaces. Just return early and let
2747 // ActOnMemberReferenceExpr do the work.
2748 if (!BaseType->isRecordType()) {
2749 // C++ [basic.lookup.classref]p2:
2750 // [...] If the type of the object expression is of pointer to scalar
2751 // type, the unqualified-id is looked up in the context of the complete
2752 // postfix-expression.
2754 // This also indicates that we should be parsing a
2755 // pseudo-destructor-name.
2756 ObjectType = ParsedType();
2757 MayBePseudoDestructor = true;
2761 // The object type must be complete (or dependent).
2762 if (!BaseType->isDependentType() &&
2763 RequireCompleteType(OpLoc, BaseType,
2764 PDiag(diag::err_incomplete_member_access)))
2767 // C++ [basic.lookup.classref]p2:
2768 // If the id-expression in a class member access (5.2.5) is an
2769 // unqualified-id, and the type of the object expression is of a class
2770 // type C (or of pointer to a class type C), the unqualified-id is looked
2771 // up in the scope of class C. [...]
2772 ObjectType = ParsedType::make(BaseType);
2776 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2778 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2779 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
2780 << isa<CXXPseudoDestructorExpr>(MemExpr)
2781 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
2783 return ActOnCallExpr(/*Scope*/ 0,
2785 /*LPLoc*/ ExpectedLParenLoc,
2788 /*RPLoc*/ ExpectedLParenLoc);
2791 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
2792 SourceLocation OpLoc,
2793 tok::TokenKind OpKind,
2794 const CXXScopeSpec &SS,
2795 TypeSourceInfo *ScopeTypeInfo,
2796 SourceLocation CCLoc,
2797 SourceLocation TildeLoc,
2798 PseudoDestructorTypeStorage Destructed,
2799 bool HasTrailingLParen) {
2800 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
2802 // C++ [expr.pseudo]p2:
2803 // The left-hand side of the dot operator shall be of scalar type. The
2804 // left-hand side of the arrow operator shall be of pointer to scalar type.
2805 // This scalar type is the object type.
2806 QualType ObjectType = Base->getType();
2807 if (OpKind == tok::arrow) {
2808 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2809 ObjectType = Ptr->getPointeeType();
2810 } else if (!Base->isTypeDependent()) {
2811 // The user wrote "p->" when she probably meant "p."; fix it.
2812 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2813 << ObjectType << true
2814 << FixItHint::CreateReplacement(OpLoc, ".");
2815 if (isSFINAEContext())
2818 OpKind = tok::period;
2822 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2823 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2824 << ObjectType << Base->getSourceRange();
2828 // C++ [expr.pseudo]p2:
2829 // [...] The cv-unqualified versions of the object type and of the type
2830 // designated by the pseudo-destructor-name shall be the same type.
2831 if (DestructedTypeInfo) {
2832 QualType DestructedType = DestructedTypeInfo->getType();
2833 SourceLocation DestructedTypeStart
2834 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
2835 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2836 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2837 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2838 << ObjectType << DestructedType << Base->getSourceRange()
2839 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
2841 // Recover by setting the destructed type to the object type.
2842 DestructedType = ObjectType;
2843 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2844 DestructedTypeStart);
2845 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2849 // C++ [expr.pseudo]p2:
2850 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2853 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2855 // shall designate the same scalar type.
2856 if (ScopeTypeInfo) {
2857 QualType ScopeType = ScopeTypeInfo->getType();
2858 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2859 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
2861 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
2862 diag::err_pseudo_dtor_type_mismatch)
2863 << ObjectType << ScopeType << Base->getSourceRange()
2864 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
2866 ScopeType = QualType();
2872 = new (Context) CXXPseudoDestructorExpr(Context, Base,
2873 OpKind == tok::arrow, OpLoc,
2874 SS.getScopeRep(), SS.getRange(),
2880 if (HasTrailingLParen)
2881 return Owned(Result);
2883 return DiagnoseDtorReference(Destructed.getLocation(), Result);
2886 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
2887 SourceLocation OpLoc,
2888 tok::TokenKind OpKind,
2890 UnqualifiedId &FirstTypeName,
2891 SourceLocation CCLoc,
2892 SourceLocation TildeLoc,
2893 UnqualifiedId &SecondTypeName,
2894 bool HasTrailingLParen) {
2895 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2896 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2897 "Invalid first type name in pseudo-destructor");
2898 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2899 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2900 "Invalid second type name in pseudo-destructor");
2902 // C++ [expr.pseudo]p2:
2903 // The left-hand side of the dot operator shall be of scalar type. The
2904 // left-hand side of the arrow operator shall be of pointer to scalar type.
2905 // This scalar type is the object type.
2906 QualType ObjectType = Base->getType();
2907 if (OpKind == tok::arrow) {
2908 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2909 ObjectType = Ptr->getPointeeType();
2910 } else if (!ObjectType->isDependentType()) {
2911 // The user wrote "p->" when she probably meant "p."; fix it.
2912 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2913 << ObjectType << true
2914 << FixItHint::CreateReplacement(OpLoc, ".");
2915 if (isSFINAEContext())
2918 OpKind = tok::period;
2922 // Compute the object type that we should use for name lookup purposes. Only
2923 // record types and dependent types matter.
2924 ParsedType ObjectTypePtrForLookup;
2926 if (const Type *T = ObjectType->getAs<RecordType>())
2927 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
2928 else if (ObjectType->isDependentType())
2929 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
2932 // Convert the name of the type being destructed (following the ~) into a
2933 // type (with source-location information).
2934 QualType DestructedType;
2935 TypeSourceInfo *DestructedTypeInfo = 0;
2936 PseudoDestructorTypeStorage Destructed;
2937 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2938 ParsedType T = getTypeName(*SecondTypeName.Identifier,
2939 SecondTypeName.StartLocation,
2940 S, &SS, true, ObjectTypePtrForLookup);
2942 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2943 (!SS.isSet() && ObjectType->isDependentType()))) {
2944 // The name of the type being destroyed is a dependent name, and we
2945 // couldn't find anything useful in scope. Just store the identifier and
2946 // it's location, and we'll perform (qualified) name lookup again at
2947 // template instantiation time.
2948 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2949 SecondTypeName.StartLocation);
2951 Diag(SecondTypeName.StartLocation,
2952 diag::err_pseudo_dtor_destructor_non_type)
2953 << SecondTypeName.Identifier << ObjectType;
2954 if (isSFINAEContext())
2957 // Recover by assuming we had the right type all along.
2958 DestructedType = ObjectType;
2960 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
2962 // Resolve the template-id to a type.
2963 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
2964 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2965 TemplateId->getTemplateArgs(),
2966 TemplateId->NumArgs);
2967 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
2968 TemplateId->TemplateNameLoc,
2969 TemplateId->LAngleLoc,
2971 TemplateId->RAngleLoc);
2972 if (T.isInvalid() || !T.get()) {
2973 // Recover by assuming we had the right type all along.
2974 DestructedType = ObjectType;
2976 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
2979 // If we've performed some kind of recovery, (re-)build the type source
2981 if (!DestructedType.isNull()) {
2982 if (!DestructedTypeInfo)
2983 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
2984 SecondTypeName.StartLocation);
2985 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2988 // Convert the name of the scope type (the type prior to '::') into a type.
2989 TypeSourceInfo *ScopeTypeInfo = 0;
2991 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2992 FirstTypeName.Identifier) {
2993 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2994 ParsedType T = getTypeName(*FirstTypeName.Identifier,
2995 FirstTypeName.StartLocation,
2996 S, &SS, false, ObjectTypePtrForLookup);
2998 Diag(FirstTypeName.StartLocation,
2999 diag::err_pseudo_dtor_destructor_non_type)
3000 << FirstTypeName.Identifier << ObjectType;
3002 if (isSFINAEContext())
3005 // Just drop this type. It's unnecessary anyway.
3006 ScopeType = QualType();
3008 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
3010 // Resolve the template-id to a type.
3011 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
3012 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3013 TemplateId->getTemplateArgs(),
3014 TemplateId->NumArgs);
3015 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
3016 TemplateId->TemplateNameLoc,
3017 TemplateId->LAngleLoc,
3019 TemplateId->RAngleLoc);
3020 if (T.isInvalid() || !T.get()) {
3021 // Recover by dropping this type.
3022 ScopeType = QualType();
3024 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
3028 if (!ScopeType.isNull() && !ScopeTypeInfo)
3029 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3030 FirstTypeName.StartLocation);
3033 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
3034 ScopeTypeInfo, CCLoc, TildeLoc,
3035 Destructed, HasTrailingLParen);
3038 CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
3039 NamedDecl *FoundDecl,
3040 CXXMethodDecl *Method) {
3041 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3043 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3046 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3047 SourceLocation(), Method->getType());
3048 QualType ResultType = Method->getCallResultType();
3049 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3050 CXXMemberCallExpr *CE =
3051 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3056 ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
3057 if (!FullExpr) return ExprError();
3058 return MaybeCreateCXXExprWithTemporaries(FullExpr);