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/ScopeInfo.h"
20 #include "clang/Sema/TemplateDeduction.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "llvm/ADT/STLExtras.h"
31 using namespace clang;
34 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
36 SourceLocation NameLoc,
37 Scope *S, CXXScopeSpec &SS,
38 ParsedType ObjectTypePtr,
39 bool EnteringContext) {
40 // Determine where to perform name lookup.
42 // FIXME: This area of the standard is very messy, and the current
43 // wording is rather unclear about which scopes we search for the
44 // destructor name; see core issues 399 and 555. Issue 399 in
45 // particular shows where the current description of destructor name
46 // lookup is completely out of line with existing practice, e.g.,
47 // this appears to be ill-formed:
50 // template <typename T> struct S {
55 // void f(N::S<int>* s) {
56 // s->N::S<int>::~S();
59 // See also PR6358 and PR6359.
60 // For this reason, we're currently only doing the C++03 version of this
61 // code; the C++0x version has to wait until we get a proper spec.
63 DeclContext *LookupCtx = 0;
64 bool isDependent = false;
65 bool LookInScope = false;
67 // If we have an object type, it's because we are in a
68 // pseudo-destructor-expression or a member access expression, and
69 // we know what type we're looking for.
71 SearchType = GetTypeFromParser(ObjectTypePtr);
74 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
76 bool AlreadySearched = false;
77 bool LookAtPrefix = true;
78 // C++ [basic.lookup.qual]p6:
79 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
80 // the type-names are looked up as types in the scope designated by the
81 // nested-name-specifier. In a qualified-id of the form:
83 // ::[opt] nested-name-specifier ~ class-name
85 // where the nested-name-specifier designates a namespace scope, and in
86 // a qualified-id of the form:
88 // ::opt nested-name-specifier class-name :: ~ class-name
90 // the class-names are looked up as types in the scope designated by
91 // the nested-name-specifier.
93 // Here, we check the first case (completely) and determine whether the
94 // code below is permitted to look at the prefix of the
95 // nested-name-specifier.
96 DeclContext *DC = computeDeclContext(SS, EnteringContext);
97 if (DC && DC->isFileContext()) {
98 AlreadySearched = true;
101 } else if (DC && isa<CXXRecordDecl>(DC))
102 LookAtPrefix = false;
104 // The second case from the C++03 rules quoted further above.
105 NestedNameSpecifier *Prefix = 0;
106 if (AlreadySearched) {
107 // Nothing left to do.
108 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109 CXXScopeSpec PrefixSS;
110 PrefixSS.setScopeRep(Prefix);
111 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112 isDependent = isDependentScopeSpecifier(PrefixSS);
113 } else if (ObjectTypePtr) {
114 LookupCtx = computeDeclContext(SearchType);
115 isDependent = SearchType->isDependentType();
117 LookupCtx = computeDeclContext(SS, EnteringContext);
118 isDependent = LookupCtx && LookupCtx->isDependentContext();
122 } else if (ObjectTypePtr) {
123 // C++ [basic.lookup.classref]p3:
124 // If the unqualified-id is ~type-name, the type-name is looked up
125 // in the context of the entire postfix-expression. If the type T
126 // of the object expression is of a class type C, the type-name is
127 // also looked up in the scope of class C. At least one of the
128 // lookups shall find a name that refers to (possibly
130 LookupCtx = computeDeclContext(SearchType);
131 isDependent = SearchType->isDependentType();
132 assert((isDependent || !SearchType->isIncompleteType()) &&
133 "Caller should have completed object type");
137 // Perform lookup into the current scope (only).
141 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
142 for (unsigned Step = 0; Step != 2; ++Step) {
143 // Look for the name first in the computed lookup context (if we
144 // have one) and, if that fails to find a match, in the sope (if
145 // we're allowed to look there).
147 if (Step == 0 && LookupCtx)
148 LookupQualifiedName(Found, LookupCtx);
149 else if (Step == 1 && LookInScope && S)
150 LookupName(Found, S);
154 // FIXME: Should we be suppressing ambiguities here?
155 if (Found.isAmbiguous())
158 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
159 QualType T = Context.getTypeDeclType(Type);
161 if (SearchType.isNull() || SearchType->isDependentType() ||
162 Context.hasSameUnqualifiedType(T, SearchType)) {
163 // We found our type!
165 return ParsedType::make(T);
169 // If the name that we found is a class template name, and it is
170 // the same name as the template name in the last part of the
171 // nested-name-specifier (if present) or the object type, then
172 // this is the destructor for that class.
173 // FIXME: This is a workaround until we get real drafting for core
174 // issue 399, for which there isn't even an obvious direction.
175 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
176 QualType MemberOfType;
178 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
179 // Figure out the type of the context, if it has one.
180 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
181 MemberOfType = Context.getTypeDeclType(Record);
184 if (MemberOfType.isNull())
185 MemberOfType = SearchType;
187 if (MemberOfType.isNull())
190 // We're referring into a class template specialization. If the
191 // class template we found is the same as the template being
192 // specialized, we found what we are looking for.
193 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
194 if (ClassTemplateSpecializationDecl *Spec
195 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
196 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
197 Template->getCanonicalDecl())
198 return ParsedType::make(MemberOfType);
204 // We're referring to an unresolved class template
205 // specialization. Determine whether we class template we found
206 // is the same as the template being specialized or, if we don't
207 // know which template is being specialized, that it at least
208 // has the same name.
209 if (const TemplateSpecializationType *SpecType
210 = MemberOfType->getAs<TemplateSpecializationType>()) {
211 TemplateName SpecName = SpecType->getTemplateName();
213 // The class template we found is the same template being
215 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
216 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
217 return ParsedType::make(MemberOfType);
222 // The class template we found has the same name as the
223 // (dependent) template name being specialized.
224 if (DependentTemplateName *DepTemplate
225 = SpecName.getAsDependentTemplateName()) {
226 if (DepTemplate->isIdentifier() &&
227 DepTemplate->getIdentifier() == Template->getIdentifier())
228 return ParsedType::make(MemberOfType);
237 // We didn't find our type, but that's okay: it's dependent
239 NestedNameSpecifier *NNS = 0;
242 NNS = (NestedNameSpecifier *)SS.getScopeRep();
243 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
245 NNS = NestedNameSpecifier::Create(Context, &II);
246 Range = SourceRange(NameLoc);
249 QualType T = CheckTypenameType(ETK_None, NNS, II,
252 return ParsedType::make(T);
256 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
259 Diag(NameLoc, diag::err_destructor_class_name);
264 /// \brief Build a C++ typeid expression with a type operand.
265 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
266 SourceLocation TypeidLoc,
267 TypeSourceInfo *Operand,
268 SourceLocation RParenLoc) {
269 // C++ [expr.typeid]p4:
270 // The top-level cv-qualifiers of the lvalue expression or the type-id
271 // that is the operand of typeid are always ignored.
272 // If the type of the type-id is a class type or a reference to a class
273 // type, the class shall be completely-defined.
276 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
278 if (T->getAs<RecordType>() &&
279 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
282 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
284 SourceRange(TypeidLoc, RParenLoc)));
287 /// \brief Build a C++ typeid expression with an expression operand.
288 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
289 SourceLocation TypeidLoc,
291 SourceLocation RParenLoc) {
292 bool isUnevaluatedOperand = true;
293 if (E && !E->isTypeDependent()) {
294 QualType T = E->getType();
295 if (const RecordType *RecordT = T->getAs<RecordType>()) {
296 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
297 // C++ [expr.typeid]p3:
298 // [...] If the type of the expression is a class type, the class
299 // shall be completely-defined.
300 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303 // C++ [expr.typeid]p3:
304 // When typeid is applied to an expression other than an glvalue of a
305 // polymorphic class type [...] [the] expression is an unevaluated
307 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
308 isUnevaluatedOperand = false;
310 // We require a vtable to query the type at run time.
311 MarkVTableUsed(TypeidLoc, RecordD);
315 // C++ [expr.typeid]p4:
316 // [...] If the type of the type-id is a reference to a possibly
317 // cv-qualified type, the result of the typeid expression refers to a
318 // std::type_info object representing the cv-unqualified referenced
321 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
322 if (!Context.hasSameType(T, UnqualT)) {
324 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
328 // If this is an unevaluated operand, clear out the set of
329 // declaration references we have been computing and eliminate any
330 // temporaries introduced in its computation.
331 if (isUnevaluatedOperand)
332 ExprEvalContexts.back().Context = Unevaluated;
334 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
336 SourceRange(TypeidLoc, RParenLoc)));
339 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
341 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
342 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
343 // Find the std::type_info type.
345 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
347 if (!CXXTypeInfoDecl) {
348 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
349 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
350 LookupQualifiedName(R, getStdNamespace());
351 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
352 if (!CXXTypeInfoDecl)
353 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
356 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
359 // The operand is a type; handle it as such.
360 TypeSourceInfo *TInfo = 0;
361 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
367 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
369 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
372 // The operand is an expression.
373 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
376 /// Retrieve the UuidAttr associated with QT.
377 static UuidAttr *GetUuidAttrOfType(QualType QT) {
378 // Optionally remove one level of pointer, reference or array indirection.
379 const Type *Ty = QT.getTypePtr();;
380 if (QT->isPointerType() || QT->isReferenceType())
381 Ty = QT->getPointeeType().getTypePtr();
382 else if (QT->isArrayType())
383 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
385 // Loop all class definition and declaration looking for an uuid attribute.
386 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
388 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
390 RD = RD->getPreviousDeclaration();
395 /// \brief Build a Microsoft __uuidof expression with a type operand.
396 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
397 SourceLocation TypeidLoc,
398 TypeSourceInfo *Operand,
399 SourceLocation RParenLoc) {
400 if (!Operand->getType()->isDependentType()) {
401 if (!GetUuidAttrOfType(Operand->getType()))
402 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
405 // FIXME: add __uuidof semantic analysis for type operand.
406 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
408 SourceRange(TypeidLoc, RParenLoc)));
411 /// \brief Build a Microsoft __uuidof expression with an expression operand.
412 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
413 SourceLocation TypeidLoc,
415 SourceLocation RParenLoc) {
416 if (!E->getType()->isDependentType()) {
417 if (!GetUuidAttrOfType(E->getType()) &&
418 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
419 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
421 // FIXME: add __uuidof semantic analysis for type operand.
422 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
424 SourceRange(TypeidLoc, RParenLoc)));
427 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
429 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
430 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
431 // If MSVCGuidDecl has not been cached, do the lookup.
433 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
434 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
435 LookupQualifiedName(R, Context.getTranslationUnitDecl());
436 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
438 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
441 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
444 // The operand is a type; handle it as such.
445 TypeSourceInfo *TInfo = 0;
446 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
452 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
454 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
457 // The operand is an expression.
458 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
461 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
463 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
464 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
465 "Unknown C++ Boolean value!");
466 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
467 Context.BoolTy, OpLoc));
470 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
472 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
473 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
476 /// ActOnCXXThrow - Parse throw expressions.
478 Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
479 if (!getLangOptions().Exceptions)
480 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
482 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
484 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
487 /// CheckCXXThrowOperand - Validate the operand of a throw.
488 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
489 // C++ [except.throw]p3:
490 // A throw-expression initializes a temporary object, called the exception
491 // object, the type of which is determined by removing any top-level
492 // cv-qualifiers from the static type of the operand of throw and adjusting
493 // the type from "array of T" or "function returning T" to "pointer to T"
494 // or "pointer to function returning T", [...]
495 if (E->getType().hasQualifiers())
496 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
499 DefaultFunctionArrayConversion(E);
501 // If the type of the exception would be an incomplete type or a pointer
502 // to an incomplete type other than (cv) void the program is ill-formed.
503 QualType Ty = E->getType();
504 bool isPointer = false;
505 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
506 Ty = Ptr->getPointeeType();
509 if (!isPointer || !Ty->isVoidType()) {
510 if (RequireCompleteType(ThrowLoc, Ty,
511 PDiag(isPointer ? diag::err_throw_incomplete_ptr
512 : diag::err_throw_incomplete)
513 << E->getSourceRange()))
516 if (RequireNonAbstractType(ThrowLoc, E->getType(),
517 PDiag(diag::err_throw_abstract_type)
518 << E->getSourceRange()))
522 // Initialize the exception result. This implicitly weeds out
523 // abstract types or types with inaccessible copy constructors.
524 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
526 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
527 InitializedEntity Entity =
528 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
530 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
534 E = Res.takeAs<Expr>();
536 // If the exception has class type, we need additional handling.
537 const RecordType *RecordTy = Ty->getAs<RecordType>();
540 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
542 // If we are throwing a polymorphic class type or pointer thereof,
543 // exception handling will make use of the vtable.
544 MarkVTableUsed(ThrowLoc, RD);
546 // If a pointer is thrown, the referenced object will not be destroyed.
550 // If the class has a non-trivial destructor, we must be able to call it.
551 if (RD->hasTrivialDestructor())
554 CXXDestructorDecl *Destructor
555 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
559 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
560 CheckDestructorAccess(E->getExprLoc(), Destructor,
561 PDiag(diag::err_access_dtor_exception) << Ty);
565 CXXMethodDecl *Sema::tryCaptureCXXThis() {
566 // Ignore block scopes: we can capture through them.
567 // Ignore nested enum scopes: we'll diagnose non-constant expressions
568 // where they're invalid, and other uses are legitimate.
569 // Don't ignore nested class scopes: you can't use 'this' in a local class.
570 DeclContext *DC = CurContext;
572 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
573 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
577 // If we're not in an instance method, error out.
578 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
579 if (!method || !method->isInstance())
582 // Mark that we're closing on 'this' in all the block scopes, if applicable.
583 for (unsigned idx = FunctionScopes.size() - 1;
584 isa<BlockScopeInfo>(FunctionScopes[idx]);
586 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
591 ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
592 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
593 /// is a non-lvalue expression whose value is the address of the object for
594 /// which the function is called.
596 CXXMethodDecl *method = tryCaptureCXXThis();
597 if (!method) return Diag(loc, diag::err_invalid_this_use);
599 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
600 /*isImplicit=*/false));
604 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
605 SourceLocation LParenLoc,
607 SourceLocation RParenLoc) {
611 TypeSourceInfo *TInfo;
612 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
614 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
616 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
619 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
620 /// Can be interpreted either as function-style casting ("int(x)")
621 /// or class type construction ("ClassType(x,y,z)")
622 /// or creation of a value-initialized type ("int()").
624 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
625 SourceLocation LParenLoc,
627 SourceLocation RParenLoc) {
628 QualType Ty = TInfo->getType();
629 unsigned NumExprs = exprs.size();
630 Expr **Exprs = (Expr**)exprs.get();
631 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
632 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
634 if (Ty->isDependentType() ||
635 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
638 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
644 if (Ty->isArrayType())
645 return ExprError(Diag(TyBeginLoc,
646 diag::err_value_init_for_array_type) << FullRange);
647 if (!Ty->isVoidType() &&
648 RequireCompleteType(TyBeginLoc, Ty,
649 PDiag(diag::err_invalid_incomplete_type_use)
653 if (RequireNonAbstractType(TyBeginLoc, Ty,
654 diag::err_allocation_of_abstract_type))
658 // C++ [expr.type.conv]p1:
659 // If the expression list is a single expression, the type conversion
660 // expression is equivalent (in definedness, and if defined in meaning) to the
661 // corresponding cast expression.
664 CastKind Kind = CK_Invalid;
665 ExprValueKind VK = VK_RValue;
666 CXXCastPath BasePath;
667 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
669 /*FunctionalStyle=*/true))
674 return Owned(CXXFunctionalCastExpr::Create(Context,
675 Ty.getNonLValueExprType(Context),
676 VK, TInfo, TyBeginLoc, Kind,
681 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
682 InitializationKind Kind
683 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
684 LParenLoc, RParenLoc)
685 : InitializationKind::CreateValue(TyBeginLoc,
686 LParenLoc, RParenLoc);
687 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
688 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
690 // FIXME: Improve AST representation?
694 /// doesUsualArrayDeleteWantSize - Answers whether the usual
695 /// operator delete[] for the given type has a size_t parameter.
696 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
697 QualType allocType) {
698 const RecordType *record =
699 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
700 if (!record) return false;
702 // Try to find an operator delete[] in class scope.
704 DeclarationName deleteName =
705 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
706 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
707 S.LookupQualifiedName(ops, record->getDecl());
709 // We're just doing this for information.
710 ops.suppressDiagnostics();
712 // Very likely: there's no operator delete[].
713 if (ops.empty()) return false;
715 // If it's ambiguous, it should be illegal to call operator delete[]
716 // on this thing, so it doesn't matter if we allocate extra space or not.
717 if (ops.isAmbiguous()) return false;
719 LookupResult::Filter filter = ops.makeFilter();
720 while (filter.hasNext()) {
721 NamedDecl *del = filter.next()->getUnderlyingDecl();
723 // C++0x [basic.stc.dynamic.deallocation]p2:
724 // A template instance is never a usual deallocation function,
725 // regardless of its signature.
726 if (isa<FunctionTemplateDecl>(del)) {
731 // C++0x [basic.stc.dynamic.deallocation]p2:
732 // If class T does not declare [an operator delete[] with one
733 // parameter] but does declare a member deallocation function
734 // named operator delete[] with exactly two parameters, the
735 // second of which has type std::size_t, then this function
736 // is a usual deallocation function.
737 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
744 if (!ops.isSingleResult()) return false;
746 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
747 return (del->getNumParams() == 2);
750 /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
751 /// @code new (memory) int[size][4] @endcode
753 /// @code ::new Foo(23, "hello") @endcode
754 /// For the interpretation of this heap of arguments, consult the base version.
756 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
757 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
758 SourceLocation PlacementRParen, SourceRange TypeIdParens,
759 Declarator &D, SourceLocation ConstructorLParen,
760 MultiExprArg ConstructorArgs,
761 SourceLocation ConstructorRParen) {
762 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
765 // If the specified type is an array, unwrap it and save the expression.
766 if (D.getNumTypeObjects() > 0 &&
767 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
768 DeclaratorChunk &Chunk = D.getTypeObject(0);
769 if (TypeContainsAuto)
770 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
771 << D.getSourceRange());
772 if (Chunk.Arr.hasStatic)
773 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
774 << D.getSourceRange());
775 if (!Chunk.Arr.NumElts)
776 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
777 << D.getSourceRange());
779 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
780 D.DropFirstTypeObject();
783 // Every dimension shall be of constant size.
785 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
786 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
789 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
790 if (Expr *NumElts = (Expr *)Array.NumElts) {
791 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
792 !NumElts->isIntegerConstantExpr(Context)) {
793 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
794 << NumElts->getSourceRange();
801 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
803 QualType AllocType = TInfo->getType();
804 if (D.isInvalidType())
807 return BuildCXXNew(StartLoc, UseGlobal,
816 move(ConstructorArgs),
822 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
823 SourceLocation PlacementLParen,
824 MultiExprArg PlacementArgs,
825 SourceLocation PlacementRParen,
826 SourceRange TypeIdParens,
828 TypeSourceInfo *AllocTypeInfo,
830 SourceLocation ConstructorLParen,
831 MultiExprArg ConstructorArgs,
832 SourceLocation ConstructorRParen,
833 bool TypeMayContainAuto) {
834 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
836 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
837 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
838 if (ConstructorArgs.size() == 0)
839 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
840 << AllocType << TypeRange);
841 if (ConstructorArgs.size() != 1) {
842 Expr *FirstBad = ConstructorArgs.get()[1];
843 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
844 diag::err_auto_new_ctor_multiple_expressions)
845 << AllocType << TypeRange);
847 QualType DeducedType;
848 if (!DeduceAutoType(AllocType, ConstructorArgs.get()[0], DeducedType))
849 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
851 << ConstructorArgs.get()[0]->getType()
853 << ConstructorArgs.get()[0]->getSourceRange());
855 AllocType = DeducedType;
856 AllocTypeInfo = Context.getTrivialTypeSourceInfo(AllocType, StartLoc);
859 // Per C++0x [expr.new]p5, the type being constructed may be a
860 // typedef of an array type.
862 if (const ConstantArrayType *Array
863 = Context.getAsConstantArrayType(AllocType)) {
864 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
865 Context.getSizeType(),
867 AllocType = Array->getElementType();
871 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
874 QualType ResultType = Context.getPointerType(AllocType);
876 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
877 // or enumeration type with a non-negative value."
878 if (ArraySize && !ArraySize->isTypeDependent()) {
880 QualType SizeType = ArraySize->getType();
882 ExprResult ConvertedSize
883 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
884 PDiag(diag::err_array_size_not_integral),
885 PDiag(diag::err_array_size_incomplete_type)
886 << ArraySize->getSourceRange(),
887 PDiag(diag::err_array_size_explicit_conversion),
888 PDiag(diag::note_array_size_conversion),
889 PDiag(diag::err_array_size_ambiguous_conversion),
890 PDiag(diag::note_array_size_conversion),
891 PDiag(getLangOptions().CPlusPlus0x? 0
892 : diag::ext_array_size_conversion));
893 if (ConvertedSize.isInvalid())
896 ArraySize = ConvertedSize.take();
897 SizeType = ArraySize->getType();
898 if (!SizeType->isIntegralOrUnscopedEnumerationType())
901 // Let's see if this is a constant < 0. If so, we reject it out of hand.
902 // We don't care about special rules, so we tell the machinery it's not
903 // evaluated - it gives us a result in more cases.
904 if (!ArraySize->isValueDependent()) {
906 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
907 if (Value < llvm::APSInt(
908 llvm::APInt::getNullValue(Value.getBitWidth()),
910 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
911 diag::err_typecheck_negative_array_size)
912 << ArraySize->getSourceRange());
914 if (!AllocType->isDependentType()) {
915 unsigned ActiveSizeBits
916 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
917 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
918 Diag(ArraySize->getSourceRange().getBegin(),
919 diag::err_array_too_large)
920 << Value.toString(10)
921 << ArraySize->getSourceRange();
925 } else if (TypeIdParens.isValid()) {
926 // Can't have dynamic array size when the type-id is in parentheses.
927 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
928 << ArraySize->getSourceRange()
929 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
930 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
932 TypeIdParens = SourceRange();
936 ImpCastExprToType(ArraySize, Context.getSizeType(),
940 FunctionDecl *OperatorNew = 0;
941 FunctionDecl *OperatorDelete = 0;
942 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
943 unsigned NumPlaceArgs = PlacementArgs.size();
945 if (!AllocType->isDependentType() &&
946 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
947 FindAllocationFunctions(StartLoc,
948 SourceRange(PlacementLParen, PlacementRParen),
949 UseGlobal, AllocType, ArraySize, PlaceArgs,
950 NumPlaceArgs, OperatorNew, OperatorDelete))
953 // If this is an array allocation, compute whether the usual array
954 // deallocation function for the type has a size_t parameter.
955 bool UsualArrayDeleteWantsSize = false;
956 if (ArraySize && !AllocType->isDependentType())
957 UsualArrayDeleteWantsSize
958 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
960 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
962 // Add default arguments, if any.
963 const FunctionProtoType *Proto =
964 OperatorNew->getType()->getAs<FunctionProtoType>();
965 VariadicCallType CallType =
966 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
968 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
969 Proto, 1, PlaceArgs, NumPlaceArgs,
970 AllPlaceArgs, CallType))
973 NumPlaceArgs = AllPlaceArgs.size();
974 if (NumPlaceArgs > 0)
975 PlaceArgs = &AllPlaceArgs[0];
978 bool Init = ConstructorLParen.isValid();
979 // --- Choosing a constructor ---
980 CXXConstructorDecl *Constructor = 0;
981 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
982 unsigned NumConsArgs = ConstructorArgs.size();
983 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
985 // Array 'new' can't have any initializers.
986 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
987 SourceRange InitRange(ConsArgs[0]->getLocStart(),
988 ConsArgs[NumConsArgs - 1]->getLocEnd());
990 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
994 if (!AllocType->isDependentType() &&
995 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
996 // C++0x [expr.new]p15:
997 // A new-expression that creates an object of type T initializes that
998 // object as follows:
999 InitializationKind Kind
1000 // - If the new-initializer is omitted, the object is default-
1001 // initialized (8.5); if no initialization is performed,
1002 // the object has indeterminate value
1003 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
1004 // - Otherwise, the new-initializer is interpreted according to the
1005 // initialization rules of 8.5 for direct-initialization.
1006 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1010 InitializedEntity Entity
1011 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1012 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
1013 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1014 move(ConstructorArgs));
1015 if (FullInit.isInvalid())
1018 // FullInit is our initializer; walk through it to determine if it's a
1019 // constructor call, which CXXNewExpr handles directly.
1020 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1021 if (CXXBindTemporaryExpr *Binder
1022 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1023 FullInitExpr = Binder->getSubExpr();
1024 if (CXXConstructExpr *Construct
1025 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1026 Constructor = Construct->getConstructor();
1027 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1028 AEnd = Construct->arg_end();
1030 ConvertedConstructorArgs.push_back(*A);
1032 // Take the converted initializer.
1033 ConvertedConstructorArgs.push_back(FullInit.release());
1036 // No initialization required.
1039 // Take the converted arguments and use them for the new expression.
1040 NumConsArgs = ConvertedConstructorArgs.size();
1041 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
1044 // Mark the new and delete operators as referenced.
1046 MarkDeclarationReferenced(StartLoc, OperatorNew);
1048 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1050 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
1052 PlacementArgs.release();
1053 ConstructorArgs.release();
1055 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1056 PlaceArgs, NumPlaceArgs, TypeIdParens,
1057 ArraySize, Constructor, Init,
1058 ConsArgs, NumConsArgs, OperatorDelete,
1059 UsualArrayDeleteWantsSize,
1060 ResultType, AllocTypeInfo,
1062 Init ? ConstructorRParen :
1064 ConstructorLParen, ConstructorRParen));
1067 /// CheckAllocatedType - Checks that a type is suitable as the allocated type
1068 /// in a new-expression.
1069 /// dimension off and stores the size expression in ArraySize.
1070 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1072 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1073 // abstract class type or array thereof.
1074 if (AllocType->isFunctionType())
1075 return Diag(Loc, diag::err_bad_new_type)
1076 << AllocType << 0 << R;
1077 else if (AllocType->isReferenceType())
1078 return Diag(Loc, diag::err_bad_new_type)
1079 << AllocType << 1 << R;
1080 else if (!AllocType->isDependentType() &&
1081 RequireCompleteType(Loc, AllocType,
1082 PDiag(diag::err_new_incomplete_type)
1085 else if (RequireNonAbstractType(Loc, AllocType,
1086 diag::err_allocation_of_abstract_type))
1088 else if (AllocType->isVariablyModifiedType())
1089 return Diag(Loc, diag::err_variably_modified_new_type)
1095 /// \brief Determine whether the given function is a non-placement
1096 /// deallocation function.
1097 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1098 if (FD->isInvalidDecl())
1101 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1102 return Method->isUsualDeallocationFunction();
1104 return ((FD->getOverloadedOperator() == OO_Delete ||
1105 FD->getOverloadedOperator() == OO_Array_Delete) &&
1106 FD->getNumParams() == 1);
1109 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1110 /// that are appropriate for the allocation.
1111 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1112 bool UseGlobal, QualType AllocType,
1113 bool IsArray, Expr **PlaceArgs,
1114 unsigned NumPlaceArgs,
1115 FunctionDecl *&OperatorNew,
1116 FunctionDecl *&OperatorDelete) {
1117 // --- Choosing an allocation function ---
1118 // C++ 5.3.4p8 - 14 & 18
1119 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1120 // in the scope of the allocated class.
1121 // 2) If an array size is given, look for operator new[], else look for
1123 // 3) The first argument is always size_t. Append the arguments from the
1126 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1127 // We don't care about the actual value of this argument.
1128 // FIXME: Should the Sema create the expression and embed it in the syntax
1129 // tree? Or should the consumer just recalculate the value?
1130 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1131 Context.Target.getPointerWidth(0)),
1132 Context.getSizeType(),
1134 AllocArgs[0] = &Size;
1135 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1137 // C++ [expr.new]p8:
1138 // If the allocated type is a non-array type, the allocation
1139 // function's name is operator new and the deallocation function's
1140 // name is operator delete. If the allocated type is an array
1141 // type, the allocation function's name is operator new[] and the
1142 // deallocation function's name is operator delete[].
1143 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1144 IsArray ? OO_Array_New : OO_New);
1145 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1146 IsArray ? OO_Array_Delete : OO_Delete);
1148 QualType AllocElemType = Context.getBaseElementType(AllocType);
1150 if (AllocElemType->isRecordType() && !UseGlobal) {
1151 CXXRecordDecl *Record
1152 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1153 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1154 AllocArgs.size(), Record, /*AllowMissing=*/true,
1159 // Didn't find a member overload. Look for a global one.
1160 DeclareGlobalNewDelete();
1161 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1162 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1163 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1168 // We don't need an operator delete if we're running under
1170 if (!getLangOptions().Exceptions) {
1175 // FindAllocationOverload can change the passed in arguments, so we need to
1177 if (NumPlaceArgs > 0)
1178 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1180 // C++ [expr.new]p19:
1182 // If the new-expression begins with a unary :: operator, the
1183 // deallocation function's name is looked up in the global
1184 // scope. Otherwise, if the allocated type is a class type T or an
1185 // array thereof, the deallocation function's name is looked up in
1186 // the scope of T. If this lookup fails to find the name, or if
1187 // the allocated type is not a class type or array thereof, the
1188 // deallocation function's name is looked up in the global scope.
1189 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1190 if (AllocElemType->isRecordType() && !UseGlobal) {
1192 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1193 LookupQualifiedName(FoundDelete, RD);
1195 if (FoundDelete.isAmbiguous())
1196 return true; // FIXME: clean up expressions?
1198 if (FoundDelete.empty()) {
1199 DeclareGlobalNewDelete();
1200 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1203 FoundDelete.suppressDiagnostics();
1205 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1207 // Whether we're looking for a placement operator delete is dictated
1208 // by whether we selected a placement operator new, not by whether
1209 // we had explicit placement arguments. This matters for things like
1210 // struct A { void *operator new(size_t, int = 0); ... };
1212 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1214 if (isPlacementNew) {
1215 // C++ [expr.new]p20:
1216 // A declaration of a placement deallocation function matches the
1217 // declaration of a placement allocation function if it has the
1218 // same number of parameters and, after parameter transformations
1219 // (8.3.5), all parameter types except the first are
1222 // To perform this comparison, we compute the function type that
1223 // the deallocation function should have, and use that type both
1224 // for template argument deduction and for comparison purposes.
1226 // FIXME: this comparison should ignore CC and the like.
1227 QualType ExpectedFunctionType;
1229 const FunctionProtoType *Proto
1230 = OperatorNew->getType()->getAs<FunctionProtoType>();
1232 llvm::SmallVector<QualType, 4> ArgTypes;
1233 ArgTypes.push_back(Context.VoidPtrTy);
1234 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1235 ArgTypes.push_back(Proto->getArgType(I));
1237 FunctionProtoType::ExtProtoInfo EPI;
1238 EPI.Variadic = Proto->isVariadic();
1240 ExpectedFunctionType
1241 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1242 ArgTypes.size(), EPI);
1245 for (LookupResult::iterator D = FoundDelete.begin(),
1246 DEnd = FoundDelete.end();
1248 FunctionDecl *Fn = 0;
1249 if (FunctionTemplateDecl *FnTmpl
1250 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1251 // Perform template argument deduction to try to match the
1252 // expected function type.
1253 TemplateDeductionInfo Info(Context, StartLoc);
1254 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1257 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1259 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1260 Matches.push_back(std::make_pair(D.getPair(), Fn));
1263 // C++ [expr.new]p20:
1264 // [...] Any non-placement deallocation function matches a
1265 // non-placement allocation function. [...]
1266 for (LookupResult::iterator D = FoundDelete.begin(),
1267 DEnd = FoundDelete.end();
1269 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1270 if (isNonPlacementDeallocationFunction(Fn))
1271 Matches.push_back(std::make_pair(D.getPair(), Fn));
1275 // C++ [expr.new]p20:
1276 // [...] If the lookup finds a single matching deallocation
1277 // function, that function will be called; otherwise, no
1278 // deallocation function will be called.
1279 if (Matches.size() == 1) {
1280 OperatorDelete = Matches[0].second;
1282 // C++0x [expr.new]p20:
1283 // If the lookup finds the two-parameter form of a usual
1284 // deallocation function (3.7.4.2) and that function, considered
1285 // as a placement deallocation function, would have been
1286 // selected as a match for the allocation function, the program
1288 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1289 isNonPlacementDeallocationFunction(OperatorDelete)) {
1290 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1291 << SourceRange(PlaceArgs[0]->getLocStart(),
1292 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1293 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1296 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1304 /// FindAllocationOverload - Find an fitting overload for the allocation
1305 /// function in the specified scope.
1306 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1307 DeclarationName Name, Expr** Args,
1308 unsigned NumArgs, DeclContext *Ctx,
1309 bool AllowMissing, FunctionDecl *&Operator) {
1310 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1311 LookupQualifiedName(R, Ctx);
1315 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1319 if (R.isAmbiguous())
1322 R.suppressDiagnostics();
1324 OverloadCandidateSet Candidates(StartLoc);
1325 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1326 Alloc != AllocEnd; ++Alloc) {
1327 // Even member operator new/delete are implicitly treated as
1328 // static, so don't use AddMemberCandidate.
1329 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1331 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1332 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1333 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1335 /*SuppressUserConversions=*/false);
1339 FunctionDecl *Fn = cast<FunctionDecl>(D);
1340 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1341 /*SuppressUserConversions=*/false);
1344 // Do the resolution.
1345 OverloadCandidateSet::iterator Best;
1346 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1349 FunctionDecl *FnDecl = Best->Function;
1350 // The first argument is size_t, and the first parameter must be size_t,
1351 // too. This is checked on declaration and can be assumed. (It can't be
1352 // asserted on, though, since invalid decls are left in there.)
1353 // Watch out for variadic allocator function.
1354 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1355 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1357 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1359 FnDecl->getParamDecl(i)),
1362 if (Result.isInvalid())
1365 Args[i] = Result.takeAs<Expr>();
1368 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1372 case OR_No_Viable_Function:
1373 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1375 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1379 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1381 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1385 Diag(StartLoc, diag::err_ovl_deleted_call)
1386 << Best->Function->isDeleted()
1388 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1391 assert(false && "Unreachable, bad result from BestViableFunction");
1396 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1397 /// delete. These are:
1399 /// void* operator new(std::size_t) throw(std::bad_alloc);
1400 /// void* operator new[](std::size_t) throw(std::bad_alloc);
1401 /// void operator delete(void *) throw();
1402 /// void operator delete[](void *) throw();
1404 /// Note that the placement and nothrow forms of new are *not* implicitly
1405 /// declared. Their use requires including \<new\>.
1406 void Sema::DeclareGlobalNewDelete() {
1407 if (GlobalNewDeleteDeclared)
1410 // C++ [basic.std.dynamic]p2:
1411 // [...] The following allocation and deallocation functions (18.4) are
1412 // implicitly declared in global scope in each translation unit of a
1415 // void* operator new(std::size_t) throw(std::bad_alloc);
1416 // void* operator new[](std::size_t) throw(std::bad_alloc);
1417 // void operator delete(void*) throw();
1418 // void operator delete[](void*) throw();
1420 // These implicit declarations introduce only the function names operator
1421 // new, operator new[], operator delete, operator delete[].
1423 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1424 // "std" or "bad_alloc" as necessary to form the exception specification.
1425 // However, we do not make these implicit declarations visible to name
1428 // The "std::bad_alloc" class has not yet been declared, so build it
1430 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1431 getOrCreateStdNamespace(),
1433 &PP.getIdentifierTable().get("bad_alloc"),
1434 SourceLocation(), 0);
1435 getStdBadAlloc()->setImplicit(true);
1438 GlobalNewDeleteDeclared = true;
1440 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1441 QualType SizeT = Context.getSizeType();
1442 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1444 DeclareGlobalAllocationFunction(
1445 Context.DeclarationNames.getCXXOperatorName(OO_New),
1446 VoidPtr, SizeT, AssumeSaneOperatorNew);
1447 DeclareGlobalAllocationFunction(
1448 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1449 VoidPtr, SizeT, AssumeSaneOperatorNew);
1450 DeclareGlobalAllocationFunction(
1451 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1452 Context.VoidTy, VoidPtr);
1453 DeclareGlobalAllocationFunction(
1454 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1455 Context.VoidTy, VoidPtr);
1458 /// DeclareGlobalAllocationFunction - Declares a single implicit global
1459 /// allocation function if it doesn't already exist.
1460 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1461 QualType Return, QualType Argument,
1462 bool AddMallocAttr) {
1463 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1465 // Check if this function is already declared.
1467 DeclContext::lookup_iterator Alloc, AllocEnd;
1468 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1469 Alloc != AllocEnd; ++Alloc) {
1470 // Only look at non-template functions, as it is the predefined,
1471 // non-templated allocation function we are trying to declare here.
1472 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1473 QualType InitialParamType =
1474 Context.getCanonicalType(
1475 Func->getParamDecl(0)->getType().getUnqualifiedType());
1476 // FIXME: Do we need to check for default arguments here?
1477 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1478 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1479 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1486 QualType BadAllocType;
1487 bool HasBadAllocExceptionSpec
1488 = (Name.getCXXOverloadedOperator() == OO_New ||
1489 Name.getCXXOverloadedOperator() == OO_Array_New);
1490 if (HasBadAllocExceptionSpec) {
1491 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1492 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1495 FunctionProtoType::ExtProtoInfo EPI;
1496 EPI.HasExceptionSpec = true;
1497 if (HasBadAllocExceptionSpec) {
1498 EPI.NumExceptions = 1;
1499 EPI.Exceptions = &BadAllocType;
1502 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1503 FunctionDecl *Alloc =
1504 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
1505 FnType, /*TInfo=*/0, SC_None,
1506 SC_None, false, true);
1507 Alloc->setImplicit();
1510 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1512 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1513 0, Argument, /*TInfo=*/0,
1516 Alloc->setParams(&Param, 1);
1518 // FIXME: Also add this declaration to the IdentifierResolver, but
1519 // make sure it is at the end of the chain to coincide with the
1521 Context.getTranslationUnitDecl()->addDecl(Alloc);
1524 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1525 DeclarationName Name,
1526 FunctionDecl* &Operator) {
1527 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1528 // Try to find operator delete/operator delete[] in class scope.
1529 LookupQualifiedName(Found, RD);
1531 if (Found.isAmbiguous())
1534 Found.suppressDiagnostics();
1536 llvm::SmallVector<DeclAccessPair,4> Matches;
1537 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1539 NamedDecl *ND = (*F)->getUnderlyingDecl();
1541 // Ignore template operator delete members from the check for a usual
1542 // deallocation function.
1543 if (isa<FunctionTemplateDecl>(ND))
1546 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1547 Matches.push_back(F.getPair());
1550 // There's exactly one suitable operator; pick it.
1551 if (Matches.size() == 1) {
1552 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1553 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1557 // We found multiple suitable operators; complain about the ambiguity.
1558 } else if (!Matches.empty()) {
1559 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1562 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1563 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1564 Diag((*F)->getUnderlyingDecl()->getLocation(),
1565 diag::note_member_declared_here) << Name;
1569 // We did find operator delete/operator delete[] declarations, but
1570 // none of them were suitable.
1571 if (!Found.empty()) {
1572 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1575 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1577 Diag((*F)->getUnderlyingDecl()->getLocation(),
1578 diag::note_member_declared_here) << Name;
1583 // Look for a global declaration.
1584 DeclareGlobalNewDelete();
1585 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1587 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1588 Expr* DeallocArgs[1];
1589 DeallocArgs[0] = &Null;
1590 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1591 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1595 assert(Operator && "Did not find a deallocation function!");
1599 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1600 /// @code ::delete ptr; @endcode
1602 /// @code delete [] ptr; @endcode
1604 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1605 bool ArrayForm, Expr *Ex) {
1606 // C++ [expr.delete]p1:
1607 // The operand shall have a pointer type, or a class type having a single
1608 // conversion function to a pointer type. The result has type void.
1610 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1612 FunctionDecl *OperatorDelete = 0;
1613 bool ArrayFormAsWritten = ArrayForm;
1614 bool UsualArrayDeleteWantsSize = false;
1616 if (!Ex->isTypeDependent()) {
1617 QualType Type = Ex->getType();
1619 if (const RecordType *Record = Type->getAs<RecordType>()) {
1620 if (RequireCompleteType(StartLoc, Type,
1621 PDiag(diag::err_delete_incomplete_class_type)))
1624 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1626 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1627 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1628 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1629 E = Conversions->end(); I != E; ++I) {
1630 NamedDecl *D = I.getDecl();
1631 if (isa<UsingShadowDecl>(D))
1632 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1634 // Skip over templated conversion functions; they aren't considered.
1635 if (isa<FunctionTemplateDecl>(D))
1638 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1640 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1641 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1642 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1643 ObjectPtrConversions.push_back(Conv);
1645 if (ObjectPtrConversions.size() == 1) {
1646 // We have a single conversion to a pointer-to-object type. Perform
1648 // TODO: don't redo the conversion calculation.
1649 if (!PerformImplicitConversion(Ex,
1650 ObjectPtrConversions.front()->getConversionType(),
1652 Type = Ex->getType();
1655 else if (ObjectPtrConversions.size() > 1) {
1656 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1657 << Type << Ex->getSourceRange();
1658 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1659 NoteOverloadCandidate(ObjectPtrConversions[i]);
1664 if (!Type->isPointerType())
1665 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1666 << Type << Ex->getSourceRange());
1668 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1669 if (Pointee->isVoidType() && !isSFINAEContext()) {
1670 // The C++ standard bans deleting a pointer to a non-object type, which
1671 // effectively bans deletion of "void*". However, most compilers support
1672 // this, so we treat it as a warning unless we're in a SFINAE context.
1673 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1674 << Type << Ex->getSourceRange();
1675 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1676 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1677 << Type << Ex->getSourceRange());
1678 else if (!Pointee->isDependentType() &&
1679 RequireCompleteType(StartLoc, Pointee,
1680 PDiag(diag::warn_delete_incomplete)
1681 << Ex->getSourceRange()))
1684 // C++ [expr.delete]p2:
1685 // [Note: a pointer to a const type can be the operand of a
1686 // delete-expression; it is not necessary to cast away the constness
1687 // (5.2.11) of the pointer expression before it is used as the operand
1688 // of the delete-expression. ]
1689 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1692 if (Pointee->isArrayType() && !ArrayForm) {
1693 Diag(StartLoc, diag::warn_delete_array_type)
1694 << Type << Ex->getSourceRange()
1695 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1699 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1700 ArrayForm ? OO_Array_Delete : OO_Delete);
1702 QualType PointeeElem = Context.getBaseElementType(Pointee);
1703 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1704 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1707 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1710 // If we're allocating an array of records, check whether the
1711 // usual operator delete[] has a size_t parameter.
1713 // If the user specifically asked to use the global allocator,
1714 // we'll need to do the lookup into the class.
1716 UsualArrayDeleteWantsSize =
1717 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1719 // Otherwise, the usual operator delete[] should be the
1720 // function we just found.
1721 else if (isa<CXXMethodDecl>(OperatorDelete))
1722 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1725 if (!RD->hasTrivialDestructor())
1726 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1727 MarkDeclarationReferenced(StartLoc,
1728 const_cast<CXXDestructorDecl*>(Dtor));
1729 DiagnoseUseOfDecl(Dtor, StartLoc);
1733 if (!OperatorDelete) {
1734 // Look for a global declaration.
1735 DeclareGlobalNewDelete();
1736 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1737 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1738 &Ex, 1, TUDecl, /*AllowMissing=*/false,
1743 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1745 // Check access and ambiguity of operator delete and destructor.
1746 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1747 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1748 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1749 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1750 PDiag(diag::err_access_dtor) << PointeeElem);
1756 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1758 UsualArrayDeleteWantsSize,
1759 OperatorDelete, Ex, StartLoc));
1762 /// \brief Check the use of the given variable as a C++ condition in an if,
1763 /// while, do-while, or switch statement.
1764 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1765 SourceLocation StmtLoc,
1766 bool ConvertToBoolean) {
1767 QualType T = ConditionVar->getType();
1769 // C++ [stmt.select]p2:
1770 // The declarator shall not specify a function or an array.
1771 if (T->isFunctionType())
1772 return ExprError(Diag(ConditionVar->getLocation(),
1773 diag::err_invalid_use_of_function_type)
1774 << ConditionVar->getSourceRange());
1775 else if (T->isArrayType())
1776 return ExprError(Diag(ConditionVar->getLocation(),
1777 diag::err_invalid_use_of_array_type)
1778 << ConditionVar->getSourceRange());
1780 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1781 ConditionVar->getLocation(),
1782 ConditionVar->getType().getNonReferenceType(),
1784 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
1787 return Owned(Condition);
1790 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1791 bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1793 // The value of a condition that is an initialized declaration in a statement
1794 // other than a switch statement is the value of the declared variable
1795 // implicitly converted to type bool. If that conversion is ill-formed, the
1796 // program is ill-formed.
1797 // The value of a condition that is an expression is the value of the
1798 // expression, implicitly converted to bool.
1800 return PerformContextuallyConvertToBool(CondExpr);
1803 /// Helper function to determine whether this is the (deprecated) C++
1804 /// conversion from a string literal to a pointer to non-const char or
1805 /// non-const wchar_t (for narrow and wide string literals,
1808 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1809 // Look inside the implicit cast, if it exists.
1810 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1811 From = Cast->getSubExpr();
1813 // A string literal (2.13.4) that is not a wide string literal can
1814 // be converted to an rvalue of type "pointer to char"; a wide
1815 // string literal can be converted to an rvalue of type "pointer
1816 // to wchar_t" (C++ 4.2p2).
1817 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
1818 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1819 if (const BuiltinType *ToPointeeType
1820 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1821 // This conversion is considered only when there is an
1822 // explicit appropriate pointer target type (C++ 4.2p2).
1823 if (!ToPtrType->getPointeeType().hasQualifiers() &&
1824 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1825 (!StrLit->isWide() &&
1826 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1827 ToPointeeType->getKind() == BuiltinType::Char_S))))
1834 static ExprResult BuildCXXCastArgument(Sema &S,
1835 SourceLocation CastLoc,
1838 CXXMethodDecl *Method,
1839 NamedDecl *FoundDecl,
1842 default: assert(0 && "Unhandled cast kind!");
1843 case CK_ConstructorConversion: {
1844 ASTOwningVector<Expr*> ConstructorArgs(S);
1846 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1847 MultiExprArg(&From, 1),
1848 CastLoc, ConstructorArgs))
1852 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1853 move_arg(ConstructorArgs),
1854 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1856 if (Result.isInvalid())
1859 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1862 case CK_UserDefinedConversion: {
1863 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1865 // Create an implicit call expr that calls it.
1866 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
1867 if (Result.isInvalid())
1870 return S.MaybeBindToTemporary(Result.get());
1875 /// PerformImplicitConversion - Perform an implicit conversion of the
1876 /// expression From to the type ToType using the pre-computed implicit
1877 /// conversion sequence ICS. Returns true if there was an error, false
1878 /// otherwise. The expression From is replaced with the converted
1879 /// expression. Action is the kind of conversion we're performing,
1880 /// used in the error message.
1882 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1883 const ImplicitConversionSequence &ICS,
1884 AssignmentAction Action, bool CStyle) {
1885 switch (ICS.getKind()) {
1886 case ImplicitConversionSequence::StandardConversion:
1887 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
1892 case ImplicitConversionSequence::UserDefinedConversion: {
1894 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1896 QualType BeforeToType;
1897 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1898 CastKind = CK_UserDefinedConversion;
1900 // If the user-defined conversion is specified by a conversion function,
1901 // the initial standard conversion sequence converts the source type to
1902 // the implicit object parameter of the conversion function.
1903 BeforeToType = Context.getTagDeclType(Conv->getParent());
1905 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
1906 CastKind = CK_ConstructorConversion;
1907 // Do no conversion if dealing with ... for the first conversion.
1908 if (!ICS.UserDefined.EllipsisConversion) {
1909 // If the user-defined conversion is specified by a constructor, the
1910 // initial standard conversion sequence converts the source type to the
1911 // type required by the argument of the constructor
1912 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1915 // Watch out for elipsis conversion.
1916 if (!ICS.UserDefined.EllipsisConversion) {
1917 if (PerformImplicitConversion(From, BeforeToType,
1918 ICS.UserDefined.Before, AA_Converting,
1924 = BuildCXXCastArgument(*this,
1925 From->getLocStart(),
1926 ToType.getNonReferenceType(),
1927 CastKind, cast<CXXMethodDecl>(FD),
1928 ICS.UserDefined.FoundConversionFunction,
1931 if (CastArg.isInvalid())
1934 From = CastArg.takeAs<Expr>();
1936 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1937 AA_Converting, CStyle);
1940 case ImplicitConversionSequence::AmbiguousConversion:
1941 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
1942 PDiag(diag::err_typecheck_ambiguous_condition)
1943 << From->getSourceRange());
1946 case ImplicitConversionSequence::EllipsisConversion:
1947 assert(false && "Cannot perform an ellipsis conversion");
1950 case ImplicitConversionSequence::BadConversion:
1954 // Everything went well.
1958 /// PerformImplicitConversion - Perform an implicit conversion of the
1959 /// expression From to the type ToType by following the standard
1960 /// conversion sequence SCS. Returns true if there was an error, false
1961 /// otherwise. The expression From is replaced with the converted
1962 /// expression. Flavor is the context in which we're performing this
1963 /// conversion, for use in error messages.
1965 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1966 const StandardConversionSequence& SCS,
1967 AssignmentAction Action, bool CStyle) {
1968 // Overall FIXME: we are recomputing too many types here and doing far too
1969 // much extra work. What this means is that we need to keep track of more
1970 // information that is computed when we try the implicit conversion initially,
1971 // so that we don't need to recompute anything here.
1972 QualType FromType = From->getType();
1974 if (SCS.CopyConstructor) {
1975 // FIXME: When can ToType be a reference type?
1976 assert(!ToType->isReferenceType());
1977 if (SCS.Second == ICK_Derived_To_Base) {
1978 ASTOwningVector<Expr*> ConstructorArgs(*this);
1979 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1980 MultiExprArg(*this, &From, 1),
1981 /*FIXME:ConstructLoc*/SourceLocation(),
1984 ExprResult FromResult =
1985 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1986 ToType, SCS.CopyConstructor,
1987 move_arg(ConstructorArgs),
1989 CXXConstructExpr::CK_Complete,
1991 if (FromResult.isInvalid())
1993 From = FromResult.takeAs<Expr>();
1996 ExprResult FromResult =
1997 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1998 ToType, SCS.CopyConstructor,
1999 MultiExprArg(*this, &From, 1),
2001 CXXConstructExpr::CK_Complete,
2004 if (FromResult.isInvalid())
2007 From = FromResult.takeAs<Expr>();
2011 // Resolve overloaded function references.
2012 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2013 DeclAccessPair Found;
2014 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2019 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2022 From = FixOverloadedFunctionReference(From, Found, Fn);
2023 FromType = From->getType();
2026 // Perform the first implicit conversion.
2027 switch (SCS.First) {
2032 case ICK_Lvalue_To_Rvalue:
2033 // Should this get its own ICK?
2034 if (From->getObjectKind() == OK_ObjCProperty) {
2035 ConvertPropertyForRValue(From);
2036 if (!From->isGLValue()) break;
2039 // Check for trivial buffer overflows.
2040 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(From))
2041 CheckArrayAccess(AE);
2043 FromType = FromType.getUnqualifiedType();
2044 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2045 From, 0, VK_RValue);
2048 case ICK_Array_To_Pointer:
2049 FromType = Context.getArrayDecayedType(FromType);
2050 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
2053 case ICK_Function_To_Pointer:
2054 FromType = Context.getPointerType(FromType);
2055 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
2059 assert(false && "Improper first standard conversion");
2063 // Perform the second implicit conversion
2064 switch (SCS.Second) {
2066 // If both sides are functions (or pointers/references to them), there could
2067 // be incompatible exception declarations.
2068 if (CheckExceptionSpecCompatibility(From, ToType))
2070 // Nothing else to do.
2073 case ICK_NoReturn_Adjustment:
2074 // If both sides are functions (or pointers/references to them), there could
2075 // be incompatible exception declarations.
2076 if (CheckExceptionSpecCompatibility(From, ToType))
2079 ImpCastExprToType(From, ToType, CK_NoOp);
2082 case ICK_Integral_Promotion:
2083 case ICK_Integral_Conversion:
2084 ImpCastExprToType(From, ToType, CK_IntegralCast);
2087 case ICK_Floating_Promotion:
2088 case ICK_Floating_Conversion:
2089 ImpCastExprToType(From, ToType, CK_FloatingCast);
2092 case ICK_Complex_Promotion:
2093 case ICK_Complex_Conversion: {
2094 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2095 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2097 if (FromEl->isRealFloatingType()) {
2098 if (ToEl->isRealFloatingType())
2099 CK = CK_FloatingComplexCast;
2101 CK = CK_FloatingComplexToIntegralComplex;
2102 } else if (ToEl->isRealFloatingType()) {
2103 CK = CK_IntegralComplexToFloatingComplex;
2105 CK = CK_IntegralComplexCast;
2107 ImpCastExprToType(From, ToType, CK);
2111 case ICK_Floating_Integral:
2112 if (ToType->isRealFloatingType())
2113 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
2115 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
2118 case ICK_Compatible_Conversion:
2119 ImpCastExprToType(From, ToType, CK_NoOp);
2122 case ICK_Pointer_Conversion: {
2123 if (SCS.IncompatibleObjC && Action != AA_Casting) {
2124 // Diagnose incompatible Objective-C conversions
2125 Diag(From->getSourceRange().getBegin(),
2126 diag::ext_typecheck_convert_incompatible_pointer)
2127 << From->getType() << ToType << Action
2128 << From->getSourceRange();
2131 CastKind Kind = CK_Invalid;
2132 CXXCastPath BasePath;
2133 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2135 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
2139 case ICK_Pointer_Member: {
2140 CastKind Kind = CK_Invalid;
2141 CXXCastPath BasePath;
2142 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2144 if (CheckExceptionSpecCompatibility(From, ToType))
2146 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
2149 case ICK_Boolean_Conversion: {
2150 CastKind Kind = CK_Invalid;
2151 switch (FromType->getScalarTypeKind()) {
2152 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2153 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2154 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2155 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2156 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2157 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2158 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2161 ImpCastExprToType(From, Context.BoolTy, Kind);
2165 case ICK_Derived_To_Base: {
2166 CXXCastPath BasePath;
2167 if (CheckDerivedToBaseConversion(From->getType(),
2168 ToType.getNonReferenceType(),
2169 From->getLocStart(),
2170 From->getSourceRange(),
2175 ImpCastExprToType(From, ToType.getNonReferenceType(),
2176 CK_DerivedToBase, CastCategory(From),
2181 case ICK_Vector_Conversion:
2182 ImpCastExprToType(From, ToType, CK_BitCast);
2185 case ICK_Vector_Splat:
2186 ImpCastExprToType(From, ToType, CK_VectorSplat);
2189 case ICK_Complex_Real:
2190 // Case 1. x -> _Complex y
2191 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2192 QualType ElType = ToComplex->getElementType();
2193 bool isFloatingComplex = ElType->isRealFloatingType();
2196 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2198 } else if (From->getType()->isRealFloatingType()) {
2199 ImpCastExprToType(From, ElType,
2200 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2202 assert(From->getType()->isIntegerType());
2203 ImpCastExprToType(From, ElType,
2204 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2207 ImpCastExprToType(From, ToType,
2208 isFloatingComplex ? CK_FloatingRealToComplex
2209 : CK_IntegralRealToComplex);
2211 // Case 2. _Complex x -> y
2213 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2214 assert(FromComplex);
2216 QualType ElType = FromComplex->getElementType();
2217 bool isFloatingComplex = ElType->isRealFloatingType();
2220 ImpCastExprToType(From, ElType,
2221 isFloatingComplex ? CK_FloatingComplexToReal
2222 : CK_IntegralComplexToReal);
2225 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2227 } else if (ToType->isRealFloatingType()) {
2228 ImpCastExprToType(From, ToType,
2229 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2231 assert(ToType->isIntegerType());
2232 ImpCastExprToType(From, ToType,
2233 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2238 case ICK_Block_Pointer_Conversion: {
2239 ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue);
2243 case ICK_Lvalue_To_Rvalue:
2244 case ICK_Array_To_Pointer:
2245 case ICK_Function_To_Pointer:
2246 case ICK_Qualification:
2247 case ICK_Num_Conversion_Kinds:
2248 assert(false && "Improper second standard conversion");
2252 switch (SCS.Third) {
2257 case ICK_Qualification: {
2258 // The qualification keeps the category of the inner expression, unless the
2259 // target type isn't a reference.
2260 ExprValueKind VK = ToType->isReferenceType() ?
2261 CastCategory(From) : VK_RValue;
2262 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2265 if (SCS.DeprecatedStringLiteralToCharPtr)
2266 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2267 << ToType.getNonReferenceType();
2273 assert(false && "Improper third standard conversion");
2280 ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2281 SourceLocation KWLoc,
2283 SourceLocation RParen) {
2284 TypeSourceInfo *TSInfo;
2285 QualType T = GetTypeFromParser(Ty, &TSInfo);
2288 TSInfo = Context.getTrivialTypeSourceInfo(T);
2289 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2292 static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2293 SourceLocation KeyLoc) {
2294 // FIXME: For many of these traits, we need a complete type before we can
2295 // check these properties.
2296 assert(!T->isDependentType() &&
2297 "Cannot evaluate traits for dependent types.");
2298 ASTContext &C = Self.Context;
2300 default: assert(false && "Unknown type trait or not implemented");
2301 case UTT_IsPOD: return T->isPODType();
2302 case UTT_IsLiteral: return T->isLiteralType();
2303 case UTT_IsClass: // Fallthrough
2305 if (const RecordType *Record = T->getAs<RecordType>()) {
2306 bool Union = Record->getDecl()->isUnion();
2307 return UTT == UTT_IsUnion ? Union : !Union;
2310 case UTT_IsEnum: return T->isEnumeralType();
2311 case UTT_IsPolymorphic:
2312 if (const RecordType *Record = T->getAs<RecordType>()) {
2313 // Type traits are only parsed in C++, so we've got CXXRecords.
2314 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2317 case UTT_IsAbstract:
2318 if (const RecordType *RT = T->getAs<RecordType>())
2319 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2322 if (const RecordType *Record = T->getAs<RecordType>()) {
2323 return !Record->getDecl()->isUnion()
2324 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2327 case UTT_HasTrivialConstructor:
2328 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2329 // If __is_pod (type) is true then the trait is true, else if type is
2330 // a cv class or union type (or array thereof) with a trivial default
2331 // constructor ([class.ctor]) then the trait is true, else it is false.
2334 if (const RecordType *RT =
2335 C.getBaseElementType(T)->getAs<RecordType>())
2336 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2338 case UTT_HasTrivialCopy:
2339 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2340 // If __is_pod (type) is true or type is a reference type then
2341 // the trait is true, else if type is a cv class or union type
2342 // with a trivial copy constructor ([class.copy]) then the trait
2343 // is true, else it is false.
2344 if (T->isPODType() || T->isReferenceType())
2346 if (const RecordType *RT = T->getAs<RecordType>())
2347 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2349 case UTT_HasTrivialAssign:
2350 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2351 // If type is const qualified or is a reference type then the
2352 // trait is false. Otherwise if __is_pod (type) is true then the
2353 // trait is true, else if type is a cv class or union type with
2354 // a trivial copy assignment ([class.copy]) then the trait is
2355 // true, else it is false.
2356 // Note: the const and reference restrictions are interesting,
2357 // given that const and reference members don't prevent a class
2358 // from having a trivial copy assignment operator (but do cause
2359 // errors if the copy assignment operator is actually used, q.v.
2360 // [class.copy]p12).
2362 if (C.getBaseElementType(T).isConstQualified())
2366 if (const RecordType *RT = T->getAs<RecordType>())
2367 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2369 case UTT_HasTrivialDestructor:
2370 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2371 // If __is_pod (type) is true or type is a reference type
2372 // then the trait is true, else if type is a cv class or union
2373 // type (or array thereof) with a trivial destructor
2374 // ([class.dtor]) then the trait is true, else it is
2376 if (T->isPODType() || T->isReferenceType())
2378 if (const RecordType *RT =
2379 C.getBaseElementType(T)->getAs<RecordType>())
2380 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2382 // TODO: Propagate nothrowness for implicitly declared special members.
2383 case UTT_HasNothrowAssign:
2384 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2385 // If type is const qualified or is a reference type then the
2386 // trait is false. Otherwise if __has_trivial_assign (type)
2387 // is true then the trait is true, else if type is a cv class
2388 // or union type with copy assignment operators that are known
2389 // not to throw an exception then the trait is true, else it is
2391 if (C.getBaseElementType(T).isConstQualified())
2393 if (T->isReferenceType())
2397 if (const RecordType *RT = T->getAs<RecordType>()) {
2398 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2399 if (RD->hasTrivialCopyAssignment())
2402 bool FoundAssign = false;
2403 bool AllNoThrow = true;
2404 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2405 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2406 Sema::LookupOrdinaryName);
2407 if (Self.LookupQualifiedName(Res, RD)) {
2408 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2409 Op != OpEnd; ++Op) {
2410 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2411 if (Operator->isCopyAssignmentOperator()) {
2413 const FunctionProtoType *CPT
2414 = Operator->getType()->getAs<FunctionProtoType>();
2415 if (!CPT->hasEmptyExceptionSpec()) {
2423 return FoundAssign && AllNoThrow;
2426 case UTT_HasNothrowCopy:
2427 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2428 // If __has_trivial_copy (type) is true then the trait is true, else
2429 // if type is a cv class or union type with copy constructors that are
2430 // known not to throw an exception then the trait is true, else it is
2432 if (T->isPODType() || T->isReferenceType())
2434 if (const RecordType *RT = T->getAs<RecordType>()) {
2435 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2436 if (RD->hasTrivialCopyConstructor())
2439 bool FoundConstructor = false;
2440 bool AllNoThrow = true;
2442 DeclContext::lookup_const_iterator Con, ConEnd;
2443 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2444 Con != ConEnd; ++Con) {
2445 // A template constructor is never a copy constructor.
2446 // FIXME: However, it may actually be selected at the actual overload
2447 // resolution point.
2448 if (isa<FunctionTemplateDecl>(*Con))
2450 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2451 if (Constructor->isCopyConstructor(FoundTQs)) {
2452 FoundConstructor = true;
2453 const FunctionProtoType *CPT
2454 = Constructor->getType()->getAs<FunctionProtoType>();
2455 // TODO: check whether evaluating default arguments can throw.
2456 // For now, we'll be conservative and assume that they can throw.
2457 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
2464 return FoundConstructor && AllNoThrow;
2467 case UTT_HasNothrowConstructor:
2468 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2469 // If __has_trivial_constructor (type) is true then the trait is
2470 // true, else if type is a cv class or union type (or array
2471 // thereof) with a default constructor that is known not to
2472 // throw an exception then the trait is true, else it is false.
2475 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2476 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2477 if (RD->hasTrivialConstructor())
2480 DeclContext::lookup_const_iterator Con, ConEnd;
2481 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2482 Con != ConEnd; ++Con) {
2483 // FIXME: In C++0x, a constructor template can be a default constructor.
2484 if (isa<FunctionTemplateDecl>(*Con))
2486 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2487 if (Constructor->isDefaultConstructor()) {
2488 const FunctionProtoType *CPT
2489 = Constructor->getType()->getAs<FunctionProtoType>();
2490 // TODO: check whether evaluating default arguments can throw.
2491 // For now, we'll be conservative and assume that they can throw.
2492 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2497 case UTT_HasVirtualDestructor:
2498 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2499 // If type is a class type with a virtual destructor ([class.dtor])
2500 // then the trait is true, else it is false.
2501 if (const RecordType *Record = T->getAs<RecordType>()) {
2502 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2503 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
2504 return Destructor->isVirtual();
2510 ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
2511 SourceLocation KWLoc,
2512 TypeSourceInfo *TSInfo,
2513 SourceLocation RParen) {
2514 QualType T = TSInfo->getType();
2516 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2517 // all traits except __is_class, __is_enum and __is_union require a the type
2518 // to be complete, an array of unknown bound, or void.
2519 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
2521 if (T->isIncompleteArrayType())
2522 E = Context.getAsArrayType(T)->getElementType();
2523 if (!T->isVoidType() &&
2524 RequireCompleteType(KWLoc, E,
2525 diag::err_incomplete_type_used_in_type_trait_expr))
2530 if (!T->isDependentType())
2531 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
2533 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
2534 RParen, Context.BoolTy));
2537 ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2538 SourceLocation KWLoc,
2541 SourceLocation RParen) {
2542 TypeSourceInfo *LhsTSInfo;
2543 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2545 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2547 TypeSourceInfo *RhsTSInfo;
2548 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2550 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2552 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2555 static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2556 QualType LhsT, QualType RhsT,
2557 SourceLocation KeyLoc) {
2558 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2559 "Cannot evaluate traits for dependent types.");
2562 case BTT_IsBaseOf: {
2563 // C++0x [meta.rel]p2
2564 // Base is a base class of Derived without regard to cv-qualifiers or
2565 // Base and Derived are not unions and name the same class type without
2566 // regard to cv-qualifiers.
2568 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2569 if (!lhsRecord) return false;
2571 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2572 if (!rhsRecord) return false;
2574 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2575 == (lhsRecord == rhsRecord));
2577 if (lhsRecord == rhsRecord)
2578 return !lhsRecord->getDecl()->isUnion();
2580 // C++0x [meta.rel]p2:
2581 // If Base and Derived are class types and are different types
2582 // (ignoring possible cv-qualifiers) then Derived shall be a
2584 if (Self.RequireCompleteType(KeyLoc, RhsT,
2585 diag::err_incomplete_type_used_in_type_trait_expr))
2588 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2589 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2592 case BTT_TypeCompatible:
2593 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2594 RhsT.getUnqualifiedType());
2596 case BTT_IsConvertibleTo: {
2597 // C++0x [meta.rel]p4:
2598 // Given the following function prototype:
2600 // template <class T>
2601 // typename add_rvalue_reference<T>::type create();
2603 // the predicate condition for a template specialization
2604 // is_convertible<From, To> shall be satisfied if and only if
2605 // the return expression in the following code would be
2606 // well-formed, including any implicit conversions to the return
2607 // type of the function:
2610 // return create<From>();
2613 // Access checking is performed as if in a context unrelated to To and
2614 // From. Only the validity of the immediate context of the expression
2615 // of the return-statement (including conversions to the return type)
2618 // We model the initialization as a copy-initialization of a temporary
2619 // of the appropriate type, which for this expression is identical to the
2620 // return statement (since NRVO doesn't apply).
2621 if (LhsT->isObjectType() || LhsT->isFunctionType())
2622 LhsT = Self.Context.getRValueReferenceType(LhsT);
2624 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
2625 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
2626 Expr::getValueKindForType(LhsT));
2627 Expr *FromPtr = &From;
2628 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2631 // Perform the initialization within a SFINAE trap at translation unit
2633 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2634 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
2635 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2636 if (Init.getKind() == InitializationSequence::FailedSequence)
2639 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2640 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2643 llvm_unreachable("Unknown type trait or not implemented");
2646 ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2647 SourceLocation KWLoc,
2648 TypeSourceInfo *LhsTSInfo,
2649 TypeSourceInfo *RhsTSInfo,
2650 SourceLocation RParen) {
2651 QualType LhsT = LhsTSInfo->getType();
2652 QualType RhsT = RhsTSInfo->getType();
2654 if (BTT == BTT_TypeCompatible) {
2655 if (getLangOptions().CPlusPlus) {
2656 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2657 << SourceRange(KWLoc, RParen);
2663 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2664 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2666 // Select trait result type.
2667 QualType ResultType;
2669 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2670 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2671 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
2674 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2675 RhsTSInfo, Value, RParen,
2679 QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2683 const char *OpSpelling = isIndirect ? "->*" : ".*";
2685 // The binary operator .* [p3: ->*] binds its second operand, which shall
2686 // be of type "pointer to member of T" (where T is a completely-defined
2687 // class type) [...]
2688 QualType RType = rex->getType();
2689 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
2691 Diag(Loc, diag::err_bad_memptr_rhs)
2692 << OpSpelling << RType << rex->getSourceRange();
2696 QualType Class(MemPtr->getClass(), 0);
2698 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2699 // member pointer points must be completely-defined. However, there is no
2700 // reason for this semantic distinction, and the rule is not enforced by
2701 // other compilers. Therefore, we do not check this property, as it is
2702 // likely to be considered a defect.
2705 // [...] to its first operand, which shall be of class T or of a class of
2706 // which T is an unambiguous and accessible base class. [p3: a pointer to
2708 QualType LType = lex->getType();
2710 if (const PointerType *Ptr = LType->getAs<PointerType>())
2711 LType = Ptr->getPointeeType();
2713 Diag(Loc, diag::err_bad_memptr_lhs)
2714 << OpSpelling << 1 << LType
2715 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
2720 if (!Context.hasSameUnqualifiedType(Class, LType)) {
2721 // If we want to check the hierarchy, we need a complete type.
2722 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2723 << OpSpelling << (int)isIndirect)) {
2726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2727 /*DetectVirtual=*/false);
2728 // FIXME: Would it be useful to print full ambiguity paths, or is that
2730 if (!IsDerivedFrom(LType, Class, Paths) ||
2731 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2732 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
2733 << (int)isIndirect << lex->getType();
2736 // Cast LHS to type of use.
2737 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
2739 isIndirect ? VK_RValue : CastCategory(lex);
2741 CXXCastPath BasePath;
2742 BuildBasePathArray(Paths, BasePath);
2743 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
2746 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
2747 // Diagnose use of pointer-to-member type which when used as
2748 // the functional cast in a pointer-to-member expression.
2749 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2754 // The result is an object or a function of the type specified by the
2756 // The cv qualifiers are the union of those in the pointer and the left side,
2757 // in accordance with 5.5p5 and 5.2.5.
2758 // FIXME: This returns a dereferenced member function pointer as a normal
2759 // function type. However, the only operation valid on such functions is
2760 // calling them. There's also a GCC extension to get a function pointer to the
2761 // thing, which is another complication, because this type - unlike the type
2762 // that is the result of this expression - takes the class as the first
2764 // We probably need a "MemberFunctionClosureType" or something like that.
2765 QualType Result = MemPtr->getPointeeType();
2766 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
2768 // C++0x [expr.mptr.oper]p6:
2769 // In a .* expression whose object expression is an rvalue, the program is
2770 // ill-formed if the second operand is a pointer to member function with
2771 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2772 // expression is an lvalue, the program is ill-formed if the second operand
2773 // is a pointer to member function with ref-qualifier &&.
2774 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2775 switch (Proto->getRefQualifier()) {
2781 if (!isIndirect && !lex->Classify(Context).isLValue())
2782 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2783 << RType << 1 << lex->getSourceRange();
2787 if (isIndirect || !lex->Classify(Context).isRValue())
2788 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2789 << RType << 0 << lex->getSourceRange();
2794 // C++ [expr.mptr.oper]p6:
2795 // The result of a .* expression whose second operand is a pointer
2796 // to a data member is of the same value category as its
2797 // first operand. The result of a .* expression whose second
2798 // operand is a pointer to a member function is a prvalue. The
2799 // result of an ->* expression is an lvalue if its second operand
2800 // is a pointer to data member and a prvalue otherwise.
2801 if (Result->isFunctionType())
2803 else if (isIndirect)
2806 VK = lex->getValueKind();
2811 /// \brief Try to convert a type to another according to C++0x 5.16p3.
2813 /// This is part of the parameter validation for the ? operator. If either
2814 /// value operand is a class type, the two operands are attempted to be
2815 /// converted to each other. This function does the conversion in one direction.
2816 /// It returns true if the program is ill-formed and has already been diagnosed
2818 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2819 SourceLocation QuestionLoc,
2820 bool &HaveConversion,
2822 HaveConversion = false;
2823 ToType = To->getType();
2825 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2828 // The process for determining whether an operand expression E1 of type T1
2829 // can be converted to match an operand expression E2 of type T2 is defined
2831 // -- If E2 is an lvalue:
2832 bool ToIsLvalue = To->isLValue();
2834 // E1 can be converted to match E2 if E1 can be implicitly converted to
2835 // type "lvalue reference to T2", subject to the constraint that in the
2836 // conversion the reference must bind directly to E1.
2837 QualType T = Self.Context.getLValueReferenceType(ToType);
2838 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2840 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2841 if (InitSeq.isDirectReferenceBinding()) {
2843 HaveConversion = true;
2847 if (InitSeq.isAmbiguous())
2848 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2851 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2852 // -- if E1 and E2 have class type, and the underlying class types are
2853 // the same or one is a base class of the other:
2854 QualType FTy = From->getType();
2855 QualType TTy = To->getType();
2856 const RecordType *FRec = FTy->getAs<RecordType>();
2857 const RecordType *TRec = TTy->getAs<RecordType>();
2858 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2859 Self.IsDerivedFrom(FTy, TTy);
2861 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
2862 // E1 can be converted to match E2 if the class of T2 is the
2863 // same type as, or a base class of, the class of T1, and
2865 if (FRec == TRec || FDerivedFromT) {
2866 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
2867 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2868 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2869 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2870 HaveConversion = true;
2874 if (InitSeq.isAmbiguous())
2875 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2882 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2883 // implicitly converted to the type that expression E2 would have
2884 // if E2 were converted to an rvalue (or the type it has, if E2 is
2887 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2888 // to the array-to-pointer or function-to-pointer conversions.
2889 if (!TTy->getAs<TagType>())
2890 TTy = TTy.getUnqualifiedType();
2892 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2893 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2894 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2896 if (InitSeq.isAmbiguous())
2897 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2902 /// \brief Try to find a common type for two according to C++0x 5.16p5.
2904 /// This is part of the parameter validation for the ? operator. If either
2905 /// value operand is a class type, overload resolution is used to find a
2906 /// conversion to a common type.
2907 static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2908 SourceLocation QuestionLoc) {
2909 Expr *Args[2] = { LHS, RHS };
2910 OverloadCandidateSet CandidateSet(QuestionLoc);
2911 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2914 OverloadCandidateSet::iterator Best;
2915 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
2917 // We found a match. Perform the conversions on the arguments and move on.
2918 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
2919 Best->Conversions[0], Sema::AA_Converting) ||
2920 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
2921 Best->Conversions[1], Sema::AA_Converting))
2925 case OR_No_Viable_Function:
2927 // Emit a better diagnostic if one of the expressions is a null pointer
2928 // constant and the other is a pointer type. In this case, the user most
2929 // likely forgot to take the address of the other expression.
2930 if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
2933 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2934 << LHS->getType() << RHS->getType()
2935 << LHS->getSourceRange() << RHS->getSourceRange();
2939 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
2940 << LHS->getType() << RHS->getType()
2941 << LHS->getSourceRange() << RHS->getSourceRange();
2942 // FIXME: Print the possible common types by printing the return types of
2943 // the viable candidates.
2947 assert(false && "Conditional operator has only built-in overloads");
2953 /// \brief Perform an "extended" implicit conversion as returned by
2954 /// TryClassUnification.
2955 static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2956 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2957 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2959 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2960 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
2961 if (Result.isInvalid())
2964 E = Result.takeAs<Expr>();
2968 /// \brief Check the operands of ?: under C++ semantics.
2970 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2971 /// extension. In this case, LHS == Cond. (But they're not aliases.)
2972 QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2973 ExprValueKind &VK, ExprObjectKind &OK,
2974 SourceLocation QuestionLoc) {
2975 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2976 // interface pointers.
2979 // The first expression is contextually converted to bool.
2980 if (!Cond->isTypeDependent()) {
2981 if (CheckCXXBooleanCondition(Cond))
2989 // Either of the arguments dependent?
2990 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2991 return Context.DependentTy;
2994 // If either the second or the third operand has type (cv) void, ...
2995 QualType LTy = LHS->getType();
2996 QualType RTy = RHS->getType();
2997 bool LVoid = LTy->isVoidType();
2998 bool RVoid = RTy->isVoidType();
2999 if (LVoid || RVoid) {
3000 // ... then the [l2r] conversions are performed on the second and third
3002 DefaultFunctionArrayLvalueConversion(LHS);
3003 DefaultFunctionArrayLvalueConversion(RHS);
3004 LTy = LHS->getType();
3005 RTy = RHS->getType();
3007 // ... and one of the following shall hold:
3008 // -- The second or the third operand (but not both) is a throw-
3009 // expression; the result is of the type of the other and is an rvalue.
3010 bool LThrow = isa<CXXThrowExpr>(LHS);
3011 bool RThrow = isa<CXXThrowExpr>(RHS);
3012 if (LThrow && !RThrow)
3014 if (RThrow && !LThrow)
3017 // -- Both the second and third operands have type void; the result is of
3018 // type void and is an rvalue.
3020 return Context.VoidTy;
3022 // Neither holds, error.
3023 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3024 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3025 << LHS->getSourceRange() << RHS->getSourceRange();
3032 // Otherwise, if the second and third operand have different types, and
3033 // either has (cv) class type, and attempt is made to convert each of those
3034 // operands to the other.
3035 if (!Context.hasSameType(LTy, RTy) &&
3036 (LTy->isRecordType() || RTy->isRecordType())) {
3037 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3038 // These return true if a single direction is already ambiguous.
3039 QualType L2RType, R2LType;
3040 bool HaveL2R, HaveR2L;
3041 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
3043 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
3046 // If both can be converted, [...] the program is ill-formed.
3047 if (HaveL2R && HaveR2L) {
3048 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3049 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3053 // If exactly one conversion is possible, that conversion is applied to
3054 // the chosen operand and the converted operands are used in place of the
3055 // original operands for the remainder of this section.
3057 if (ConvertForConditional(*this, LHS, L2RType))
3059 LTy = LHS->getType();
3060 } else if (HaveR2L) {
3061 if (ConvertForConditional(*this, RHS, R2LType))
3063 RTy = RHS->getType();
3068 // If the second and third operands are glvalues of the same value
3069 // category and have the same type, the result is of that type and
3070 // value category and it is a bit-field if the second or the third
3071 // operand is a bit-field, or if both are bit-fields.
3072 // We only extend this to bitfields, not to the crazy other kinds of
3074 bool Same = Context.hasSameType(LTy, RTy);
3077 LHS->getValueKind() == RHS->getValueKind() &&
3078 LHS->isOrdinaryOrBitFieldObject() &&
3079 RHS->isOrdinaryOrBitFieldObject()) {
3080 VK = LHS->getValueKind();
3081 if (LHS->getObjectKind() == OK_BitField ||
3082 RHS->getObjectKind() == OK_BitField)
3088 // Otherwise, the result is an rvalue. If the second and third operands
3089 // do not have the same type, and either has (cv) class type, ...
3090 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3091 // ... overload resolution is used to determine the conversions (if any)
3092 // to be applied to the operands. If the overload resolution fails, the
3093 // program is ill-formed.
3094 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3099 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3100 // conversions are performed on the second and third operands.
3101 DefaultFunctionArrayLvalueConversion(LHS);
3102 DefaultFunctionArrayLvalueConversion(RHS);
3103 LTy = LHS->getType();
3104 RTy = RHS->getType();
3106 // After those conversions, one of the following shall hold:
3107 // -- The second and third operands have the same type; the result
3108 // is of that type. If the operands have class type, the result
3109 // is a prvalue temporary of the result type, which is
3110 // copy-initialized from either the second operand or the third
3111 // operand depending on the value of the first operand.
3112 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3113 if (LTy->isRecordType()) {
3114 // The operands have class type. Make a temporary copy.
3115 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
3116 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3119 if (LHSCopy.isInvalid())
3122 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3125 if (RHSCopy.isInvalid())
3128 LHS = LHSCopy.takeAs<Expr>();
3129 RHS = RHSCopy.takeAs<Expr>();
3135 // Extension: conditional operator involving vector types.
3136 if (LTy->isVectorType() || RTy->isVectorType())
3137 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3139 // -- The second and third operands have arithmetic or enumeration type;
3140 // the usual arithmetic conversions are performed to bring them to a
3141 // common type, and the result is of that type.
3142 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3143 UsualArithmeticConversions(LHS, RHS);
3144 return LHS->getType();
3147 // -- The second and third operands have pointer type, or one has pointer
3148 // type and the other is a null pointer constant; pointer conversions
3149 // and qualification conversions are performed to bring them to their
3150 // composite pointer type. The result is of the composite pointer type.
3151 // -- The second and third operands have pointer to member type, or one has
3152 // pointer to member type and the other is a null pointer constant;
3153 // pointer to member conversions and qualification conversions are
3154 // performed to bring them to a common type, whose cv-qualification
3155 // shall match the cv-qualification of either the second or the third
3156 // operand. The result is of the common type.
3157 bool NonStandardCompositeType = false;
3158 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
3159 isSFINAEContext()? 0 : &NonStandardCompositeType);
3160 if (!Composite.isNull()) {
3161 if (NonStandardCompositeType)
3163 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3164 << LTy << RTy << Composite
3165 << LHS->getSourceRange() << RHS->getSourceRange();
3170 // Similarly, attempt to find composite type of two objective-c pointers.
3171 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3172 if (!Composite.isNull())
3175 // Check if we are using a null with a non-pointer type.
3176 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
3179 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3180 << LHS->getType() << RHS->getType()
3181 << LHS->getSourceRange() << RHS->getSourceRange();
3185 /// \brief Find a merged pointer type and convert the two expressions to it.
3187 /// This finds the composite pointer type (or member pointer type) for @p E1
3188 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3189 /// type and returns it.
3190 /// It does not emit diagnostics.
3192 /// \param Loc The location of the operator requiring these two expressions to
3193 /// be converted to the composite pointer type.
3195 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3196 /// a non-standard (but still sane) composite type to which both expressions
3197 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3198 /// will be set true.
3199 QualType Sema::FindCompositePointerType(SourceLocation Loc,
3200 Expr *&E1, Expr *&E2,
3201 bool *NonStandardCompositeType) {
3202 if (NonStandardCompositeType)
3203 *NonStandardCompositeType = false;
3205 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3206 QualType T1 = E1->getType(), T2 = E2->getType();
3208 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3209 !T2->isAnyPointerType() && !T2->isMemberPointerType())
3213 // Pointer conversions and qualification conversions are performed on
3214 // pointer operands to bring them to their composite pointer type. If
3215 // one operand is a null pointer constant, the composite pointer type is
3216 // the type of the other operand.
3217 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3218 if (T2->isMemberPointerType())
3219 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
3221 ImpCastExprToType(E1, T2, CK_NullToPointer);
3224 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3225 if (T1->isMemberPointerType())
3226 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
3228 ImpCastExprToType(E2, T1, CK_NullToPointer);
3232 // Now both have to be pointers or member pointers.
3233 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3234 (!T2->isPointerType() && !T2->isMemberPointerType()))
3237 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3238 // the other has type "pointer to cv2 T" and the composite pointer type is
3239 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3240 // Otherwise, the composite pointer type is a pointer type similar to the
3241 // type of one of the operands, with a cv-qualification signature that is
3242 // the union of the cv-qualification signatures of the operand types.
3243 // In practice, the first part here is redundant; it's subsumed by the second.
3244 // What we do here is, we build the two possible composite types, and try the
3245 // conversions in both directions. If only one works, or if the two composite
3246 // types are the same, we have succeeded.
3247 // FIXME: extended qualifiers?
3248 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3249 QualifierVector QualifierUnion;
3250 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3251 ContainingClassVector;
3252 ContainingClassVector MemberOfClass;
3253 QualType Composite1 = Context.getCanonicalType(T1),
3254 Composite2 = Context.getCanonicalType(T2);
3255 unsigned NeedConstBefore = 0;
3257 const PointerType *Ptr1, *Ptr2;
3258 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3259 (Ptr2 = Composite2->getAs<PointerType>())) {
3260 Composite1 = Ptr1->getPointeeType();
3261 Composite2 = Ptr2->getPointeeType();
3263 // If we're allowed to create a non-standard composite type, keep track
3264 // of where we need to fill in additional 'const' qualifiers.
3265 if (NonStandardCompositeType &&
3266 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3267 NeedConstBefore = QualifierUnion.size();
3269 QualifierUnion.push_back(
3270 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3271 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3275 const MemberPointerType *MemPtr1, *MemPtr2;
3276 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3277 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3278 Composite1 = MemPtr1->getPointeeType();
3279 Composite2 = MemPtr2->getPointeeType();
3281 // If we're allowed to create a non-standard composite type, keep track
3282 // of where we need to fill in additional 'const' qualifiers.
3283 if (NonStandardCompositeType &&
3284 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3285 NeedConstBefore = QualifierUnion.size();
3287 QualifierUnion.push_back(
3288 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3289 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3290 MemPtr2->getClass()));
3294 // FIXME: block pointer types?
3296 // Cannot unwrap any more types.
3300 if (NeedConstBefore && NonStandardCompositeType) {
3301 // Extension: Add 'const' to qualifiers that come before the first qualifier
3302 // mismatch, so that our (non-standard!) composite type meets the
3303 // requirements of C++ [conv.qual]p4 bullet 3.
3304 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3305 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3306 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3307 *NonStandardCompositeType = true;
3312 // Rewrap the composites as pointers or member pointers with the union CVRs.
3313 ContainingClassVector::reverse_iterator MOC
3314 = MemberOfClass.rbegin();
3315 for (QualifierVector::reverse_iterator
3316 I = QualifierUnion.rbegin(),
3317 E = QualifierUnion.rend();
3318 I != E; (void)++I, ++MOC) {
3319 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
3320 if (MOC->first && MOC->second) {
3321 // Rebuild member pointer type
3322 Composite1 = Context.getMemberPointerType(
3323 Context.getQualifiedType(Composite1, Quals),
3325 Composite2 = Context.getMemberPointerType(
3326 Context.getQualifiedType(Composite2, Quals),
3329 // Rebuild pointer type
3331 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3333 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
3337 // Try to convert to the first composite pointer type.
3338 InitializedEntity Entity1
3339 = InitializedEntity::InitializeTemporary(Composite1);
3340 InitializationKind Kind
3341 = InitializationKind::CreateCopy(Loc, SourceLocation());
3342 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3343 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
3345 if (E1ToC1 && E2ToC1) {
3346 // Conversion to Composite1 is viable.
3347 if (!Context.hasSameType(Composite1, Composite2)) {
3348 // Composite2 is a different type from Composite1. Check whether
3349 // Composite2 is also viable.
3350 InitializedEntity Entity2
3351 = InitializedEntity::InitializeTemporary(Composite2);
3352 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3353 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3354 if (E1ToC2 && E2ToC2) {
3355 // Both Composite1 and Composite2 are viable and are different;
3356 // this is an ambiguity.
3361 // Convert E1 to Composite1
3363 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
3364 if (E1Result.isInvalid())
3366 E1 = E1Result.takeAs<Expr>();
3368 // Convert E2 to Composite1
3370 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
3371 if (E2Result.isInvalid())
3373 E2 = E2Result.takeAs<Expr>();
3378 // Check whether Composite2 is viable.
3379 InitializedEntity Entity2
3380 = InitializedEntity::InitializeTemporary(Composite2);
3381 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3382 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3383 if (!E1ToC2 || !E2ToC2)
3386 // Convert E1 to Composite2
3388 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
3389 if (E1Result.isInvalid())
3391 E1 = E1Result.takeAs<Expr>();
3393 // Convert E2 to Composite2
3395 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
3396 if (E2Result.isInvalid())
3398 E2 = E2Result.takeAs<Expr>();
3403 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
3407 if (!Context.getLangOptions().CPlusPlus)
3410 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3412 const RecordType *RT = E->getType()->getAs<RecordType>();
3416 // If the result is a glvalue, we shouldn't bind it.
3417 if (E->Classify(Context).isGLValue())
3420 // That should be enough to guarantee that this type is complete.
3421 // If it has a trivial destructor, we can avoid the extra copy.
3422 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3423 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
3426 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
3427 ExprTemporaries.push_back(Temp);
3428 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
3429 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
3430 CheckDestructorAccess(E->getExprLoc(), Destructor,
3431 PDiag(diag::err_access_dtor_temp)
3434 // FIXME: Add the temporary to the temporaries vector.
3435 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3438 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
3439 assert(SubExpr && "sub expression can't be null!");
3441 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3442 assert(ExprTemporaries.size() >= FirstTemporary);
3443 if (ExprTemporaries.size() == FirstTemporary)
3446 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3447 &ExprTemporaries[FirstTemporary],
3448 ExprTemporaries.size() - FirstTemporary);
3449 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3450 ExprTemporaries.end());
3456 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
3457 if (SubExpr.isInvalid())
3460 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
3463 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
3464 assert(SubStmt && "sub statement can't be null!");
3466 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3467 assert(ExprTemporaries.size() >= FirstTemporary);
3468 if (ExprTemporaries.size() == FirstTemporary)
3471 // FIXME: In order to attach the temporaries, wrap the statement into
3472 // a StmtExpr; currently this is only used for asm statements.
3473 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3474 // a new AsmStmtWithTemporaries.
3475 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3478 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3480 return MaybeCreateExprWithCleanups(E);
3484 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
3485 tok::TokenKind OpKind, ParsedType &ObjectType,
3486 bool &MayBePseudoDestructor) {
3487 // Since this might be a postfix expression, get rid of ParenListExprs.
3488 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3489 if (Result.isInvalid()) return ExprError();
3490 Base = Result.get();
3492 QualType BaseType = Base->getType();
3493 MayBePseudoDestructor = false;
3494 if (BaseType->isDependentType()) {
3495 // If we have a pointer to a dependent type and are using the -> operator,
3496 // the object type is the type that the pointer points to. We might still
3497 // have enough information about that type to do something useful.
3498 if (OpKind == tok::arrow)
3499 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3500 BaseType = Ptr->getPointeeType();
3502 ObjectType = ParsedType::make(BaseType);
3503 MayBePseudoDestructor = true;
3507 // C++ [over.match.oper]p8:
3508 // [...] When operator->returns, the operator-> is applied to the value
3509 // returned, with the original second operand.
3510 if (OpKind == tok::arrow) {
3511 // The set of types we've considered so far.
3512 llvm::SmallPtrSet<CanQualType,8> CTypes;
3513 llvm::SmallVector<SourceLocation, 8> Locations;
3514 CTypes.insert(Context.getCanonicalType(BaseType));
3516 while (BaseType->isRecordType()) {
3517 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3518 if (Result.isInvalid())
3520 Base = Result.get();
3521 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
3522 Locations.push_back(OpCall->getDirectCallee()->getLocation());
3523 BaseType = Base->getType();
3524 CanQualType CBaseType = Context.getCanonicalType(BaseType);
3525 if (!CTypes.insert(CBaseType)) {
3526 Diag(OpLoc, diag::err_operator_arrow_circular);
3527 for (unsigned i = 0; i < Locations.size(); i++)
3528 Diag(Locations[i], diag::note_declared_at);
3533 if (BaseType->isPointerType())
3534 BaseType = BaseType->getPointeeType();
3537 // We could end up with various non-record types here, such as extended
3538 // vector types or Objective-C interfaces. Just return early and let
3539 // ActOnMemberReferenceExpr do the work.
3540 if (!BaseType->isRecordType()) {
3541 // C++ [basic.lookup.classref]p2:
3542 // [...] If the type of the object expression is of pointer to scalar
3543 // type, the unqualified-id is looked up in the context of the complete
3544 // postfix-expression.
3546 // This also indicates that we should be parsing a
3547 // pseudo-destructor-name.
3548 ObjectType = ParsedType();
3549 MayBePseudoDestructor = true;
3553 // The object type must be complete (or dependent).
3554 if (!BaseType->isDependentType() &&
3555 RequireCompleteType(OpLoc, BaseType,
3556 PDiag(diag::err_incomplete_member_access)))
3559 // C++ [basic.lookup.classref]p2:
3560 // If the id-expression in a class member access (5.2.5) is an
3561 // unqualified-id, and the type of the object expression is of a class
3562 // type C (or of pointer to a class type C), the unqualified-id is looked
3563 // up in the scope of class C. [...]
3564 ObjectType = ParsedType::make(BaseType);
3568 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
3570 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
3571 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3572 << isa<CXXPseudoDestructorExpr>(MemExpr)
3573 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
3575 return ActOnCallExpr(/*Scope*/ 0,
3577 /*LPLoc*/ ExpectedLParenLoc,
3579 /*RPLoc*/ ExpectedLParenLoc);
3582 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
3583 SourceLocation OpLoc,
3584 tok::TokenKind OpKind,
3585 const CXXScopeSpec &SS,
3586 TypeSourceInfo *ScopeTypeInfo,
3587 SourceLocation CCLoc,
3588 SourceLocation TildeLoc,
3589 PseudoDestructorTypeStorage Destructed,
3590 bool HasTrailingLParen) {
3591 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
3593 // C++ [expr.pseudo]p2:
3594 // The left-hand side of the dot operator shall be of scalar type. The
3595 // left-hand side of the arrow operator shall be of pointer to scalar type.
3596 // This scalar type is the object type.
3597 QualType ObjectType = Base->getType();
3598 if (OpKind == tok::arrow) {
3599 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3600 ObjectType = Ptr->getPointeeType();
3601 } else if (!Base->isTypeDependent()) {
3602 // The user wrote "p->" when she probably meant "p."; fix it.
3603 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3604 << ObjectType << true
3605 << FixItHint::CreateReplacement(OpLoc, ".");
3606 if (isSFINAEContext())
3609 OpKind = tok::period;
3613 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3614 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
3615 << ObjectType << Base->getSourceRange();
3619 // C++ [expr.pseudo]p2:
3620 // [...] The cv-unqualified versions of the object type and of the type
3621 // designated by the pseudo-destructor-name shall be the same type.
3622 if (DestructedTypeInfo) {
3623 QualType DestructedType = DestructedTypeInfo->getType();
3624 SourceLocation DestructedTypeStart
3625 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
3626 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3627 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3628 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
3629 << ObjectType << DestructedType << Base->getSourceRange()
3630 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
3632 // Recover by setting the destructed type to the object type.
3633 DestructedType = ObjectType;
3634 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3635 DestructedTypeStart);
3636 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3640 // C++ [expr.pseudo]p2:
3641 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3644 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3646 // shall designate the same scalar type.
3647 if (ScopeTypeInfo) {
3648 QualType ScopeType = ScopeTypeInfo->getType();
3649 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
3650 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
3652 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
3653 diag::err_pseudo_dtor_type_mismatch)
3654 << ObjectType << ScopeType << Base->getSourceRange()
3655 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
3657 ScopeType = QualType();
3663 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3664 OpKind == tok::arrow, OpLoc,
3665 SS.getScopeRep(), SS.getRange(),
3671 if (HasTrailingLParen)
3672 return Owned(Result);
3674 return DiagnoseDtorReference(Destructed.getLocation(), Result);
3677 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3678 SourceLocation OpLoc,
3679 tok::TokenKind OpKind,
3681 UnqualifiedId &FirstTypeName,
3682 SourceLocation CCLoc,
3683 SourceLocation TildeLoc,
3684 UnqualifiedId &SecondTypeName,
3685 bool HasTrailingLParen) {
3686 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3687 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3688 "Invalid first type name in pseudo-destructor");
3689 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3690 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3691 "Invalid second type name in pseudo-destructor");
3693 // C++ [expr.pseudo]p2:
3694 // The left-hand side of the dot operator shall be of scalar type. The
3695 // left-hand side of the arrow operator shall be of pointer to scalar type.
3696 // This scalar type is the object type.
3697 QualType ObjectType = Base->getType();
3698 if (OpKind == tok::arrow) {
3699 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3700 ObjectType = Ptr->getPointeeType();
3701 } else if (!ObjectType->isDependentType()) {
3702 // The user wrote "p->" when she probably meant "p."; fix it.
3703 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3704 << ObjectType << true
3705 << FixItHint::CreateReplacement(OpLoc, ".");
3706 if (isSFINAEContext())
3709 OpKind = tok::period;
3713 // Compute the object type that we should use for name lookup purposes. Only
3714 // record types and dependent types matter.
3715 ParsedType ObjectTypePtrForLookup;
3717 if (const Type *T = ObjectType->getAs<RecordType>())
3718 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3719 else if (ObjectType->isDependentType())
3720 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
3723 // Convert the name of the type being destructed (following the ~) into a
3724 // type (with source-location information).
3725 QualType DestructedType;
3726 TypeSourceInfo *DestructedTypeInfo = 0;
3727 PseudoDestructorTypeStorage Destructed;
3728 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3729 ParsedType T = getTypeName(*SecondTypeName.Identifier,
3730 SecondTypeName.StartLocation,
3731 S, &SS, true, false, ObjectTypePtrForLookup);
3733 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3734 (!SS.isSet() && ObjectType->isDependentType()))) {
3735 // The name of the type being destroyed is a dependent name, and we
3736 // couldn't find anything useful in scope. Just store the identifier and
3737 // it's location, and we'll perform (qualified) name lookup again at
3738 // template instantiation time.
3739 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3740 SecondTypeName.StartLocation);
3742 Diag(SecondTypeName.StartLocation,
3743 diag::err_pseudo_dtor_destructor_non_type)
3744 << SecondTypeName.Identifier << ObjectType;
3745 if (isSFINAEContext())
3748 // Recover by assuming we had the right type all along.
3749 DestructedType = ObjectType;
3751 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
3753 // Resolve the template-id to a type.
3754 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
3755 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3756 TemplateId->getTemplateArgs(),
3757 TemplateId->NumArgs);
3758 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
3759 TemplateId->TemplateNameLoc,
3760 TemplateId->LAngleLoc,
3762 TemplateId->RAngleLoc);
3763 if (T.isInvalid() || !T.get()) {
3764 // Recover by assuming we had the right type all along.
3765 DestructedType = ObjectType;
3767 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
3770 // If we've performed some kind of recovery, (re-)build the type source
3772 if (!DestructedType.isNull()) {
3773 if (!DestructedTypeInfo)
3774 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
3775 SecondTypeName.StartLocation);
3776 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3779 // Convert the name of the scope type (the type prior to '::') into a type.
3780 TypeSourceInfo *ScopeTypeInfo = 0;
3782 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3783 FirstTypeName.Identifier) {
3784 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3785 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3786 FirstTypeName.StartLocation,
3787 S, &SS, false, false, ObjectTypePtrForLookup);
3789 Diag(FirstTypeName.StartLocation,
3790 diag::err_pseudo_dtor_destructor_non_type)
3791 << FirstTypeName.Identifier << ObjectType;
3793 if (isSFINAEContext())
3796 // Just drop this type. It's unnecessary anyway.
3797 ScopeType = QualType();
3799 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
3801 // Resolve the template-id to a type.
3802 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
3803 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3804 TemplateId->getTemplateArgs(),
3805 TemplateId->NumArgs);
3806 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
3807 TemplateId->TemplateNameLoc,
3808 TemplateId->LAngleLoc,
3810 TemplateId->RAngleLoc);
3811 if (T.isInvalid() || !T.get()) {
3812 // Recover by dropping this type.
3813 ScopeType = QualType();
3815 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
3819 if (!ScopeType.isNull() && !ScopeTypeInfo)
3820 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3821 FirstTypeName.StartLocation);
3824 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
3825 ScopeTypeInfo, CCLoc, TildeLoc,
3826 Destructed, HasTrailingLParen);
3829 ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3830 CXXMethodDecl *Method) {
3831 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3836 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3837 SourceLocation(), Method->getType(),
3838 VK_RValue, OK_Ordinary);
3839 QualType ResultType = Method->getResultType();
3840 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3841 ResultType = ResultType.getNonLValueExprType(Context);
3843 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3844 CXXMemberCallExpr *CE =
3845 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
3850 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3851 SourceLocation RParen) {
3852 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3853 Operand->CanThrow(Context),
3857 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3858 Expr *Operand, SourceLocation RParen) {
3859 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
3862 /// Perform the conversions required for an expression used in a
3863 /// context that ignores the result.
3864 void Sema::IgnoredValueConversions(Expr *&E) {
3866 // [Except in specific positions,] an lvalue that does not have
3867 // array type is converted to the value stored in the
3868 // designated object (and is no longer an lvalue).
3869 if (E->isRValue()) return;
3871 // We always want to do this on ObjC property references.
3872 if (E->getObjectKind() == OK_ObjCProperty) {
3873 ConvertPropertyForRValue(E);
3874 if (E->isRValue()) return;
3877 // Otherwise, this rule does not apply in C++, at least not for the moment.
3878 if (getLangOptions().CPlusPlus) return;
3880 // GCC seems to also exclude expressions of incomplete enum type.
3881 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3882 if (!T->getDecl()->isComplete()) {
3883 // FIXME: stupid workaround for a codegen bug!
3884 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3889 DefaultFunctionArrayLvalueConversion(E);
3890 if (!E->getType()->isVoidType())
3891 RequireCompleteType(E->getExprLoc(), E->getType(),
3892 diag::err_incomplete_type);
3895 ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
3899 if (DiagnoseUnexpandedParameterPack(FullExpr))
3902 IgnoredValueConversions(FullExpr);
3903 CheckImplicitConversions(FullExpr);
3904 return MaybeCreateExprWithCleanups(FullExpr);
3907 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3908 if (!FullStmt) return StmtError();
3910 return MaybeCreateStmtWithCleanups(FullStmt);