10b57cec5SDimitry Andric //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric /// 90b57cec5SDimitry Andric /// \file 100b57cec5SDimitry Andric /// Implements semantic analysis for C++ expressions. 110b57cec5SDimitry Andric /// 120b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 130b57cec5SDimitry Andric 140b57cec5SDimitry Andric #include "TreeTransform.h" 150b57cec5SDimitry Andric #include "TypeLocBuilder.h" 160b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 170b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h" 180b57cec5SDimitry Andric #include "clang/AST/CXXInheritance.h" 190b57cec5SDimitry Andric #include "clang/AST/CharUnits.h" 200b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 210b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h" 220b57cec5SDimitry Andric #include "clang/AST/ExprObjC.h" 230b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 240b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h" 250b57cec5SDimitry Andric #include "clang/Basic/AlignedAllocation.h" 2681ad6265SDimitry Andric #include "clang/Basic/DiagnosticSema.h" 270b57cec5SDimitry Andric #include "clang/Basic/PartialDiagnostic.h" 280b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h" 2981ad6265SDimitry Andric #include "clang/Basic/TypeTraits.h" 300b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h" 310b57cec5SDimitry Andric #include "clang/Sema/DeclSpec.h" 320b57cec5SDimitry Andric #include "clang/Sema/Initialization.h" 330b57cec5SDimitry Andric #include "clang/Sema/Lookup.h" 340b57cec5SDimitry Andric #include "clang/Sema/ParsedTemplate.h" 350b57cec5SDimitry Andric #include "clang/Sema/Scope.h" 360b57cec5SDimitry Andric #include "clang/Sema/ScopeInfo.h" 3781ad6265SDimitry Andric #include "clang/Sema/SemaInternal.h" 380b57cec5SDimitry Andric #include "clang/Sema/SemaLambda.h" 3981ad6265SDimitry Andric #include "clang/Sema/Template.h" 400b57cec5SDimitry Andric #include "clang/Sema/TemplateDeduction.h" 410b57cec5SDimitry Andric #include "llvm/ADT/APInt.h" 420b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 430b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 4481ad6265SDimitry Andric #include "llvm/Support/TypeSize.h" 450b57cec5SDimitry Andric using namespace clang; 460b57cec5SDimitry Andric using namespace sema; 470b57cec5SDimitry Andric 480b57cec5SDimitry Andric /// Handle the result of the special case name lookup for inheriting 490b57cec5SDimitry Andric /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as 500b57cec5SDimitry Andric /// constructor names in member using declarations, even if 'X' is not the 510b57cec5SDimitry Andric /// name of the corresponding type. 520b57cec5SDimitry Andric ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, 530b57cec5SDimitry Andric SourceLocation NameLoc, 540b57cec5SDimitry Andric IdentifierInfo &Name) { 550b57cec5SDimitry Andric NestedNameSpecifier *NNS = SS.getScopeRep(); 560b57cec5SDimitry Andric 570b57cec5SDimitry Andric // Convert the nested-name-specifier into a type. 580b57cec5SDimitry Andric QualType Type; 590b57cec5SDimitry Andric switch (NNS->getKind()) { 600b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpec: 610b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpecWithTemplate: 620b57cec5SDimitry Andric Type = QualType(NNS->getAsType(), 0); 630b57cec5SDimitry Andric break; 640b57cec5SDimitry Andric 650b57cec5SDimitry Andric case NestedNameSpecifier::Identifier: 660b57cec5SDimitry Andric // Strip off the last layer of the nested-name-specifier and build a 670b57cec5SDimitry Andric // typename type for it. 680b57cec5SDimitry Andric assert(NNS->getAsIdentifier() == &Name && "not a constructor name"); 690b57cec5SDimitry Andric Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(), 700b57cec5SDimitry Andric NNS->getAsIdentifier()); 710b57cec5SDimitry Andric break; 720b57cec5SDimitry Andric 730b57cec5SDimitry Andric case NestedNameSpecifier::Global: 740b57cec5SDimitry Andric case NestedNameSpecifier::Super: 750b57cec5SDimitry Andric case NestedNameSpecifier::Namespace: 760b57cec5SDimitry Andric case NestedNameSpecifier::NamespaceAlias: 770b57cec5SDimitry Andric llvm_unreachable("Nested name specifier is not a type for inheriting ctor"); 780b57cec5SDimitry Andric } 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric // This reference to the type is located entirely at the location of the 810b57cec5SDimitry Andric // final identifier in the qualified-id. 820b57cec5SDimitry Andric return CreateParsedType(Type, 830b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(Type, NameLoc)); 840b57cec5SDimitry Andric } 850b57cec5SDimitry Andric 860b57cec5SDimitry Andric ParsedType Sema::getConstructorName(IdentifierInfo &II, 870b57cec5SDimitry Andric SourceLocation NameLoc, 880b57cec5SDimitry Andric Scope *S, CXXScopeSpec &SS, 890b57cec5SDimitry Andric bool EnteringContext) { 900b57cec5SDimitry Andric CXXRecordDecl *CurClass = getCurrentClass(S, &SS); 910b57cec5SDimitry Andric assert(CurClass && &II == CurClass->getIdentifier() && 920b57cec5SDimitry Andric "not a constructor name"); 930b57cec5SDimitry Andric 940b57cec5SDimitry Andric // When naming a constructor as a member of a dependent context (eg, in a 950b57cec5SDimitry Andric // friend declaration or an inherited constructor declaration), form an 960b57cec5SDimitry Andric // unresolved "typename" type. 970b57cec5SDimitry Andric if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { 980b57cec5SDimitry Andric QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II); 990b57cec5SDimitry Andric return ParsedType::make(T); 1000b57cec5SDimitry Andric } 1010b57cec5SDimitry Andric 1020b57cec5SDimitry Andric if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) 1030b57cec5SDimitry Andric return ParsedType(); 1040b57cec5SDimitry Andric 1050b57cec5SDimitry Andric // Find the injected-class-name declaration. Note that we make no attempt to 1060b57cec5SDimitry Andric // diagnose cases where the injected-class-name is shadowed: the only 1070b57cec5SDimitry Andric // declaration that can validly shadow the injected-class-name is a 1080b57cec5SDimitry Andric // non-static data member, and if the class contains both a non-static data 1090b57cec5SDimitry Andric // member and a constructor then it is ill-formed (we check that in 1100b57cec5SDimitry Andric // CheckCompletedCXXClass). 1110b57cec5SDimitry Andric CXXRecordDecl *InjectedClassName = nullptr; 1120b57cec5SDimitry Andric for (NamedDecl *ND : CurClass->lookup(&II)) { 1130b57cec5SDimitry Andric auto *RD = dyn_cast<CXXRecordDecl>(ND); 1140b57cec5SDimitry Andric if (RD && RD->isInjectedClassName()) { 1150b57cec5SDimitry Andric InjectedClassName = RD; 1160b57cec5SDimitry Andric break; 1170b57cec5SDimitry Andric } 1180b57cec5SDimitry Andric } 1190b57cec5SDimitry Andric if (!InjectedClassName) { 1200b57cec5SDimitry Andric if (!CurClass->isInvalidDecl()) { 1210b57cec5SDimitry Andric // FIXME: RequireCompleteDeclContext doesn't check dependent contexts 1220b57cec5SDimitry Andric // properly. Work around it here for now. 1230b57cec5SDimitry Andric Diag(SS.getLastQualifierNameLoc(), 1240b57cec5SDimitry Andric diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); 1250b57cec5SDimitry Andric } 1260b57cec5SDimitry Andric return ParsedType(); 1270b57cec5SDimitry Andric } 1280b57cec5SDimitry Andric 1290b57cec5SDimitry Andric QualType T = Context.getTypeDeclType(InjectedClassName); 1300b57cec5SDimitry Andric DiagnoseUseOfDecl(InjectedClassName, NameLoc); 1310b57cec5SDimitry Andric MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric return ParsedType::make(T); 1340b57cec5SDimitry Andric } 1350b57cec5SDimitry Andric 1360b57cec5SDimitry Andric ParsedType Sema::getDestructorName(SourceLocation TildeLoc, 1370b57cec5SDimitry Andric IdentifierInfo &II, 1380b57cec5SDimitry Andric SourceLocation NameLoc, 1390b57cec5SDimitry Andric Scope *S, CXXScopeSpec &SS, 1400b57cec5SDimitry Andric ParsedType ObjectTypePtr, 1410b57cec5SDimitry Andric bool EnteringContext) { 1420b57cec5SDimitry Andric // Determine where to perform name lookup. 1430b57cec5SDimitry Andric 1440b57cec5SDimitry Andric // FIXME: This area of the standard is very messy, and the current 1450b57cec5SDimitry Andric // wording is rather unclear about which scopes we search for the 1460b57cec5SDimitry Andric // destructor name; see core issues 399 and 555. Issue 399 in 1470b57cec5SDimitry Andric // particular shows where the current description of destructor name 1480b57cec5SDimitry Andric // lookup is completely out of line with existing practice, e.g., 1490b57cec5SDimitry Andric // this appears to be ill-formed: 1500b57cec5SDimitry Andric // 1510b57cec5SDimitry Andric // namespace N { 1520b57cec5SDimitry Andric // template <typename T> struct S { 1530b57cec5SDimitry Andric // ~S(); 1540b57cec5SDimitry Andric // }; 1550b57cec5SDimitry Andric // } 1560b57cec5SDimitry Andric // 1570b57cec5SDimitry Andric // void f(N::S<int>* s) { 1580b57cec5SDimitry Andric // s->N::S<int>::~S(); 1590b57cec5SDimitry Andric // } 1600b57cec5SDimitry Andric // 1610b57cec5SDimitry Andric // See also PR6358 and PR6359. 1625ffd83dbSDimitry Andric // 1635ffd83dbSDimitry Andric // For now, we accept all the cases in which the name given could plausibly 1645ffd83dbSDimitry Andric // be interpreted as a correct destructor name, issuing off-by-default 1655ffd83dbSDimitry Andric // extension diagnostics on the cases that don't strictly conform to the 1665ffd83dbSDimitry Andric // C++20 rules. This basically means we always consider looking in the 1675ffd83dbSDimitry Andric // nested-name-specifier prefix, the complete nested-name-specifier, and 1685ffd83dbSDimitry Andric // the scope, and accept if we find the expected type in any of the three 1695ffd83dbSDimitry Andric // places. 1700b57cec5SDimitry Andric 1710b57cec5SDimitry Andric if (SS.isInvalid()) 1720b57cec5SDimitry Andric return nullptr; 1730b57cec5SDimitry Andric 1745ffd83dbSDimitry Andric // Whether we've failed with a diagnostic already. 1755ffd83dbSDimitry Andric bool Failed = false; 1765ffd83dbSDimitry Andric 1775ffd83dbSDimitry Andric llvm::SmallVector<NamedDecl*, 8> FoundDecls; 178e8d8bef9SDimitry Andric llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; 1795ffd83dbSDimitry Andric 1800b57cec5SDimitry Andric // If we have an object type, it's because we are in a 1810b57cec5SDimitry Andric // pseudo-destructor-expression or a member access expression, and 1820b57cec5SDimitry Andric // we know what type we're looking for. 1835ffd83dbSDimitry Andric QualType SearchType = 1845ffd83dbSDimitry Andric ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType(); 1850b57cec5SDimitry Andric 1865ffd83dbSDimitry Andric auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { 1875ffd83dbSDimitry Andric auto IsAcceptableResult = [&](NamedDecl *D) -> bool { 1885ffd83dbSDimitry Andric auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl()); 1895ffd83dbSDimitry Andric if (!Type) 1905ffd83dbSDimitry Andric return false; 1910b57cec5SDimitry Andric 1925ffd83dbSDimitry Andric if (SearchType.isNull() || SearchType->isDependentType()) 1935ffd83dbSDimitry Andric return true; 1945ffd83dbSDimitry Andric 1955ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(Type); 1965ffd83dbSDimitry Andric return Context.hasSameUnqualifiedType(T, SearchType); 1975ffd83dbSDimitry Andric }; 1985ffd83dbSDimitry Andric 1995ffd83dbSDimitry Andric unsigned NumAcceptableResults = 0; 2005ffd83dbSDimitry Andric for (NamedDecl *D : Found) { 2015ffd83dbSDimitry Andric if (IsAcceptableResult(D)) 2025ffd83dbSDimitry Andric ++NumAcceptableResults; 2035ffd83dbSDimitry Andric 2045ffd83dbSDimitry Andric // Don't list a class twice in the lookup failure diagnostic if it's 2055ffd83dbSDimitry Andric // found by both its injected-class-name and by the name in the enclosing 2065ffd83dbSDimitry Andric // scope. 2075ffd83dbSDimitry Andric if (auto *RD = dyn_cast<CXXRecordDecl>(D)) 2085ffd83dbSDimitry Andric if (RD->isInjectedClassName()) 2095ffd83dbSDimitry Andric D = cast<NamedDecl>(RD->getParent()); 2105ffd83dbSDimitry Andric 2115ffd83dbSDimitry Andric if (FoundDeclSet.insert(D).second) 2125ffd83dbSDimitry Andric FoundDecls.push_back(D); 2130b57cec5SDimitry Andric } 2140b57cec5SDimitry Andric 2155ffd83dbSDimitry Andric // As an extension, attempt to "fix" an ambiguity by erasing all non-type 2165ffd83dbSDimitry Andric // results, and all non-matching results if we have a search type. It's not 2175ffd83dbSDimitry Andric // clear what the right behavior is if destructor lookup hits an ambiguity, 2185ffd83dbSDimitry Andric // but other compilers do generally accept at least some kinds of 2195ffd83dbSDimitry Andric // ambiguity. 2205ffd83dbSDimitry Andric if (Found.isAmbiguous() && NumAcceptableResults == 1) { 2215ffd83dbSDimitry Andric Diag(NameLoc, diag::ext_dtor_name_ambiguous); 2225ffd83dbSDimitry Andric LookupResult::Filter F = Found.makeFilter(); 2235ffd83dbSDimitry Andric while (F.hasNext()) { 2245ffd83dbSDimitry Andric NamedDecl *D = F.next(); 2255ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) 2265ffd83dbSDimitry Andric Diag(D->getLocation(), diag::note_destructor_type_here) 2275ffd83dbSDimitry Andric << Context.getTypeDeclType(TD); 2285ffd83dbSDimitry Andric else 2295ffd83dbSDimitry Andric Diag(D->getLocation(), diag::note_destructor_nontype_here); 2305ffd83dbSDimitry Andric 2315ffd83dbSDimitry Andric if (!IsAcceptableResult(D)) 2325ffd83dbSDimitry Andric F.erase(); 2330b57cec5SDimitry Andric } 2345ffd83dbSDimitry Andric F.done(); 2355ffd83dbSDimitry Andric } 2365ffd83dbSDimitry Andric 2375ffd83dbSDimitry Andric if (Found.isAmbiguous()) 2385ffd83dbSDimitry Andric Failed = true; 2395ffd83dbSDimitry Andric 2405ffd83dbSDimitry Andric if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 2415ffd83dbSDimitry Andric if (IsAcceptableResult(Type)) { 2425ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(Type); 2435ffd83dbSDimitry Andric MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 2445ffd83dbSDimitry Andric return CreateParsedType(T, 2455ffd83dbSDimitry Andric Context.getTrivialTypeSourceInfo(T, NameLoc)); 2465ffd83dbSDimitry Andric } 2475ffd83dbSDimitry Andric } 2485ffd83dbSDimitry Andric 2495ffd83dbSDimitry Andric return nullptr; 2505ffd83dbSDimitry Andric }; 2515ffd83dbSDimitry Andric 2525ffd83dbSDimitry Andric bool IsDependent = false; 2535ffd83dbSDimitry Andric 2545ffd83dbSDimitry Andric auto LookupInObjectType = [&]() -> ParsedType { 2555ffd83dbSDimitry Andric if (Failed || SearchType.isNull()) 2565ffd83dbSDimitry Andric return nullptr; 2575ffd83dbSDimitry Andric 2585ffd83dbSDimitry Andric IsDependent |= SearchType->isDependentType(); 2595ffd83dbSDimitry Andric 2605ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2615ffd83dbSDimitry Andric DeclContext *LookupCtx = computeDeclContext(SearchType); 2625ffd83dbSDimitry Andric if (!LookupCtx) 2635ffd83dbSDimitry Andric return nullptr; 2645ffd83dbSDimitry Andric LookupQualifiedName(Found, LookupCtx); 2655ffd83dbSDimitry Andric return CheckLookupResult(Found); 2665ffd83dbSDimitry Andric }; 2675ffd83dbSDimitry Andric 2685ffd83dbSDimitry Andric auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { 2695ffd83dbSDimitry Andric if (Failed) 2705ffd83dbSDimitry Andric return nullptr; 2715ffd83dbSDimitry Andric 2725ffd83dbSDimitry Andric IsDependent |= isDependentScopeSpecifier(LookupSS); 2735ffd83dbSDimitry Andric DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext); 2745ffd83dbSDimitry Andric if (!LookupCtx) 2755ffd83dbSDimitry Andric return nullptr; 2765ffd83dbSDimitry Andric 2775ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2785ffd83dbSDimitry Andric if (RequireCompleteDeclContext(LookupSS, LookupCtx)) { 2795ffd83dbSDimitry Andric Failed = true; 2805ffd83dbSDimitry Andric return nullptr; 2815ffd83dbSDimitry Andric } 2825ffd83dbSDimitry Andric LookupQualifiedName(Found, LookupCtx); 2835ffd83dbSDimitry Andric return CheckLookupResult(Found); 2845ffd83dbSDimitry Andric }; 2855ffd83dbSDimitry Andric 2865ffd83dbSDimitry Andric auto LookupInScope = [&]() -> ParsedType { 2875ffd83dbSDimitry Andric if (Failed || !S) 2885ffd83dbSDimitry Andric return nullptr; 2895ffd83dbSDimitry Andric 2905ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2915ffd83dbSDimitry Andric LookupName(Found, S); 2925ffd83dbSDimitry Andric return CheckLookupResult(Found); 2935ffd83dbSDimitry Andric }; 2945ffd83dbSDimitry Andric 2955ffd83dbSDimitry Andric // C++2a [basic.lookup.qual]p6: 2965ffd83dbSDimitry Andric // In a qualified-id of the form 2975ffd83dbSDimitry Andric // 2985ffd83dbSDimitry Andric // nested-name-specifier[opt] type-name :: ~ type-name 2995ffd83dbSDimitry Andric // 3005ffd83dbSDimitry Andric // the second type-name is looked up in the same scope as the first. 3015ffd83dbSDimitry Andric // 3025ffd83dbSDimitry Andric // We interpret this as meaning that if you do a dual-scope lookup for the 3035ffd83dbSDimitry Andric // first name, you also do a dual-scope lookup for the second name, per 3045ffd83dbSDimitry Andric // C++ [basic.lookup.classref]p4: 3055ffd83dbSDimitry Andric // 3065ffd83dbSDimitry Andric // If the id-expression in a class member access is a qualified-id of the 3075ffd83dbSDimitry Andric // form 3085ffd83dbSDimitry Andric // 3095ffd83dbSDimitry Andric // class-name-or-namespace-name :: ... 3105ffd83dbSDimitry Andric // 3115ffd83dbSDimitry Andric // the class-name-or-namespace-name following the . or -> is first looked 3125ffd83dbSDimitry Andric // up in the class of the object expression and the name, if found, is used. 3135ffd83dbSDimitry Andric // Otherwise, it is looked up in the context of the entire 3145ffd83dbSDimitry Andric // postfix-expression. 3155ffd83dbSDimitry Andric // 3165ffd83dbSDimitry Andric // This looks in the same scopes as for an unqualified destructor name: 3175ffd83dbSDimitry Andric // 3180b57cec5SDimitry Andric // C++ [basic.lookup.classref]p3: 3190b57cec5SDimitry Andric // If the unqualified-id is ~ type-name, the type-name is looked up 3200b57cec5SDimitry Andric // in the context of the entire postfix-expression. If the type T 3210b57cec5SDimitry Andric // of the object expression is of a class type C, the type-name is 3220b57cec5SDimitry Andric // also looked up in the scope of class C. At least one of the 3235ffd83dbSDimitry Andric // lookups shall find a name that refers to cv T. 3245ffd83dbSDimitry Andric // 3255ffd83dbSDimitry Andric // FIXME: The intent is unclear here. Should type-name::~type-name look in 3265ffd83dbSDimitry Andric // the scope anyway if it finds a non-matching name declared in the class? 3275ffd83dbSDimitry Andric // If both lookups succeed and find a dependent result, which result should 3285ffd83dbSDimitry Andric // we retain? (Same question for p->~type-name().) 3290b57cec5SDimitry Andric 3305ffd83dbSDimitry Andric if (NestedNameSpecifier *Prefix = 3315ffd83dbSDimitry Andric SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { 3325ffd83dbSDimitry Andric // This is 3335ffd83dbSDimitry Andric // 3345ffd83dbSDimitry Andric // nested-name-specifier type-name :: ~ type-name 3355ffd83dbSDimitry Andric // 3365ffd83dbSDimitry Andric // Look for the second type-name in the nested-name-specifier. 3375ffd83dbSDimitry Andric CXXScopeSpec PrefixSS; 3385ffd83dbSDimitry Andric PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 3395ffd83dbSDimitry Andric if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) 3405ffd83dbSDimitry Andric return T; 3410b57cec5SDimitry Andric } else { 3425ffd83dbSDimitry Andric // This is one of 3435ffd83dbSDimitry Andric // 3445ffd83dbSDimitry Andric // type-name :: ~ type-name 3455ffd83dbSDimitry Andric // ~ type-name 3465ffd83dbSDimitry Andric // 3475ffd83dbSDimitry Andric // Look in the scope and (if any) the object type. 3485ffd83dbSDimitry Andric if (ParsedType T = LookupInScope()) 3495ffd83dbSDimitry Andric return T; 3505ffd83dbSDimitry Andric if (ParsedType T = LookupInObjectType()) 3515ffd83dbSDimitry Andric return T; 3520b57cec5SDimitry Andric } 3530b57cec5SDimitry Andric 3545ffd83dbSDimitry Andric if (Failed) 3550b57cec5SDimitry Andric return nullptr; 3560b57cec5SDimitry Andric 3575ffd83dbSDimitry Andric if (IsDependent) { 3585ffd83dbSDimitry Andric // We didn't find our type, but that's OK: it's dependent anyway. 3590b57cec5SDimitry Andric 3600b57cec5SDimitry Andric // FIXME: What if we have no nested-name-specifier? 3610b57cec5SDimitry Andric QualType T = CheckTypenameType(ETK_None, SourceLocation(), 3620b57cec5SDimitry Andric SS.getWithLocInContext(Context), 3630b57cec5SDimitry Andric II, NameLoc); 3640b57cec5SDimitry Andric return ParsedType::make(T); 3650b57cec5SDimitry Andric } 3660b57cec5SDimitry Andric 3675ffd83dbSDimitry Andric // The remaining cases are all non-standard extensions imitating the behavior 3685ffd83dbSDimitry Andric // of various other compilers. 3695ffd83dbSDimitry Andric unsigned NumNonExtensionDecls = FoundDecls.size(); 3705ffd83dbSDimitry Andric 3715ffd83dbSDimitry Andric if (SS.isSet()) { 3725ffd83dbSDimitry Andric // For compatibility with older broken C++ rules and existing code, 3735ffd83dbSDimitry Andric // 3745ffd83dbSDimitry Andric // nested-name-specifier :: ~ type-name 3755ffd83dbSDimitry Andric // 3765ffd83dbSDimitry Andric // also looks for type-name within the nested-name-specifier. 3775ffd83dbSDimitry Andric if (ParsedType T = LookupInNestedNameSpec(SS)) { 3785ffd83dbSDimitry Andric Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) 3795ffd83dbSDimitry Andric << SS.getRange() 3805ffd83dbSDimitry Andric << FixItHint::CreateInsertion(SS.getEndLoc(), 3815ffd83dbSDimitry Andric ("::" + II.getName()).str()); 3825ffd83dbSDimitry Andric return T; 3830b57cec5SDimitry Andric } 3845ffd83dbSDimitry Andric 3855ffd83dbSDimitry Andric // For compatibility with other compilers and older versions of Clang, 3865ffd83dbSDimitry Andric // 3875ffd83dbSDimitry Andric // nested-name-specifier type-name :: ~ type-name 3885ffd83dbSDimitry Andric // 3895ffd83dbSDimitry Andric // also looks for type-name in the scope. Unfortunately, we can't 3905ffd83dbSDimitry Andric // reasonably apply this fallback for dependent nested-name-specifiers. 3915ffd83dbSDimitry Andric if (SS.getScopeRep()->getPrefix()) { 3925ffd83dbSDimitry Andric if (ParsedType T = LookupInScope()) { 3935ffd83dbSDimitry Andric Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) 3945ffd83dbSDimitry Andric << FixItHint::CreateRemoval(SS.getRange()); 3955ffd83dbSDimitry Andric Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) 3965ffd83dbSDimitry Andric << GetTypeFromParser(T); 3975ffd83dbSDimitry Andric return T; 3985ffd83dbSDimitry Andric } 3995ffd83dbSDimitry Andric } 4005ffd83dbSDimitry Andric } 4015ffd83dbSDimitry Andric 4025ffd83dbSDimitry Andric // We didn't find anything matching; tell the user what we did find (if 4035ffd83dbSDimitry Andric // anything). 4045ffd83dbSDimitry Andric 4055ffd83dbSDimitry Andric // Don't tell the user about declarations we shouldn't have found. 4065ffd83dbSDimitry Andric FoundDecls.resize(NumNonExtensionDecls); 4075ffd83dbSDimitry Andric 4085ffd83dbSDimitry Andric // List types before non-types. 4095ffd83dbSDimitry Andric std::stable_sort(FoundDecls.begin(), FoundDecls.end(), 4105ffd83dbSDimitry Andric [](NamedDecl *A, NamedDecl *B) { 4115ffd83dbSDimitry Andric return isa<TypeDecl>(A->getUnderlyingDecl()) > 4125ffd83dbSDimitry Andric isa<TypeDecl>(B->getUnderlyingDecl()); 4135ffd83dbSDimitry Andric }); 4145ffd83dbSDimitry Andric 4155ffd83dbSDimitry Andric // Suggest a fixit to properly name the destroyed type. 4165ffd83dbSDimitry Andric auto MakeFixItHint = [&]{ 4175ffd83dbSDimitry Andric const CXXRecordDecl *Destroyed = nullptr; 4185ffd83dbSDimitry Andric // FIXME: If we have a scope specifier, suggest its last component? 4195ffd83dbSDimitry Andric if (!SearchType.isNull()) 4205ffd83dbSDimitry Andric Destroyed = SearchType->getAsCXXRecordDecl(); 4215ffd83dbSDimitry Andric else if (S) 4225ffd83dbSDimitry Andric Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity()); 4235ffd83dbSDimitry Andric if (Destroyed) 4245ffd83dbSDimitry Andric return FixItHint::CreateReplacement(SourceRange(NameLoc), 4255ffd83dbSDimitry Andric Destroyed->getNameAsString()); 4265ffd83dbSDimitry Andric return FixItHint(); 4275ffd83dbSDimitry Andric }; 4285ffd83dbSDimitry Andric 4295ffd83dbSDimitry Andric if (FoundDecls.empty()) { 4305ffd83dbSDimitry Andric // FIXME: Attempt typo-correction? 4315ffd83dbSDimitry Andric Diag(NameLoc, diag::err_undeclared_destructor_name) 4325ffd83dbSDimitry Andric << &II << MakeFixItHint(); 4335ffd83dbSDimitry Andric } else if (!SearchType.isNull() && FoundDecls.size() == 1) { 4345ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) { 4355ffd83dbSDimitry Andric assert(!SearchType.isNull() && 4365ffd83dbSDimitry Andric "should only reject a type result if we have a search type"); 4375ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(TD); 4385ffd83dbSDimitry Andric Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 4395ffd83dbSDimitry Andric << T << SearchType << MakeFixItHint(); 4405ffd83dbSDimitry Andric } else { 4415ffd83dbSDimitry Andric Diag(NameLoc, diag::err_destructor_expr_nontype) 4425ffd83dbSDimitry Andric << &II << MakeFixItHint(); 4435ffd83dbSDimitry Andric } 4445ffd83dbSDimitry Andric } else { 4455ffd83dbSDimitry Andric Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype 4465ffd83dbSDimitry Andric : diag::err_destructor_expr_mismatch) 4475ffd83dbSDimitry Andric << &II << SearchType << MakeFixItHint(); 4485ffd83dbSDimitry Andric } 4495ffd83dbSDimitry Andric 4505ffd83dbSDimitry Andric for (NamedDecl *FoundD : FoundDecls) { 4515ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) 4525ffd83dbSDimitry Andric Diag(FoundD->getLocation(), diag::note_destructor_type_here) 4535ffd83dbSDimitry Andric << Context.getTypeDeclType(TD); 4545ffd83dbSDimitry Andric else 4555ffd83dbSDimitry Andric Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) 4565ffd83dbSDimitry Andric << FoundD; 4570b57cec5SDimitry Andric } 4580b57cec5SDimitry Andric 4590b57cec5SDimitry Andric return nullptr; 4600b57cec5SDimitry Andric } 4610b57cec5SDimitry Andric 4620b57cec5SDimitry Andric ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, 4630b57cec5SDimitry Andric ParsedType ObjectType) { 4640b57cec5SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_error) 4650b57cec5SDimitry Andric return nullptr; 4660b57cec5SDimitry Andric 4670b57cec5SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { 4680b57cec5SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4690b57cec5SDimitry Andric return nullptr; 4700b57cec5SDimitry Andric } 4710b57cec5SDimitry Andric 4720b57cec5SDimitry Andric assert(DS.getTypeSpecType() == DeclSpec::TST_decltype && 4730b57cec5SDimitry Andric "unexpected type in getDestructorType"); 474349cc55cSDimitry Andric QualType T = BuildDecltypeType(DS.getRepAsExpr()); 4750b57cec5SDimitry Andric 4760b57cec5SDimitry Andric // If we know the type of the object, check that the correct destructor 4770b57cec5SDimitry Andric // type was named now; we can give better diagnostics this way. 4780b57cec5SDimitry Andric QualType SearchType = GetTypeFromParser(ObjectType); 4790b57cec5SDimitry Andric if (!SearchType.isNull() && !SearchType->isDependentType() && 4800b57cec5SDimitry Andric !Context.hasSameUnqualifiedType(T, SearchType)) { 4810b57cec5SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 4820b57cec5SDimitry Andric << T << SearchType; 4830b57cec5SDimitry Andric return nullptr; 4840b57cec5SDimitry Andric } 4850b57cec5SDimitry Andric 4860b57cec5SDimitry Andric return ParsedType::make(T); 4870b57cec5SDimitry Andric } 4880b57cec5SDimitry Andric 4890b57cec5SDimitry Andric bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, 490fe6060f1SDimitry Andric const UnqualifiedId &Name, bool IsUDSuffix) { 4910b57cec5SDimitry Andric assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); 492fe6060f1SDimitry Andric if (!IsUDSuffix) { 493fe6060f1SDimitry Andric // [over.literal] p8 494fe6060f1SDimitry Andric // 495fe6060f1SDimitry Andric // double operator""_Bq(long double); // OK: not a reserved identifier 496fe6060f1SDimitry Andric // double operator"" _Bq(long double); // ill-formed, no diagnostic required 497fe6060f1SDimitry Andric IdentifierInfo *II = Name.Identifier; 498fe6060f1SDimitry Andric ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts()); 499fe6060f1SDimitry Andric SourceLocation Loc = Name.getEndLoc(); 500349cc55cSDimitry Andric if (isReservedInAllContexts(Status) && 501fe6060f1SDimitry Andric !PP.getSourceManager().isInSystemHeader(Loc)) { 502fe6060f1SDimitry Andric Diag(Loc, diag::warn_reserved_extern_symbol) 503fe6060f1SDimitry Andric << II << static_cast<int>(Status) 504fe6060f1SDimitry Andric << FixItHint::CreateReplacement( 505fe6060f1SDimitry Andric Name.getSourceRange(), 506fe6060f1SDimitry Andric (StringRef("operator\"\"") + II->getName()).str()); 507fe6060f1SDimitry Andric } 508fe6060f1SDimitry Andric } 5090b57cec5SDimitry Andric 5100b57cec5SDimitry Andric if (!SS.isValid()) 5110b57cec5SDimitry Andric return false; 5120b57cec5SDimitry Andric 5130b57cec5SDimitry Andric switch (SS.getScopeRep()->getKind()) { 5140b57cec5SDimitry Andric case NestedNameSpecifier::Identifier: 5150b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpec: 5160b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpecWithTemplate: 5170b57cec5SDimitry Andric // Per C++11 [over.literal]p2, literal operators can only be declared at 5180b57cec5SDimitry Andric // namespace scope. Therefore, this unqualified-id cannot name anything. 5190b57cec5SDimitry Andric // Reject it early, because we have no AST representation for this in the 5200b57cec5SDimitry Andric // case where the scope is dependent. 5210b57cec5SDimitry Andric Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) 5220b57cec5SDimitry Andric << SS.getScopeRep(); 5230b57cec5SDimitry Andric return true; 5240b57cec5SDimitry Andric 5250b57cec5SDimitry Andric case NestedNameSpecifier::Global: 5260b57cec5SDimitry Andric case NestedNameSpecifier::Super: 5270b57cec5SDimitry Andric case NestedNameSpecifier::Namespace: 5280b57cec5SDimitry Andric case NestedNameSpecifier::NamespaceAlias: 5290b57cec5SDimitry Andric return false; 5300b57cec5SDimitry Andric } 5310b57cec5SDimitry Andric 5320b57cec5SDimitry Andric llvm_unreachable("unknown nested name specifier kind"); 5330b57cec5SDimitry Andric } 5340b57cec5SDimitry Andric 5350b57cec5SDimitry Andric /// Build a C++ typeid expression with a type operand. 5360b57cec5SDimitry Andric ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 5370b57cec5SDimitry Andric SourceLocation TypeidLoc, 5380b57cec5SDimitry Andric TypeSourceInfo *Operand, 5390b57cec5SDimitry Andric SourceLocation RParenLoc) { 5400b57cec5SDimitry Andric // C++ [expr.typeid]p4: 5410b57cec5SDimitry Andric // The top-level cv-qualifiers of the lvalue expression or the type-id 5420b57cec5SDimitry Andric // that is the operand of typeid are always ignored. 5430b57cec5SDimitry Andric // If the type of the type-id is a class type or a reference to a class 5440b57cec5SDimitry Andric // type, the class shall be completely-defined. 5450b57cec5SDimitry Andric Qualifiers Quals; 5460b57cec5SDimitry Andric QualType T 5470b57cec5SDimitry Andric = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 5480b57cec5SDimitry Andric Quals); 5490b57cec5SDimitry Andric if (T->getAs<RecordType>() && 5500b57cec5SDimitry Andric RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 5510b57cec5SDimitry Andric return ExprError(); 5520b57cec5SDimitry Andric 5530b57cec5SDimitry Andric if (T->isVariablyModifiedType()) 5540b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); 5550b57cec5SDimitry Andric 556a7dea167SDimitry Andric if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) 557a7dea167SDimitry Andric return ExprError(); 558a7dea167SDimitry Andric 5590b57cec5SDimitry Andric return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, 5600b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 5610b57cec5SDimitry Andric } 5620b57cec5SDimitry Andric 5630b57cec5SDimitry Andric /// Build a C++ typeid expression with an expression operand. 5640b57cec5SDimitry Andric ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 5650b57cec5SDimitry Andric SourceLocation TypeidLoc, 5660b57cec5SDimitry Andric Expr *E, 5670b57cec5SDimitry Andric SourceLocation RParenLoc) { 5680b57cec5SDimitry Andric bool WasEvaluated = false; 5690b57cec5SDimitry Andric if (E && !E->isTypeDependent()) { 5701fd87a68SDimitry Andric if (E->hasPlaceholderType()) { 5710b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(E); 5720b57cec5SDimitry Andric if (result.isInvalid()) return ExprError(); 5730b57cec5SDimitry Andric E = result.get(); 5740b57cec5SDimitry Andric } 5750b57cec5SDimitry Andric 5760b57cec5SDimitry Andric QualType T = E->getType(); 5770b57cec5SDimitry Andric if (const RecordType *RecordT = T->getAs<RecordType>()) { 5780b57cec5SDimitry Andric CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 5790b57cec5SDimitry Andric // C++ [expr.typeid]p3: 5800b57cec5SDimitry Andric // [...] If the type of the expression is a class type, the class 5810b57cec5SDimitry Andric // shall be completely-defined. 5820b57cec5SDimitry Andric if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 5830b57cec5SDimitry Andric return ExprError(); 5840b57cec5SDimitry Andric 5850b57cec5SDimitry Andric // C++ [expr.typeid]p3: 5860b57cec5SDimitry Andric // When typeid is applied to an expression other than an glvalue of a 5870b57cec5SDimitry Andric // polymorphic class type [...] [the] expression is an unevaluated 5880b57cec5SDimitry Andric // operand. [...] 5890b57cec5SDimitry Andric if (RecordD->isPolymorphic() && E->isGLValue()) { 590fe6060f1SDimitry Andric if (isUnevaluatedContext()) { 591fe6060f1SDimitry Andric // The operand was processed in unevaluated context, switch the 592fe6060f1SDimitry Andric // context and recheck the subexpression. 5930b57cec5SDimitry Andric ExprResult Result = TransformToPotentiallyEvaluated(E); 594fe6060f1SDimitry Andric if (Result.isInvalid()) 595fe6060f1SDimitry Andric return ExprError(); 5960b57cec5SDimitry Andric E = Result.get(); 597fe6060f1SDimitry Andric } 5980b57cec5SDimitry Andric 5990b57cec5SDimitry Andric // We require a vtable to query the type at run time. 6000b57cec5SDimitry Andric MarkVTableUsed(TypeidLoc, RecordD); 6010b57cec5SDimitry Andric WasEvaluated = true; 6020b57cec5SDimitry Andric } 6030b57cec5SDimitry Andric } 6040b57cec5SDimitry Andric 605a7dea167SDimitry Andric ExprResult Result = CheckUnevaluatedOperand(E); 606a7dea167SDimitry Andric if (Result.isInvalid()) 607a7dea167SDimitry Andric return ExprError(); 608a7dea167SDimitry Andric E = Result.get(); 609a7dea167SDimitry Andric 6100b57cec5SDimitry Andric // C++ [expr.typeid]p4: 6110b57cec5SDimitry Andric // [...] If the type of the type-id is a reference to a possibly 6120b57cec5SDimitry Andric // cv-qualified type, the result of the typeid expression refers to a 6130b57cec5SDimitry Andric // std::type_info object representing the cv-unqualified referenced 6140b57cec5SDimitry Andric // type. 6150b57cec5SDimitry Andric Qualifiers Quals; 6160b57cec5SDimitry Andric QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 6170b57cec5SDimitry Andric if (!Context.hasSameType(T, UnqualT)) { 6180b57cec5SDimitry Andric T = UnqualT; 6190b57cec5SDimitry Andric E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); 6200b57cec5SDimitry Andric } 6210b57cec5SDimitry Andric } 6220b57cec5SDimitry Andric 6230b57cec5SDimitry Andric if (E->getType()->isVariablyModifiedType()) 6240b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) 6250b57cec5SDimitry Andric << E->getType()); 6260b57cec5SDimitry Andric else if (!inTemplateInstantiation() && 6270b57cec5SDimitry Andric E->HasSideEffects(Context, WasEvaluated)) { 6280b57cec5SDimitry Andric // The expression operand for typeid is in an unevaluated expression 6290b57cec5SDimitry Andric // context, so side effects could result in unintended consequences. 6300b57cec5SDimitry Andric Diag(E->getExprLoc(), WasEvaluated 6310b57cec5SDimitry Andric ? diag::warn_side_effects_typeid 6320b57cec5SDimitry Andric : diag::warn_side_effects_unevaluated_context); 6330b57cec5SDimitry Andric } 6340b57cec5SDimitry Andric 6350b57cec5SDimitry Andric return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, 6360b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 6370b57cec5SDimitry Andric } 6380b57cec5SDimitry Andric 6390b57cec5SDimitry Andric /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 6400b57cec5SDimitry Andric ExprResult 6410b57cec5SDimitry Andric Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 6420b57cec5SDimitry Andric bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 6430b57cec5SDimitry Andric // typeid is not supported in OpenCL. 6440b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) { 6450b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) 6460b57cec5SDimitry Andric << "typeid"); 6470b57cec5SDimitry Andric } 6480b57cec5SDimitry Andric 6490b57cec5SDimitry Andric // Find the std::type_info type. 6500b57cec5SDimitry Andric if (!getStdNamespace()) 6510b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 6520b57cec5SDimitry Andric 6530b57cec5SDimitry Andric if (!CXXTypeInfoDecl) { 6540b57cec5SDimitry Andric IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 6550b57cec5SDimitry Andric LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 6560b57cec5SDimitry Andric LookupQualifiedName(R, getStdNamespace()); 6570b57cec5SDimitry Andric CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 6580b57cec5SDimitry Andric // Microsoft's typeinfo doesn't have type_info in std but in the global 6590b57cec5SDimitry Andric // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. 6600b57cec5SDimitry Andric if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { 6610b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 6620b57cec5SDimitry Andric CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 6630b57cec5SDimitry Andric } 6640b57cec5SDimitry Andric if (!CXXTypeInfoDecl) 6650b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 6660b57cec5SDimitry Andric } 6670b57cec5SDimitry Andric 6680b57cec5SDimitry Andric if (!getLangOpts().RTTI) { 6690b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 6700b57cec5SDimitry Andric } 6710b57cec5SDimitry Andric 6720b57cec5SDimitry Andric QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 6730b57cec5SDimitry Andric 6740b57cec5SDimitry Andric if (isType) { 6750b57cec5SDimitry Andric // The operand is a type; handle it as such. 6760b57cec5SDimitry Andric TypeSourceInfo *TInfo = nullptr; 6770b57cec5SDimitry Andric QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 6780b57cec5SDimitry Andric &TInfo); 6790b57cec5SDimitry Andric if (T.isNull()) 6800b57cec5SDimitry Andric return ExprError(); 6810b57cec5SDimitry Andric 6820b57cec5SDimitry Andric if (!TInfo) 6830b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 6840b57cec5SDimitry Andric 6850b57cec5SDimitry Andric return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 6860b57cec5SDimitry Andric } 6870b57cec5SDimitry Andric 6880b57cec5SDimitry Andric // The operand is an expression. 689e8d8bef9SDimitry Andric ExprResult Result = 690e8d8bef9SDimitry Andric BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc); 691e8d8bef9SDimitry Andric 692e8d8bef9SDimitry Andric if (!getLangOpts().RTTIData && !Result.isInvalid()) 693e8d8bef9SDimitry Andric if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) 694e8d8bef9SDimitry Andric if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) 695e8d8bef9SDimitry Andric Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) 696e8d8bef9SDimitry Andric << (getDiagnostics().getDiagnosticOptions().getFormat() == 697e8d8bef9SDimitry Andric DiagnosticOptions::MSVC); 698e8d8bef9SDimitry Andric return Result; 6990b57cec5SDimitry Andric } 7000b57cec5SDimitry Andric 7010b57cec5SDimitry Andric /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to 7020b57cec5SDimitry Andric /// a single GUID. 7030b57cec5SDimitry Andric static void 7040b57cec5SDimitry Andric getUuidAttrOfType(Sema &SemaRef, QualType QT, 7050b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { 7060b57cec5SDimitry Andric // Optionally remove one level of pointer, reference or array indirection. 7070b57cec5SDimitry Andric const Type *Ty = QT.getTypePtr(); 7080b57cec5SDimitry Andric if (QT->isPointerType() || QT->isReferenceType()) 7090b57cec5SDimitry Andric Ty = QT->getPointeeType().getTypePtr(); 7100b57cec5SDimitry Andric else if (QT->isArrayType()) 7110b57cec5SDimitry Andric Ty = Ty->getBaseElementTypeUnsafe(); 7120b57cec5SDimitry Andric 7130b57cec5SDimitry Andric const auto *TD = Ty->getAsTagDecl(); 7140b57cec5SDimitry Andric if (!TD) 7150b57cec5SDimitry Andric return; 7160b57cec5SDimitry Andric 7170b57cec5SDimitry Andric if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { 7180b57cec5SDimitry Andric UuidAttrs.insert(Uuid); 7190b57cec5SDimitry Andric return; 7200b57cec5SDimitry Andric } 7210b57cec5SDimitry Andric 7220b57cec5SDimitry Andric // __uuidof can grab UUIDs from template arguments. 7230b57cec5SDimitry Andric if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { 7240b57cec5SDimitry Andric const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 7250b57cec5SDimitry Andric for (const TemplateArgument &TA : TAL.asArray()) { 7260b57cec5SDimitry Andric const UuidAttr *UuidForTA = nullptr; 7270b57cec5SDimitry Andric if (TA.getKind() == TemplateArgument::Type) 7280b57cec5SDimitry Andric getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); 7290b57cec5SDimitry Andric else if (TA.getKind() == TemplateArgument::Declaration) 7300b57cec5SDimitry Andric getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); 7310b57cec5SDimitry Andric 7320b57cec5SDimitry Andric if (UuidForTA) 7330b57cec5SDimitry Andric UuidAttrs.insert(UuidForTA); 7340b57cec5SDimitry Andric } 7350b57cec5SDimitry Andric } 7360b57cec5SDimitry Andric } 7370b57cec5SDimitry Andric 7380b57cec5SDimitry Andric /// Build a Microsoft __uuidof expression with a type operand. 7395ffd83dbSDimitry Andric ExprResult Sema::BuildCXXUuidof(QualType Type, 7400b57cec5SDimitry Andric SourceLocation TypeidLoc, 7410b57cec5SDimitry Andric TypeSourceInfo *Operand, 7420b57cec5SDimitry Andric SourceLocation RParenLoc) { 7435ffd83dbSDimitry Andric MSGuidDecl *Guid = nullptr; 7440b57cec5SDimitry Andric if (!Operand->getType()->isDependentType()) { 7450b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 7460b57cec5SDimitry Andric getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); 7470b57cec5SDimitry Andric if (UuidAttrs.empty()) 7480b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 7490b57cec5SDimitry Andric if (UuidAttrs.size() > 1) 7500b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 7515ffd83dbSDimitry Andric Guid = UuidAttrs.back()->getGuidDecl(); 7520b57cec5SDimitry Andric } 7530b57cec5SDimitry Andric 7545ffd83dbSDimitry Andric return new (Context) 7555ffd83dbSDimitry Andric CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); 7560b57cec5SDimitry Andric } 7570b57cec5SDimitry Andric 7580b57cec5SDimitry Andric /// Build a Microsoft __uuidof expression with an expression operand. 7595ffd83dbSDimitry Andric ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, 7605ffd83dbSDimitry Andric Expr *E, SourceLocation RParenLoc) { 7615ffd83dbSDimitry Andric MSGuidDecl *Guid = nullptr; 7620b57cec5SDimitry Andric if (!E->getType()->isDependentType()) { 7630b57cec5SDimitry Andric if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 7645ffd83dbSDimitry Andric // A null pointer results in {00000000-0000-0000-0000-000000000000}. 7655ffd83dbSDimitry Andric Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{}); 7660b57cec5SDimitry Andric } else { 7670b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 7680b57cec5SDimitry Andric getUuidAttrOfType(*this, E->getType(), UuidAttrs); 7690b57cec5SDimitry Andric if (UuidAttrs.empty()) 7700b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 7710b57cec5SDimitry Andric if (UuidAttrs.size() > 1) 7720b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 7735ffd83dbSDimitry Andric Guid = UuidAttrs.back()->getGuidDecl(); 7740b57cec5SDimitry Andric } 7750b57cec5SDimitry Andric } 7760b57cec5SDimitry Andric 7775ffd83dbSDimitry Andric return new (Context) 7785ffd83dbSDimitry Andric CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); 7790b57cec5SDimitry Andric } 7800b57cec5SDimitry Andric 7810b57cec5SDimitry Andric /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 7820b57cec5SDimitry Andric ExprResult 7830b57cec5SDimitry Andric Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 7840b57cec5SDimitry Andric bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 7855ffd83dbSDimitry Andric QualType GuidType = Context.getMSGuidType(); 7865ffd83dbSDimitry Andric GuidType.addConst(); 7870b57cec5SDimitry Andric 7880b57cec5SDimitry Andric if (isType) { 7890b57cec5SDimitry Andric // The operand is a type; handle it as such. 7900b57cec5SDimitry Andric TypeSourceInfo *TInfo = nullptr; 7910b57cec5SDimitry Andric QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 7920b57cec5SDimitry Andric &TInfo); 7930b57cec5SDimitry Andric if (T.isNull()) 7940b57cec5SDimitry Andric return ExprError(); 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric if (!TInfo) 7970b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 8000b57cec5SDimitry Andric } 8010b57cec5SDimitry Andric 8020b57cec5SDimitry Andric // The operand is an expression. 8030b57cec5SDimitry Andric return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 8040b57cec5SDimitry Andric } 8050b57cec5SDimitry Andric 8060b57cec5SDimitry Andric /// ActOnCXXBoolLiteral - Parse {true,false} literals. 8070b57cec5SDimitry Andric ExprResult 8080b57cec5SDimitry Andric Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 8090b57cec5SDimitry Andric assert((Kind == tok::kw_true || Kind == tok::kw_false) && 8100b57cec5SDimitry Andric "Unknown C++ Boolean value!"); 8110b57cec5SDimitry Andric return new (Context) 8120b57cec5SDimitry Andric CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 8130b57cec5SDimitry Andric } 8140b57cec5SDimitry Andric 8150b57cec5SDimitry Andric /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 8160b57cec5SDimitry Andric ExprResult 8170b57cec5SDimitry Andric Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 8180b57cec5SDimitry Andric return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 8190b57cec5SDimitry Andric } 8200b57cec5SDimitry Andric 8210b57cec5SDimitry Andric /// ActOnCXXThrow - Parse throw expressions. 8220b57cec5SDimitry Andric ExprResult 8230b57cec5SDimitry Andric Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 8240b57cec5SDimitry Andric bool IsThrownVarInScope = false; 8250b57cec5SDimitry Andric if (Ex) { 8260b57cec5SDimitry Andric // C++0x [class.copymove]p31: 8270b57cec5SDimitry Andric // When certain criteria are met, an implementation is allowed to omit the 8280b57cec5SDimitry Andric // copy/move construction of a class object [...] 8290b57cec5SDimitry Andric // 8300b57cec5SDimitry Andric // - in a throw-expression, when the operand is the name of a 8310b57cec5SDimitry Andric // non-volatile automatic object (other than a function or catch- 8320b57cec5SDimitry Andric // clause parameter) whose scope does not extend beyond the end of the 8330b57cec5SDimitry Andric // innermost enclosing try-block (if there is one), the copy/move 8340b57cec5SDimitry Andric // operation from the operand to the exception object (15.1) can be 8350b57cec5SDimitry Andric // omitted by constructing the automatic object directly into the 8360b57cec5SDimitry Andric // exception object 8370b57cec5SDimitry Andric if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 8380b57cec5SDimitry Andric if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 8390b57cec5SDimitry Andric if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { 8400b57cec5SDimitry Andric for( ; S; S = S->getParent()) { 8410b57cec5SDimitry Andric if (S->isDeclScope(Var)) { 8420b57cec5SDimitry Andric IsThrownVarInScope = true; 8430b57cec5SDimitry Andric break; 8440b57cec5SDimitry Andric } 8450b57cec5SDimitry Andric 84681ad6265SDimitry Andric // FIXME: Many of the scope checks here seem incorrect. 8470b57cec5SDimitry Andric if (S->getFlags() & 8480b57cec5SDimitry Andric (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 84981ad6265SDimitry Andric Scope::ObjCMethodScope | Scope::TryScope)) 8500b57cec5SDimitry Andric break; 8510b57cec5SDimitry Andric } 8520b57cec5SDimitry Andric } 8530b57cec5SDimitry Andric } 8540b57cec5SDimitry Andric } 8550b57cec5SDimitry Andric 8560b57cec5SDimitry Andric return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 8570b57cec5SDimitry Andric } 8580b57cec5SDimitry Andric 8590b57cec5SDimitry Andric ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 8600b57cec5SDimitry Andric bool IsThrownVarInScope) { 8610b57cec5SDimitry Andric // Don't report an error if 'throw' is used in system headers. 8620b57cec5SDimitry Andric if (!getLangOpts().CXXExceptions && 8630b57cec5SDimitry Andric !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { 8640b57cec5SDimitry Andric // Delay error emission for the OpenMP device code. 8650b57cec5SDimitry Andric targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric 8680b57cec5SDimitry Andric // Exceptions aren't allowed in CUDA device code. 8690b57cec5SDimitry Andric if (getLangOpts().CUDA) 8700b57cec5SDimitry Andric CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) 8710b57cec5SDimitry Andric << "throw" << CurrentCUDATarget(); 8720b57cec5SDimitry Andric 8730b57cec5SDimitry Andric if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 8740b57cec5SDimitry Andric Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; 8750b57cec5SDimitry Andric 8760b57cec5SDimitry Andric if (Ex && !Ex->isTypeDependent()) { 8770b57cec5SDimitry Andric // Initialize the exception result. This implicitly weeds out 8780b57cec5SDimitry Andric // abstract types or types with inaccessible copy constructors. 8790b57cec5SDimitry Andric 8800b57cec5SDimitry Andric // C++0x [class.copymove]p31: 8810b57cec5SDimitry Andric // When certain criteria are met, an implementation is allowed to omit the 8820b57cec5SDimitry Andric // copy/move construction of a class object [...] 8830b57cec5SDimitry Andric // 8840b57cec5SDimitry Andric // - in a throw-expression, when the operand is the name of a 8850b57cec5SDimitry Andric // non-volatile automatic object (other than a function or 8860b57cec5SDimitry Andric // catch-clause 8870b57cec5SDimitry Andric // parameter) whose scope does not extend beyond the end of the 8880b57cec5SDimitry Andric // innermost enclosing try-block (if there is one), the copy/move 8890b57cec5SDimitry Andric // operation from the operand to the exception object (15.1) can be 8900b57cec5SDimitry Andric // omitted by constructing the automatic object directly into the 8910b57cec5SDimitry Andric // exception object 892fe6060f1SDimitry Andric NamedReturnInfo NRInfo = 893fe6060f1SDimitry Andric IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo(); 894fe6060f1SDimitry Andric 895fe6060f1SDimitry Andric QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); 896fe6060f1SDimitry Andric if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) 897fe6060f1SDimitry Andric return ExprError(); 8980b57cec5SDimitry Andric 89928a41182SDimitry Andric InitializedEntity Entity = 90028a41182SDimitry Andric InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy); 901fe6060f1SDimitry Andric ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex); 9020b57cec5SDimitry Andric if (Res.isInvalid()) 9030b57cec5SDimitry Andric return ExprError(); 9040b57cec5SDimitry Andric Ex = Res.get(); 9050b57cec5SDimitry Andric } 9060b57cec5SDimitry Andric 907e8d8bef9SDimitry Andric // PPC MMA non-pointer types are not allowed as throw expr types. 908e8d8bef9SDimitry Andric if (Ex && Context.getTargetInfo().getTriple().isPPC64()) 909e8d8bef9SDimitry Andric CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc()); 910e8d8bef9SDimitry Andric 9110b57cec5SDimitry Andric return new (Context) 9120b57cec5SDimitry Andric CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); 9130b57cec5SDimitry Andric } 9140b57cec5SDimitry Andric 9150b57cec5SDimitry Andric static void 9160b57cec5SDimitry Andric collectPublicBases(CXXRecordDecl *RD, 9170b57cec5SDimitry Andric llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, 9180b57cec5SDimitry Andric llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, 9190b57cec5SDimitry Andric llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, 9200b57cec5SDimitry Andric bool ParentIsPublic) { 9210b57cec5SDimitry Andric for (const CXXBaseSpecifier &BS : RD->bases()) { 9220b57cec5SDimitry Andric CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 9230b57cec5SDimitry Andric bool NewSubobject; 9240b57cec5SDimitry Andric // Virtual bases constitute the same subobject. Non-virtual bases are 9250b57cec5SDimitry Andric // always distinct subobjects. 9260b57cec5SDimitry Andric if (BS.isVirtual()) 9270b57cec5SDimitry Andric NewSubobject = VBases.insert(BaseDecl).second; 9280b57cec5SDimitry Andric else 9290b57cec5SDimitry Andric NewSubobject = true; 9300b57cec5SDimitry Andric 9310b57cec5SDimitry Andric if (NewSubobject) 9320b57cec5SDimitry Andric ++SubobjectsSeen[BaseDecl]; 9330b57cec5SDimitry Andric 9340b57cec5SDimitry Andric // Only add subobjects which have public access throughout the entire chain. 9350b57cec5SDimitry Andric bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; 9360b57cec5SDimitry Andric if (PublicPath) 9370b57cec5SDimitry Andric PublicSubobjectsSeen.insert(BaseDecl); 9380b57cec5SDimitry Andric 9390b57cec5SDimitry Andric // Recurse on to each base subobject. 9400b57cec5SDimitry Andric collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, 9410b57cec5SDimitry Andric PublicPath); 9420b57cec5SDimitry Andric } 9430b57cec5SDimitry Andric } 9440b57cec5SDimitry Andric 9450b57cec5SDimitry Andric static void getUnambiguousPublicSubobjects( 9460b57cec5SDimitry Andric CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { 9470b57cec5SDimitry Andric llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; 9480b57cec5SDimitry Andric llvm::SmallSet<CXXRecordDecl *, 2> VBases; 9490b57cec5SDimitry Andric llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; 9500b57cec5SDimitry Andric SubobjectsSeen[RD] = 1; 9510b57cec5SDimitry Andric PublicSubobjectsSeen.insert(RD); 9520b57cec5SDimitry Andric collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, 9530b57cec5SDimitry Andric /*ParentIsPublic=*/true); 9540b57cec5SDimitry Andric 9550b57cec5SDimitry Andric for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { 9560b57cec5SDimitry Andric // Skip ambiguous objects. 9570b57cec5SDimitry Andric if (SubobjectsSeen[PublicSubobject] > 1) 9580b57cec5SDimitry Andric continue; 9590b57cec5SDimitry Andric 9600b57cec5SDimitry Andric Objects.push_back(PublicSubobject); 9610b57cec5SDimitry Andric } 9620b57cec5SDimitry Andric } 9630b57cec5SDimitry Andric 9640b57cec5SDimitry Andric /// CheckCXXThrowOperand - Validate the operand of a throw. 9650b57cec5SDimitry Andric bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, 9660b57cec5SDimitry Andric QualType ExceptionObjectTy, Expr *E) { 9670b57cec5SDimitry Andric // If the type of the exception would be an incomplete type or a pointer 9680b57cec5SDimitry Andric // to an incomplete type other than (cv) void the program is ill-formed. 9690b57cec5SDimitry Andric QualType Ty = ExceptionObjectTy; 9700b57cec5SDimitry Andric bool isPointer = false; 9710b57cec5SDimitry Andric if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 9720b57cec5SDimitry Andric Ty = Ptr->getPointeeType(); 9730b57cec5SDimitry Andric isPointer = true; 9740b57cec5SDimitry Andric } 9750b57cec5SDimitry Andric if (!isPointer || !Ty->isVoidType()) { 9760b57cec5SDimitry Andric if (RequireCompleteType(ThrowLoc, Ty, 9770b57cec5SDimitry Andric isPointer ? diag::err_throw_incomplete_ptr 9780b57cec5SDimitry Andric : diag::err_throw_incomplete, 9790b57cec5SDimitry Andric E->getSourceRange())) 9800b57cec5SDimitry Andric return true; 9810b57cec5SDimitry Andric 9825ffd83dbSDimitry Andric if (!isPointer && Ty->isSizelessType()) { 9835ffd83dbSDimitry Andric Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); 9845ffd83dbSDimitry Andric return true; 9855ffd83dbSDimitry Andric } 9865ffd83dbSDimitry Andric 9870b57cec5SDimitry Andric if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, 9880b57cec5SDimitry Andric diag::err_throw_abstract_type, E)) 9890b57cec5SDimitry Andric return true; 9900b57cec5SDimitry Andric } 9910b57cec5SDimitry Andric 9920b57cec5SDimitry Andric // If the exception has class type, we need additional handling. 9930b57cec5SDimitry Andric CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9940b57cec5SDimitry Andric if (!RD) 9950b57cec5SDimitry Andric return false; 9960b57cec5SDimitry Andric 9970b57cec5SDimitry Andric // If we are throwing a polymorphic class type or pointer thereof, 9980b57cec5SDimitry Andric // exception handling will make use of the vtable. 9990b57cec5SDimitry Andric MarkVTableUsed(ThrowLoc, RD); 10000b57cec5SDimitry Andric 10010b57cec5SDimitry Andric // If a pointer is thrown, the referenced object will not be destroyed. 10020b57cec5SDimitry Andric if (isPointer) 10030b57cec5SDimitry Andric return false; 10040b57cec5SDimitry Andric 10050b57cec5SDimitry Andric // If the class has a destructor, we must be able to call it. 10060b57cec5SDimitry Andric if (!RD->hasIrrelevantDestructor()) { 10070b57cec5SDimitry Andric if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10080b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), Destructor); 10090b57cec5SDimitry Andric CheckDestructorAccess(E->getExprLoc(), Destructor, 10100b57cec5SDimitry Andric PDiag(diag::err_access_dtor_exception) << Ty); 10110b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 10120b57cec5SDimitry Andric return true; 10130b57cec5SDimitry Andric } 10140b57cec5SDimitry Andric } 10150b57cec5SDimitry Andric 10160b57cec5SDimitry Andric // The MSVC ABI creates a list of all types which can catch the exception 10170b57cec5SDimitry Andric // object. This list also references the appropriate copy constructor to call 10180b57cec5SDimitry Andric // if the object is caught by value and has a non-trivial copy constructor. 10190b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 10200b57cec5SDimitry Andric // We are only interested in the public, unambiguous bases contained within 10210b57cec5SDimitry Andric // the exception object. Bases which are ambiguous or otherwise 10220b57cec5SDimitry Andric // inaccessible are not catchable types. 10230b57cec5SDimitry Andric llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; 10240b57cec5SDimitry Andric getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); 10250b57cec5SDimitry Andric 10260b57cec5SDimitry Andric for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { 10270b57cec5SDimitry Andric // Attempt to lookup the copy constructor. Various pieces of machinery 10280b57cec5SDimitry Andric // will spring into action, like template instantiation, which means this 10290b57cec5SDimitry Andric // cannot be a simple walk of the class's decls. Instead, we must perform 10300b57cec5SDimitry Andric // lookup and overload resolution. 10310b57cec5SDimitry Andric CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); 1032480093f4SDimitry Andric if (!CD || CD->isDeleted()) 10330b57cec5SDimitry Andric continue; 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric // Mark the constructor referenced as it is used by this throw expression. 10360b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), CD); 10370b57cec5SDimitry Andric 10380b57cec5SDimitry Andric // Skip this copy constructor if it is trivial, we don't need to record it 10390b57cec5SDimitry Andric // in the catchable type data. 10400b57cec5SDimitry Andric if (CD->isTrivial()) 10410b57cec5SDimitry Andric continue; 10420b57cec5SDimitry Andric 10430b57cec5SDimitry Andric // The copy constructor is non-trivial, create a mapping from this class 10440b57cec5SDimitry Andric // type to this constructor. 10450b57cec5SDimitry Andric // N.B. The selection of copy constructor is not sensitive to this 10460b57cec5SDimitry Andric // particular throw-site. Lookup will be performed at the catch-site to 10470b57cec5SDimitry Andric // ensure that the copy constructor is, in fact, accessible (via 10480b57cec5SDimitry Andric // friendship or any other means). 10490b57cec5SDimitry Andric Context.addCopyConstructorForExceptionObject(Subobject, CD); 10500b57cec5SDimitry Andric 10510b57cec5SDimitry Andric // We don't keep the instantiated default argument expressions around so 10520b57cec5SDimitry Andric // we must rebuild them here. 10530b57cec5SDimitry Andric for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { 10540b57cec5SDimitry Andric if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) 10550b57cec5SDimitry Andric return true; 10560b57cec5SDimitry Andric } 10570b57cec5SDimitry Andric } 10580b57cec5SDimitry Andric } 10590b57cec5SDimitry Andric 10600b57cec5SDimitry Andric // Under the Itanium C++ ABI, memory for the exception object is allocated by 10610b57cec5SDimitry Andric // the runtime with no ability for the compiler to request additional 10620b57cec5SDimitry Andric // alignment. Warn if the exception type requires alignment beyond the minimum 10630b57cec5SDimitry Andric // guaranteed by the target C++ runtime. 10640b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { 10650b57cec5SDimitry Andric CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); 10660b57cec5SDimitry Andric CharUnits ExnObjAlign = Context.getExnObjectAlignment(); 10670b57cec5SDimitry Andric if (ExnObjAlign < TypeAlign) { 10680b57cec5SDimitry Andric Diag(ThrowLoc, diag::warn_throw_underaligned_obj); 10690b57cec5SDimitry Andric Diag(ThrowLoc, diag::note_throw_underaligned_obj) 10700b57cec5SDimitry Andric << Ty << (unsigned)TypeAlign.getQuantity() 10710b57cec5SDimitry Andric << (unsigned)ExnObjAlign.getQuantity(); 10720b57cec5SDimitry Andric } 10730b57cec5SDimitry Andric } 10740b57cec5SDimitry Andric 10750b57cec5SDimitry Andric return false; 10760b57cec5SDimitry Andric } 10770b57cec5SDimitry Andric 10780b57cec5SDimitry Andric static QualType adjustCVQualifiersForCXXThisWithinLambda( 10790b57cec5SDimitry Andric ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, 10800b57cec5SDimitry Andric DeclContext *CurSemaContext, ASTContext &ASTCtx) { 10810b57cec5SDimitry Andric 10820b57cec5SDimitry Andric QualType ClassType = ThisTy->getPointeeType(); 10830b57cec5SDimitry Andric LambdaScopeInfo *CurLSI = nullptr; 10840b57cec5SDimitry Andric DeclContext *CurDC = CurSemaContext; 10850b57cec5SDimitry Andric 10860b57cec5SDimitry Andric // Iterate through the stack of lambdas starting from the innermost lambda to 10870b57cec5SDimitry Andric // the outermost lambda, checking if '*this' is ever captured by copy - since 10880b57cec5SDimitry Andric // that could change the cv-qualifiers of the '*this' object. 10890b57cec5SDimitry Andric // The object referred to by '*this' starts out with the cv-qualifiers of its 10900b57cec5SDimitry Andric // member function. We then start with the innermost lambda and iterate 10910b57cec5SDimitry Andric // outward checking to see if any lambda performs a by-copy capture of '*this' 10920b57cec5SDimitry Andric // - and if so, any nested lambda must respect the 'constness' of that 10930b57cec5SDimitry Andric // capturing lamdbda's call operator. 10940b57cec5SDimitry Andric // 10950b57cec5SDimitry Andric 10960b57cec5SDimitry Andric // Since the FunctionScopeInfo stack is representative of the lexical 10970b57cec5SDimitry Andric // nesting of the lambda expressions during initial parsing (and is the best 10980b57cec5SDimitry Andric // place for querying information about captures about lambdas that are 10990b57cec5SDimitry Andric // partially processed) and perhaps during instantiation of function templates 11000b57cec5SDimitry Andric // that contain lambda expressions that need to be transformed BUT not 11010b57cec5SDimitry Andric // necessarily during instantiation of a nested generic lambda's function call 11020b57cec5SDimitry Andric // operator (which might even be instantiated at the end of the TU) - at which 11030b57cec5SDimitry Andric // time the DeclContext tree is mature enough to query capture information 11040b57cec5SDimitry Andric // reliably - we use a two pronged approach to walk through all the lexically 11050b57cec5SDimitry Andric // enclosing lambda expressions: 11060b57cec5SDimitry Andric // 11070b57cec5SDimitry Andric // 1) Climb down the FunctionScopeInfo stack as long as each item represents 11080b57cec5SDimitry Andric // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically 11090b57cec5SDimitry Andric // enclosed by the call-operator of the LSI below it on the stack (while 11100b57cec5SDimitry Andric // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on 11110b57cec5SDimitry Andric // the stack represents the innermost lambda. 11120b57cec5SDimitry Andric // 11130b57cec5SDimitry Andric // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext 11140b57cec5SDimitry Andric // represents a lambda's call operator. If it does, we must be instantiating 11150b57cec5SDimitry Andric // a generic lambda's call operator (represented by the Current LSI, and 11160b57cec5SDimitry Andric // should be the only scenario where an inconsistency between the LSI and the 11170b57cec5SDimitry Andric // DeclContext should occur), so climb out the DeclContexts if they 11180b57cec5SDimitry Andric // represent lambdas, while querying the corresponding closure types 11190b57cec5SDimitry Andric // regarding capture information. 11200b57cec5SDimitry Andric 11210b57cec5SDimitry Andric // 1) Climb down the function scope info stack. 11220b57cec5SDimitry Andric for (int I = FunctionScopes.size(); 11230b57cec5SDimitry Andric I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && 11240b57cec5SDimitry Andric (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == 11250b57cec5SDimitry Andric cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); 11260b57cec5SDimitry Andric CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { 11270b57cec5SDimitry Andric CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); 11280b57cec5SDimitry Andric 11290b57cec5SDimitry Andric if (!CurLSI->isCXXThisCaptured()) 11300b57cec5SDimitry Andric continue; 11310b57cec5SDimitry Andric 11320b57cec5SDimitry Andric auto C = CurLSI->getCXXThisCapture(); 11330b57cec5SDimitry Andric 11340b57cec5SDimitry Andric if (C.isCopyCapture()) { 11350b57cec5SDimitry Andric ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 11360b57cec5SDimitry Andric if (CurLSI->CallOperator->isConst()) 11370b57cec5SDimitry Andric ClassType.addConst(); 11380b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11390b57cec5SDimitry Andric } 11400b57cec5SDimitry Andric } 11410b57cec5SDimitry Andric 1142349cc55cSDimitry Andric // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which 1143349cc55cSDimitry Andric // can happen during instantiation of its nested generic lambda call 1144349cc55cSDimitry Andric // operator); 2. if we're in a lambda scope (lambda body). 1145349cc55cSDimitry Andric if (CurLSI && isLambdaCallOperator(CurDC)) { 11460b57cec5SDimitry Andric assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && 11470b57cec5SDimitry Andric "While computing 'this' capture-type for a generic lambda, when we " 11480b57cec5SDimitry Andric "run out of enclosing LSI's, yet the enclosing DC is a " 11490b57cec5SDimitry Andric "lambda-call-operator we must be (i.e. Current LSI) in a generic " 11500b57cec5SDimitry Andric "lambda call oeprator"); 11510b57cec5SDimitry Andric assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); 11520b57cec5SDimitry Andric 11530b57cec5SDimitry Andric auto IsThisCaptured = 11540b57cec5SDimitry Andric [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { 11550b57cec5SDimitry Andric IsConst = false; 11560b57cec5SDimitry Andric IsByCopy = false; 11570b57cec5SDimitry Andric for (auto &&C : Closure->captures()) { 11580b57cec5SDimitry Andric if (C.capturesThis()) { 11590b57cec5SDimitry Andric if (C.getCaptureKind() == LCK_StarThis) 11600b57cec5SDimitry Andric IsByCopy = true; 11610b57cec5SDimitry Andric if (Closure->getLambdaCallOperator()->isConst()) 11620b57cec5SDimitry Andric IsConst = true; 11630b57cec5SDimitry Andric return true; 11640b57cec5SDimitry Andric } 11650b57cec5SDimitry Andric } 11660b57cec5SDimitry Andric return false; 11670b57cec5SDimitry Andric }; 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric bool IsByCopyCapture = false; 11700b57cec5SDimitry Andric bool IsConstCapture = false; 11710b57cec5SDimitry Andric CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); 11720b57cec5SDimitry Andric while (Closure && 11730b57cec5SDimitry Andric IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { 11740b57cec5SDimitry Andric if (IsByCopyCapture) { 11750b57cec5SDimitry Andric ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 11760b57cec5SDimitry Andric if (IsConstCapture) 11770b57cec5SDimitry Andric ClassType.addConst(); 11780b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11790b57cec5SDimitry Andric } 11800b57cec5SDimitry Andric Closure = isLambdaCallOperator(Closure->getParent()) 11810b57cec5SDimitry Andric ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) 11820b57cec5SDimitry Andric : nullptr; 11830b57cec5SDimitry Andric } 11840b57cec5SDimitry Andric } 11850b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11860b57cec5SDimitry Andric } 11870b57cec5SDimitry Andric 11880b57cec5SDimitry Andric QualType Sema::getCurrentThisType() { 11890b57cec5SDimitry Andric DeclContext *DC = getFunctionLevelDeclContext(); 11900b57cec5SDimitry Andric QualType ThisTy = CXXThisTypeOverride; 11910b57cec5SDimitry Andric 11920b57cec5SDimitry Andric if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 11930b57cec5SDimitry Andric if (method && method->isInstance()) 11940b57cec5SDimitry Andric ThisTy = method->getThisType(); 11950b57cec5SDimitry Andric } 11960b57cec5SDimitry Andric 11970b57cec5SDimitry Andric if (ThisTy.isNull() && isLambdaCallOperator(CurContext) && 1198fe6060f1SDimitry Andric inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) { 11990b57cec5SDimitry Andric 12000b57cec5SDimitry Andric // This is a lambda call operator that is being instantiated as a default 12010b57cec5SDimitry Andric // initializer. DC must point to the enclosing class type, so we can recover 12020b57cec5SDimitry Andric // the 'this' type from it. 12030b57cec5SDimitry Andric QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); 12040b57cec5SDimitry Andric // There are no cv-qualifiers for 'this' within default initializers, 12050b57cec5SDimitry Andric // per [expr.prim.general]p4. 12060b57cec5SDimitry Andric ThisTy = Context.getPointerType(ClassTy); 12070b57cec5SDimitry Andric } 12080b57cec5SDimitry Andric 12090b57cec5SDimitry Andric // If we are within a lambda's call operator, the cv-qualifiers of 'this' 12100b57cec5SDimitry Andric // might need to be adjusted if the lambda or any of its enclosing lambda's 12110b57cec5SDimitry Andric // captures '*this' by copy. 12120b57cec5SDimitry Andric if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) 12130b57cec5SDimitry Andric return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, 12140b57cec5SDimitry Andric CurContext, Context); 12150b57cec5SDimitry Andric return ThisTy; 12160b57cec5SDimitry Andric } 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 12190b57cec5SDimitry Andric Decl *ContextDecl, 12200b57cec5SDimitry Andric Qualifiers CXXThisTypeQuals, 12210b57cec5SDimitry Andric bool Enabled) 12220b57cec5SDimitry Andric : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 12230b57cec5SDimitry Andric { 12240b57cec5SDimitry Andric if (!Enabled || !ContextDecl) 12250b57cec5SDimitry Andric return; 12260b57cec5SDimitry Andric 12270b57cec5SDimitry Andric CXXRecordDecl *Record = nullptr; 12280b57cec5SDimitry Andric if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 12290b57cec5SDimitry Andric Record = Template->getTemplatedDecl(); 12300b57cec5SDimitry Andric else 12310b57cec5SDimitry Andric Record = cast<CXXRecordDecl>(ContextDecl); 12320b57cec5SDimitry Andric 12330b57cec5SDimitry Andric QualType T = S.Context.getRecordType(Record); 12340b57cec5SDimitry Andric T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); 12350b57cec5SDimitry Andric 12360b57cec5SDimitry Andric S.CXXThisTypeOverride = S.Context.getPointerType(T); 12370b57cec5SDimitry Andric 12380b57cec5SDimitry Andric this->Enabled = true; 12390b57cec5SDimitry Andric } 12400b57cec5SDimitry Andric 12410b57cec5SDimitry Andric 12420b57cec5SDimitry Andric Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { 12430b57cec5SDimitry Andric if (Enabled) { 12440b57cec5SDimitry Andric S.CXXThisTypeOverride = OldCXXThisTypeOverride; 12450b57cec5SDimitry Andric } 12460b57cec5SDimitry Andric } 12470b57cec5SDimitry Andric 1248fe6060f1SDimitry Andric static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { 1249fe6060f1SDimitry Andric SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); 1250fe6060f1SDimitry Andric assert(!LSI->isCXXThisCaptured()); 1251fe6060f1SDimitry Andric // [=, this] {}; // until C++20: Error: this when = is the default 1252fe6060f1SDimitry Andric if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval && 1253fe6060f1SDimitry Andric !Sema.getLangOpts().CPlusPlus20) 1254fe6060f1SDimitry Andric return; 1255fe6060f1SDimitry Andric Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit) 1256fe6060f1SDimitry Andric << FixItHint::CreateInsertion( 1257fe6060f1SDimitry Andric DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this"); 1258fe6060f1SDimitry Andric } 1259fe6060f1SDimitry Andric 12600b57cec5SDimitry Andric bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, 12610b57cec5SDimitry Andric bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, 12620b57cec5SDimitry Andric const bool ByCopy) { 12630b57cec5SDimitry Andric // We don't need to capture this in an unevaluated context. 12640b57cec5SDimitry Andric if (isUnevaluatedContext() && !Explicit) 12650b57cec5SDimitry Andric return true; 12660b57cec5SDimitry Andric 12670b57cec5SDimitry Andric assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); 12680b57cec5SDimitry Andric 12690b57cec5SDimitry Andric const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12700b57cec5SDimitry Andric ? *FunctionScopeIndexToStopAt 12710b57cec5SDimitry Andric : FunctionScopes.size() - 1; 12720b57cec5SDimitry Andric 12730b57cec5SDimitry Andric // Check that we can capture the *enclosing object* (referred to by '*this') 12740b57cec5SDimitry Andric // by the capturing-entity/closure (lambda/block/etc) at 12750b57cec5SDimitry Andric // MaxFunctionScopesIndex-deep on the FunctionScopes stack. 12760b57cec5SDimitry Andric 12770b57cec5SDimitry Andric // Note: The *enclosing object* can only be captured by-value by a 12780b57cec5SDimitry Andric // closure that is a lambda, using the explicit notation: 12790b57cec5SDimitry Andric // [*this] { ... }. 12800b57cec5SDimitry Andric // Every other capture of the *enclosing object* results in its by-reference 12810b57cec5SDimitry Andric // capture. 12820b57cec5SDimitry Andric 12830b57cec5SDimitry Andric // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes 12840b57cec5SDimitry Andric // stack), we can capture the *enclosing object* only if: 12850b57cec5SDimitry Andric // - 'L' has an explicit byref or byval capture of the *enclosing object* 12860b57cec5SDimitry Andric // - or, 'L' has an implicit capture. 12870b57cec5SDimitry Andric // AND 12880b57cec5SDimitry Andric // -- there is no enclosing closure 12890b57cec5SDimitry Andric // -- or, there is some enclosing closure 'E' that has already captured the 12900b57cec5SDimitry Andric // *enclosing object*, and every intervening closure (if any) between 'E' 12910b57cec5SDimitry Andric // and 'L' can implicitly capture the *enclosing object*. 12920b57cec5SDimitry Andric // -- or, every enclosing closure can implicitly capture the 12930b57cec5SDimitry Andric // *enclosing object* 12940b57cec5SDimitry Andric 12950b57cec5SDimitry Andric 12960b57cec5SDimitry Andric unsigned NumCapturingClosures = 0; 12970b57cec5SDimitry Andric for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { 12980b57cec5SDimitry Andric if (CapturingScopeInfo *CSI = 12990b57cec5SDimitry Andric dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 13000b57cec5SDimitry Andric if (CSI->CXXThisCaptureIndex != 0) { 13010b57cec5SDimitry Andric // 'this' is already being captured; there isn't anything more to do. 13020b57cec5SDimitry Andric CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); 13030b57cec5SDimitry Andric break; 13040b57cec5SDimitry Andric } 13050b57cec5SDimitry Andric LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); 13060b57cec5SDimitry Andric if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 13070b57cec5SDimitry Andric // This context can't implicitly capture 'this'; fail out. 1308fe6060f1SDimitry Andric if (BuildAndDiagnose) { 13090b57cec5SDimitry Andric Diag(Loc, diag::err_this_capture) 13100b57cec5SDimitry Andric << (Explicit && idx == MaxFunctionScopesIndex); 1311fe6060f1SDimitry Andric if (!Explicit) 1312fe6060f1SDimitry Andric buildLambdaThisCaptureFixit(*this, LSI); 1313fe6060f1SDimitry Andric } 13140b57cec5SDimitry Andric return true; 13150b57cec5SDimitry Andric } 13160b57cec5SDimitry Andric if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 13170b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 13180b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 13190b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || 13200b57cec5SDimitry Andric (Explicit && idx == MaxFunctionScopesIndex)) { 13210b57cec5SDimitry Andric // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first 13220b57cec5SDimitry Andric // iteration through can be an explicit capture, all enclosing closures, 13230b57cec5SDimitry Andric // if any, must perform implicit captures. 13240b57cec5SDimitry Andric 13250b57cec5SDimitry Andric // This closure can capture 'this'; continue looking upwards. 13260b57cec5SDimitry Andric NumCapturingClosures++; 13270b57cec5SDimitry Andric continue; 13280b57cec5SDimitry Andric } 13290b57cec5SDimitry Andric // This context can't implicitly capture 'this'; fail out. 13300b57cec5SDimitry Andric if (BuildAndDiagnose) 13310b57cec5SDimitry Andric Diag(Loc, diag::err_this_capture) 13320b57cec5SDimitry Andric << (Explicit && idx == MaxFunctionScopesIndex); 1333fe6060f1SDimitry Andric 1334fe6060f1SDimitry Andric if (!Explicit) 1335fe6060f1SDimitry Andric buildLambdaThisCaptureFixit(*this, LSI); 13360b57cec5SDimitry Andric return true; 13370b57cec5SDimitry Andric } 13380b57cec5SDimitry Andric break; 13390b57cec5SDimitry Andric } 13400b57cec5SDimitry Andric if (!BuildAndDiagnose) return false; 13410b57cec5SDimitry Andric 13420b57cec5SDimitry Andric // If we got here, then the closure at MaxFunctionScopesIndex on the 13430b57cec5SDimitry Andric // FunctionScopes stack, can capture the *enclosing object*, so capture it 13440b57cec5SDimitry Andric // (including implicit by-reference captures in any enclosing closures). 13450b57cec5SDimitry Andric 13460b57cec5SDimitry Andric // In the loop below, respect the ByCopy flag only for the closure requesting 13470b57cec5SDimitry Andric // the capture (i.e. first iteration through the loop below). Ignore it for 13480b57cec5SDimitry Andric // all enclosing closure's up to NumCapturingClosures (since they must be 13490b57cec5SDimitry Andric // implicitly capturing the *enclosing object* by reference (see loop 13500b57cec5SDimitry Andric // above)). 13510b57cec5SDimitry Andric assert((!ByCopy || 13520eae32dcSDimitry Andric isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && 13530b57cec5SDimitry Andric "Only a lambda can capture the enclosing object (referred to by " 13540b57cec5SDimitry Andric "*this) by copy"); 13550b57cec5SDimitry Andric QualType ThisTy = getCurrentThisType(); 13560b57cec5SDimitry Andric for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; 13570b57cec5SDimitry Andric --idx, --NumCapturingClosures) { 13580b57cec5SDimitry Andric CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 13590b57cec5SDimitry Andric 13600b57cec5SDimitry Andric // The type of the corresponding data member (not a 'this' pointer if 'by 13610b57cec5SDimitry Andric // copy'). 13620b57cec5SDimitry Andric QualType CaptureType = ThisTy; 13630b57cec5SDimitry Andric if (ByCopy) { 13640b57cec5SDimitry Andric // If we are capturing the object referred to by '*this' by copy, ignore 13650b57cec5SDimitry Andric // any cv qualifiers inherited from the type of the member function for 13660b57cec5SDimitry Andric // the type of the closure-type's corresponding data member and any use 13670b57cec5SDimitry Andric // of 'this'. 13680b57cec5SDimitry Andric CaptureType = ThisTy->getPointeeType(); 13690b57cec5SDimitry Andric CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 13700b57cec5SDimitry Andric } 13710b57cec5SDimitry Andric 13720b57cec5SDimitry Andric bool isNested = NumCapturingClosures > 1; 13730b57cec5SDimitry Andric CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); 13740b57cec5SDimitry Andric } 13750b57cec5SDimitry Andric return false; 13760b57cec5SDimitry Andric } 13770b57cec5SDimitry Andric 13780b57cec5SDimitry Andric ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 13790b57cec5SDimitry Andric /// C++ 9.3.2: In the body of a non-static member function, the keyword this 13800b57cec5SDimitry Andric /// is a non-lvalue expression whose value is the address of the object for 13810b57cec5SDimitry Andric /// which the function is called. 13820b57cec5SDimitry Andric 13830b57cec5SDimitry Andric QualType ThisTy = getCurrentThisType(); 13840b57cec5SDimitry Andric if (ThisTy.isNull()) 13850b57cec5SDimitry Andric return Diag(Loc, diag::err_invalid_this_use); 13860b57cec5SDimitry Andric return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); 13870b57cec5SDimitry Andric } 13880b57cec5SDimitry Andric 13890b57cec5SDimitry Andric Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, 13900b57cec5SDimitry Andric bool IsImplicit) { 13910b57cec5SDimitry Andric auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); 13920b57cec5SDimitry Andric MarkThisReferenced(This); 13930b57cec5SDimitry Andric return This; 13940b57cec5SDimitry Andric } 13950b57cec5SDimitry Andric 13960b57cec5SDimitry Andric void Sema::MarkThisReferenced(CXXThisExpr *This) { 13970b57cec5SDimitry Andric CheckCXXThisCapture(This->getExprLoc()); 13980b57cec5SDimitry Andric } 13990b57cec5SDimitry Andric 14000b57cec5SDimitry Andric bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 14010b57cec5SDimitry Andric // If we're outside the body of a member function, then we'll have a specified 14020b57cec5SDimitry Andric // type for 'this'. 14030b57cec5SDimitry Andric if (CXXThisTypeOverride.isNull()) 14040b57cec5SDimitry Andric return false; 14050b57cec5SDimitry Andric 14060b57cec5SDimitry Andric // Determine whether we're looking into a class that's currently being 14070b57cec5SDimitry Andric // defined. 14080b57cec5SDimitry Andric CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 14090b57cec5SDimitry Andric return Class && Class->isBeingDefined(); 14100b57cec5SDimitry Andric } 14110b57cec5SDimitry Andric 14120b57cec5SDimitry Andric /// Parse construction of a specified type. 14130b57cec5SDimitry Andric /// Can be interpreted either as function-style casting ("int(x)") 14140b57cec5SDimitry Andric /// or class type construction ("ClassType(x,y,z)") 14150b57cec5SDimitry Andric /// or creation of a value-initialized type ("int()"). 14160b57cec5SDimitry Andric ExprResult 14170b57cec5SDimitry Andric Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 14180b57cec5SDimitry Andric SourceLocation LParenOrBraceLoc, 14190b57cec5SDimitry Andric MultiExprArg exprs, 14200b57cec5SDimitry Andric SourceLocation RParenOrBraceLoc, 14210b57cec5SDimitry Andric bool ListInitialization) { 14220b57cec5SDimitry Andric if (!TypeRep) 14230b57cec5SDimitry Andric return ExprError(); 14240b57cec5SDimitry Andric 14250b57cec5SDimitry Andric TypeSourceInfo *TInfo; 14260b57cec5SDimitry Andric QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 14270b57cec5SDimitry Andric if (!TInfo) 14280b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 14290b57cec5SDimitry Andric 14300b57cec5SDimitry Andric auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, 14310b57cec5SDimitry Andric RParenOrBraceLoc, ListInitialization); 14320b57cec5SDimitry Andric // Avoid creating a non-type-dependent expression that contains typos. 14330b57cec5SDimitry Andric // Non-type-dependent expressions are liable to be discarded without 14340b57cec5SDimitry Andric // checking for embedded typos. 14350b57cec5SDimitry Andric if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && 14360b57cec5SDimitry Andric !Result.get()->isTypeDependent()) 14370b57cec5SDimitry Andric Result = CorrectDelayedTyposInExpr(Result.get()); 1438e8d8bef9SDimitry Andric else if (Result.isInvalid()) 1439e8d8bef9SDimitry Andric Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), 1440e8d8bef9SDimitry Andric RParenOrBraceLoc, exprs, Ty); 14410b57cec5SDimitry Andric return Result; 14420b57cec5SDimitry Andric } 14430b57cec5SDimitry Andric 14440b57cec5SDimitry Andric ExprResult 14450b57cec5SDimitry Andric Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 14460b57cec5SDimitry Andric SourceLocation LParenOrBraceLoc, 14470b57cec5SDimitry Andric MultiExprArg Exprs, 14480b57cec5SDimitry Andric SourceLocation RParenOrBraceLoc, 14490b57cec5SDimitry Andric bool ListInitialization) { 14500b57cec5SDimitry Andric QualType Ty = TInfo->getType(); 14510b57cec5SDimitry Andric SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 14520b57cec5SDimitry Andric 14530b57cec5SDimitry Andric assert((!ListInitialization || 14540b57cec5SDimitry Andric (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && 14550b57cec5SDimitry Andric "List initialization must have initializer list as expression."); 14560b57cec5SDimitry Andric SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); 14570b57cec5SDimitry Andric 1458349cc55cSDimitry Andric InitializedEntity Entity = 1459349cc55cSDimitry Andric InitializedEntity::InitializeTemporary(Context, TInfo); 14600b57cec5SDimitry Andric InitializationKind Kind = 14610b57cec5SDimitry Andric Exprs.size() 14620b57cec5SDimitry Andric ? ListInitialization 14630b57cec5SDimitry Andric ? InitializationKind::CreateDirectList( 14640b57cec5SDimitry Andric TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) 14650b57cec5SDimitry Andric : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, 14660b57cec5SDimitry Andric RParenOrBraceLoc) 14670b57cec5SDimitry Andric : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, 14680b57cec5SDimitry Andric RParenOrBraceLoc); 14690b57cec5SDimitry Andric 14700b57cec5SDimitry Andric // C++1z [expr.type.conv]p1: 14710b57cec5SDimitry Andric // If the type is a placeholder for a deduced class type, [...perform class 14720b57cec5SDimitry Andric // template argument deduction...] 147381ad6265SDimitry Andric // C++2b: 147481ad6265SDimitry Andric // Otherwise, if the type contains a placeholder type, it is replaced by the 147581ad6265SDimitry Andric // type determined by placeholder type deduction. 14760b57cec5SDimitry Andric DeducedType *Deduced = Ty->getContainedDeducedType(); 14770b57cec5SDimitry Andric if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 14780b57cec5SDimitry Andric Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, 14790b57cec5SDimitry Andric Kind, Exprs); 14800b57cec5SDimitry Andric if (Ty.isNull()) 14810b57cec5SDimitry Andric return ExprError(); 14820b57cec5SDimitry Andric Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 148381ad6265SDimitry Andric } else if (Deduced) { 148481ad6265SDimitry Andric MultiExprArg Inits = Exprs; 148581ad6265SDimitry Andric if (ListInitialization) { 148681ad6265SDimitry Andric auto *ILE = cast<InitListExpr>(Exprs[0]); 148781ad6265SDimitry Andric Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); 148881ad6265SDimitry Andric } 148981ad6265SDimitry Andric 149081ad6265SDimitry Andric if (Inits.empty()) 149181ad6265SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression) 149281ad6265SDimitry Andric << Ty << FullRange); 149381ad6265SDimitry Andric if (Inits.size() > 1) { 149481ad6265SDimitry Andric Expr *FirstBad = Inits[1]; 149581ad6265SDimitry Andric return ExprError(Diag(FirstBad->getBeginLoc(), 149681ad6265SDimitry Andric diag::err_auto_expr_init_multiple_expressions) 149781ad6265SDimitry Andric << Ty << FullRange); 149881ad6265SDimitry Andric } 149981ad6265SDimitry Andric if (getLangOpts().CPlusPlus2b) { 150081ad6265SDimitry Andric if (Ty->getAs<AutoType>()) 150181ad6265SDimitry Andric Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange; 150281ad6265SDimitry Andric } 150381ad6265SDimitry Andric Expr *Deduce = Inits[0]; 150481ad6265SDimitry Andric if (isa<InitListExpr>(Deduce)) 150581ad6265SDimitry Andric return ExprError( 150681ad6265SDimitry Andric Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) 150781ad6265SDimitry Andric << ListInitialization << Ty << FullRange); 150881ad6265SDimitry Andric QualType DeducedType; 150981ad6265SDimitry Andric if (DeduceAutoType(TInfo, Deduce, DeducedType) == DAR_Failed) 151081ad6265SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure) 151181ad6265SDimitry Andric << Ty << Deduce->getType() << FullRange 151281ad6265SDimitry Andric << Deduce->getSourceRange()); 151381ad6265SDimitry Andric if (DeducedType.isNull()) 151481ad6265SDimitry Andric return ExprError(); 151581ad6265SDimitry Andric 151681ad6265SDimitry Andric Ty = DeducedType; 151781ad6265SDimitry Andric Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 15180b57cec5SDimitry Andric } 15190b57cec5SDimitry Andric 1520e8d8bef9SDimitry Andric if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { 1521e8d8bef9SDimitry Andric // FIXME: CXXUnresolvedConstructExpr does not model list-initialization 1522e8d8bef9SDimitry Andric // directly. We work around this by dropping the locations of the braces. 1523e8d8bef9SDimitry Andric SourceRange Locs = ListInitialization 1524e8d8bef9SDimitry Andric ? SourceRange() 1525e8d8bef9SDimitry Andric : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 1526e8d8bef9SDimitry Andric return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(), 1527e8d8bef9SDimitry Andric TInfo, Locs.getBegin(), Exprs, 1528e8d8bef9SDimitry Andric Locs.getEnd()); 1529e8d8bef9SDimitry Andric } 1530e8d8bef9SDimitry Andric 15310b57cec5SDimitry Andric // C++ [expr.type.conv]p1: 15320b57cec5SDimitry Andric // If the expression list is a parenthesized single expression, the type 15330b57cec5SDimitry Andric // conversion expression is equivalent (in definedness, and if defined in 15340b57cec5SDimitry Andric // meaning) to the corresponding cast expression. 15350b57cec5SDimitry Andric if (Exprs.size() == 1 && !ListInitialization && 15360b57cec5SDimitry Andric !isa<InitListExpr>(Exprs[0])) { 15370b57cec5SDimitry Andric Expr *Arg = Exprs[0]; 15380b57cec5SDimitry Andric return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, 15390b57cec5SDimitry Andric RParenOrBraceLoc); 15400b57cec5SDimitry Andric } 15410b57cec5SDimitry Andric 15420b57cec5SDimitry Andric // For an expression of the form T(), T shall not be an array type. 15430b57cec5SDimitry Andric QualType ElemTy = Ty; 15440b57cec5SDimitry Andric if (Ty->isArrayType()) { 15450b57cec5SDimitry Andric if (!ListInitialization) 15460b57cec5SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) 15470b57cec5SDimitry Andric << FullRange); 15480b57cec5SDimitry Andric ElemTy = Context.getBaseElementType(Ty); 15490b57cec5SDimitry Andric } 15500b57cec5SDimitry Andric 15515e801ac6SDimitry Andric // Only construct objects with object types. 15524824e7fdSDimitry Andric // The standard doesn't explicitly forbid function types here, but that's an 15534824e7fdSDimitry Andric // obvious oversight, as there's no way to dynamically construct a function 15544824e7fdSDimitry Andric // in general. 15550b57cec5SDimitry Andric if (Ty->isFunctionType()) 15560b57cec5SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) 15570b57cec5SDimitry Andric << Ty << FullRange); 15580b57cec5SDimitry Andric 15590b57cec5SDimitry Andric // C++17 [expr.type.conv]p2: 15600b57cec5SDimitry Andric // If the type is cv void and the initializer is (), the expression is a 15610b57cec5SDimitry Andric // prvalue of the specified type that performs no initialization. 15620b57cec5SDimitry Andric if (!Ty->isVoidType() && 15630b57cec5SDimitry Andric RequireCompleteType(TyBeginLoc, ElemTy, 15640b57cec5SDimitry Andric diag::err_invalid_incomplete_type_use, FullRange)) 15650b57cec5SDimitry Andric return ExprError(); 15660b57cec5SDimitry Andric 15670b57cec5SDimitry Andric // Otherwise, the expression is a prvalue of the specified type whose 15680b57cec5SDimitry Andric // result object is direct-initialized (11.6) with the initializer. 15690b57cec5SDimitry Andric InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 15700b57cec5SDimitry Andric ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 15710b57cec5SDimitry Andric 15720b57cec5SDimitry Andric if (Result.isInvalid()) 15730b57cec5SDimitry Andric return Result; 15740b57cec5SDimitry Andric 15750b57cec5SDimitry Andric Expr *Inner = Result.get(); 15760b57cec5SDimitry Andric if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 15770b57cec5SDimitry Andric Inner = BTE->getSubExpr(); 15780b57cec5SDimitry Andric if (!isa<CXXTemporaryObjectExpr>(Inner) && 15790b57cec5SDimitry Andric !isa<CXXScalarValueInitExpr>(Inner)) { 15800b57cec5SDimitry Andric // If we created a CXXTemporaryObjectExpr, that node also represents the 15810b57cec5SDimitry Andric // functional cast. Otherwise, create an explicit cast to represent 15820b57cec5SDimitry Andric // the syntactic form of a functional-style cast that was used here. 15830b57cec5SDimitry Andric // 15840b57cec5SDimitry Andric // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr 15850b57cec5SDimitry Andric // would give a more consistent AST representation than using a 15860b57cec5SDimitry Andric // CXXTemporaryObjectExpr. It's also weird that the functional cast 15870b57cec5SDimitry Andric // is sometimes handled by initialization and sometimes not. 15880b57cec5SDimitry Andric QualType ResultType = Result.get()->getType(); 15890b57cec5SDimitry Andric SourceRange Locs = ListInitialization 15900b57cec5SDimitry Andric ? SourceRange() 15910b57cec5SDimitry Andric : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 15920b57cec5SDimitry Andric Result = CXXFunctionalCastExpr::Create( 15930b57cec5SDimitry Andric Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, 1594e8d8bef9SDimitry Andric Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), 1595e8d8bef9SDimitry Andric Locs.getBegin(), Locs.getEnd()); 15960b57cec5SDimitry Andric } 15970b57cec5SDimitry Andric 15980b57cec5SDimitry Andric return Result; 15990b57cec5SDimitry Andric } 16000b57cec5SDimitry Andric 16010b57cec5SDimitry Andric bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { 16020b57cec5SDimitry Andric // [CUDA] Ignore this function, if we can't call it. 160381ad6265SDimitry Andric const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); 1604e8d8bef9SDimitry Andric if (getLangOpts().CUDA) { 1605e8d8bef9SDimitry Andric auto CallPreference = IdentifyCUDAPreference(Caller, Method); 1606e8d8bef9SDimitry Andric // If it's not callable at all, it's not the right function. 1607e8d8bef9SDimitry Andric if (CallPreference < CFP_WrongSide) 16080b57cec5SDimitry Andric return false; 1609e8d8bef9SDimitry Andric if (CallPreference == CFP_WrongSide) { 1610e8d8bef9SDimitry Andric // Maybe. We have to check if there are better alternatives. 1611e8d8bef9SDimitry Andric DeclContext::lookup_result R = 1612e8d8bef9SDimitry Andric Method->getDeclContext()->lookup(Method->getDeclName()); 1613e8d8bef9SDimitry Andric for (const auto *D : R) { 1614e8d8bef9SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1615e8d8bef9SDimitry Andric if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide) 1616e8d8bef9SDimitry Andric return false; 1617e8d8bef9SDimitry Andric } 1618e8d8bef9SDimitry Andric } 1619e8d8bef9SDimitry Andric // We've found no better variants. 1620e8d8bef9SDimitry Andric } 1621e8d8bef9SDimitry Andric } 16220b57cec5SDimitry Andric 16230b57cec5SDimitry Andric SmallVector<const FunctionDecl*, 4> PreventedBy; 16240b57cec5SDimitry Andric bool Result = Method->isUsualDeallocationFunction(PreventedBy); 16250b57cec5SDimitry Andric 16260b57cec5SDimitry Andric if (Result || !getLangOpts().CUDA || PreventedBy.empty()) 16270b57cec5SDimitry Andric return Result; 16280b57cec5SDimitry Andric 16290b57cec5SDimitry Andric // In case of CUDA, return true if none of the 1-argument deallocator 16300b57cec5SDimitry Andric // functions are actually callable. 16310b57cec5SDimitry Andric return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { 16320b57cec5SDimitry Andric assert(FD->getNumParams() == 1 && 16330b57cec5SDimitry Andric "Only single-operand functions should be in PreventedBy"); 16340b57cec5SDimitry Andric return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; 16350b57cec5SDimitry Andric }); 16360b57cec5SDimitry Andric } 16370b57cec5SDimitry Andric 16380b57cec5SDimitry Andric /// Determine whether the given function is a non-placement 16390b57cec5SDimitry Andric /// deallocation function. 16400b57cec5SDimitry Andric static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 16410b57cec5SDimitry Andric if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 16420b57cec5SDimitry Andric return S.isUsualDeallocationFunction(Method); 16430b57cec5SDimitry Andric 16440b57cec5SDimitry Andric if (FD->getOverloadedOperator() != OO_Delete && 16450b57cec5SDimitry Andric FD->getOverloadedOperator() != OO_Array_Delete) 16460b57cec5SDimitry Andric return false; 16470b57cec5SDimitry Andric 16480b57cec5SDimitry Andric unsigned UsualParams = 1; 16490b57cec5SDimitry Andric 16500b57cec5SDimitry Andric if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && 16510b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 16520b57cec5SDimitry Andric FD->getParamDecl(UsualParams)->getType(), 16530b57cec5SDimitry Andric S.Context.getSizeType())) 16540b57cec5SDimitry Andric ++UsualParams; 16550b57cec5SDimitry Andric 16560b57cec5SDimitry Andric if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && 16570b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 16580b57cec5SDimitry Andric FD->getParamDecl(UsualParams)->getType(), 16590b57cec5SDimitry Andric S.Context.getTypeDeclType(S.getStdAlignValT()))) 16600b57cec5SDimitry Andric ++UsualParams; 16610b57cec5SDimitry Andric 16620b57cec5SDimitry Andric return UsualParams == FD->getNumParams(); 16630b57cec5SDimitry Andric } 16640b57cec5SDimitry Andric 16650b57cec5SDimitry Andric namespace { 16660b57cec5SDimitry Andric struct UsualDeallocFnInfo { 16670b57cec5SDimitry Andric UsualDeallocFnInfo() : Found(), FD(nullptr) {} 16680b57cec5SDimitry Andric UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) 16690b57cec5SDimitry Andric : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), 16700b57cec5SDimitry Andric Destroying(false), HasSizeT(false), HasAlignValT(false), 16710b57cec5SDimitry Andric CUDAPref(Sema::CFP_Native) { 16720b57cec5SDimitry Andric // A function template declaration is never a usual deallocation function. 16730b57cec5SDimitry Andric if (!FD) 16740b57cec5SDimitry Andric return; 16750b57cec5SDimitry Andric unsigned NumBaseParams = 1; 16760b57cec5SDimitry Andric if (FD->isDestroyingOperatorDelete()) { 16770b57cec5SDimitry Andric Destroying = true; 16780b57cec5SDimitry Andric ++NumBaseParams; 16790b57cec5SDimitry Andric } 16800b57cec5SDimitry Andric 16810b57cec5SDimitry Andric if (NumBaseParams < FD->getNumParams() && 16820b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 16830b57cec5SDimitry Andric FD->getParamDecl(NumBaseParams)->getType(), 16840b57cec5SDimitry Andric S.Context.getSizeType())) { 16850b57cec5SDimitry Andric ++NumBaseParams; 16860b57cec5SDimitry Andric HasSizeT = true; 16870b57cec5SDimitry Andric } 16880b57cec5SDimitry Andric 16890b57cec5SDimitry Andric if (NumBaseParams < FD->getNumParams() && 16900b57cec5SDimitry Andric FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { 16910b57cec5SDimitry Andric ++NumBaseParams; 16920b57cec5SDimitry Andric HasAlignValT = true; 16930b57cec5SDimitry Andric } 16940b57cec5SDimitry Andric 16950b57cec5SDimitry Andric // In CUDA, determine how much we'd like / dislike to call this. 16960b57cec5SDimitry Andric if (S.getLangOpts().CUDA) 169781ad6265SDimitry Andric if (auto *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) 16980b57cec5SDimitry Andric CUDAPref = S.IdentifyCUDAPreference(Caller, FD); 16990b57cec5SDimitry Andric } 17000b57cec5SDimitry Andric 17010b57cec5SDimitry Andric explicit operator bool() const { return FD; } 17020b57cec5SDimitry Andric 17030b57cec5SDimitry Andric bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, 17040b57cec5SDimitry Andric bool WantAlign) const { 17050b57cec5SDimitry Andric // C++ P0722: 17060b57cec5SDimitry Andric // A destroying operator delete is preferred over a non-destroying 17070b57cec5SDimitry Andric // operator delete. 17080b57cec5SDimitry Andric if (Destroying != Other.Destroying) 17090b57cec5SDimitry Andric return Destroying; 17100b57cec5SDimitry Andric 17110b57cec5SDimitry Andric // C++17 [expr.delete]p10: 17120b57cec5SDimitry Andric // If the type has new-extended alignment, a function with a parameter 17130b57cec5SDimitry Andric // of type std::align_val_t is preferred; otherwise a function without 17140b57cec5SDimitry Andric // such a parameter is preferred 17150b57cec5SDimitry Andric if (HasAlignValT != Other.HasAlignValT) 17160b57cec5SDimitry Andric return HasAlignValT == WantAlign; 17170b57cec5SDimitry Andric 17180b57cec5SDimitry Andric if (HasSizeT != Other.HasSizeT) 17190b57cec5SDimitry Andric return HasSizeT == WantSize; 17200b57cec5SDimitry Andric 17210b57cec5SDimitry Andric // Use CUDA call preference as a tiebreaker. 17220b57cec5SDimitry Andric return CUDAPref > Other.CUDAPref; 17230b57cec5SDimitry Andric } 17240b57cec5SDimitry Andric 17250b57cec5SDimitry Andric DeclAccessPair Found; 17260b57cec5SDimitry Andric FunctionDecl *FD; 17270b57cec5SDimitry Andric bool Destroying, HasSizeT, HasAlignValT; 17280b57cec5SDimitry Andric Sema::CUDAFunctionPreference CUDAPref; 17290b57cec5SDimitry Andric }; 17300b57cec5SDimitry Andric } 17310b57cec5SDimitry Andric 17320b57cec5SDimitry Andric /// Determine whether a type has new-extended alignment. This may be called when 17330b57cec5SDimitry Andric /// the type is incomplete (for a delete-expression with an incomplete pointee 17340b57cec5SDimitry Andric /// type), in which case it will conservatively return false if the alignment is 17350b57cec5SDimitry Andric /// not known. 17360b57cec5SDimitry Andric static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { 17370b57cec5SDimitry Andric return S.getLangOpts().AlignedAllocation && 17380b57cec5SDimitry Andric S.getASTContext().getTypeAlignIfKnown(AllocType) > 17390b57cec5SDimitry Andric S.getASTContext().getTargetInfo().getNewAlign(); 17400b57cec5SDimitry Andric } 17410b57cec5SDimitry Andric 17420b57cec5SDimitry Andric /// Select the correct "usual" deallocation function to use from a selection of 17430b57cec5SDimitry Andric /// deallocation functions (either global or class-scope). 17440b57cec5SDimitry Andric static UsualDeallocFnInfo resolveDeallocationOverload( 17450b57cec5SDimitry Andric Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 17460b57cec5SDimitry Andric llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { 17470b57cec5SDimitry Andric UsualDeallocFnInfo Best; 17480b57cec5SDimitry Andric 17490b57cec5SDimitry Andric for (auto I = R.begin(), E = R.end(); I != E; ++I) { 17500b57cec5SDimitry Andric UsualDeallocFnInfo Info(S, I.getPair()); 17510b57cec5SDimitry Andric if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || 17520b57cec5SDimitry Andric Info.CUDAPref == Sema::CFP_Never) 17530b57cec5SDimitry Andric continue; 17540b57cec5SDimitry Andric 17550b57cec5SDimitry Andric if (!Best) { 17560b57cec5SDimitry Andric Best = Info; 17570b57cec5SDimitry Andric if (BestFns) 17580b57cec5SDimitry Andric BestFns->push_back(Info); 17590b57cec5SDimitry Andric continue; 17600b57cec5SDimitry Andric } 17610b57cec5SDimitry Andric 17620b57cec5SDimitry Andric if (Best.isBetterThan(Info, WantSize, WantAlign)) 17630b57cec5SDimitry Andric continue; 17640b57cec5SDimitry Andric 17650b57cec5SDimitry Andric // If more than one preferred function is found, all non-preferred 17660b57cec5SDimitry Andric // functions are eliminated from further consideration. 17670b57cec5SDimitry Andric if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) 17680b57cec5SDimitry Andric BestFns->clear(); 17690b57cec5SDimitry Andric 17700b57cec5SDimitry Andric Best = Info; 17710b57cec5SDimitry Andric if (BestFns) 17720b57cec5SDimitry Andric BestFns->push_back(Info); 17730b57cec5SDimitry Andric } 17740b57cec5SDimitry Andric 17750b57cec5SDimitry Andric return Best; 17760b57cec5SDimitry Andric } 17770b57cec5SDimitry Andric 17780b57cec5SDimitry Andric /// Determine whether a given type is a class for which 'delete[]' would call 17790b57cec5SDimitry Andric /// a member 'operator delete[]' with a 'size_t' parameter. This implies that 17800b57cec5SDimitry Andric /// we need to store the array size (even if the type is 17810b57cec5SDimitry Andric /// trivially-destructible). 17820b57cec5SDimitry Andric static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 17830b57cec5SDimitry Andric QualType allocType) { 17840b57cec5SDimitry Andric const RecordType *record = 17850b57cec5SDimitry Andric allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 17860b57cec5SDimitry Andric if (!record) return false; 17870b57cec5SDimitry Andric 17880b57cec5SDimitry Andric // Try to find an operator delete[] in class scope. 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric DeclarationName deleteName = 17910b57cec5SDimitry Andric S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 17920b57cec5SDimitry Andric LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 17930b57cec5SDimitry Andric S.LookupQualifiedName(ops, record->getDecl()); 17940b57cec5SDimitry Andric 17950b57cec5SDimitry Andric // We're just doing this for information. 17960b57cec5SDimitry Andric ops.suppressDiagnostics(); 17970b57cec5SDimitry Andric 17980b57cec5SDimitry Andric // Very likely: there's no operator delete[]. 17990b57cec5SDimitry Andric if (ops.empty()) return false; 18000b57cec5SDimitry Andric 18010b57cec5SDimitry Andric // If it's ambiguous, it should be illegal to call operator delete[] 18020b57cec5SDimitry Andric // on this thing, so it doesn't matter if we allocate extra space or not. 18030b57cec5SDimitry Andric if (ops.isAmbiguous()) return false; 18040b57cec5SDimitry Andric 18050b57cec5SDimitry Andric // C++17 [expr.delete]p10: 18060b57cec5SDimitry Andric // If the deallocation functions have class scope, the one without a 18070b57cec5SDimitry Andric // parameter of type std::size_t is selected. 18080b57cec5SDimitry Andric auto Best = resolveDeallocationOverload( 18090b57cec5SDimitry Andric S, ops, /*WantSize*/false, 18100b57cec5SDimitry Andric /*WantAlign*/hasNewExtendedAlignment(S, allocType)); 18110b57cec5SDimitry Andric return Best && Best.HasSizeT; 18120b57cec5SDimitry Andric } 18130b57cec5SDimitry Andric 18140b57cec5SDimitry Andric /// Parsed a C++ 'new' expression (C++ 5.3.4). 18150b57cec5SDimitry Andric /// 18160b57cec5SDimitry Andric /// E.g.: 18170b57cec5SDimitry Andric /// @code new (memory) int[size][4] @endcode 18180b57cec5SDimitry Andric /// or 18190b57cec5SDimitry Andric /// @code ::new Foo(23, "hello") @endcode 18200b57cec5SDimitry Andric /// 18210b57cec5SDimitry Andric /// \param StartLoc The first location of the expression. 18220b57cec5SDimitry Andric /// \param UseGlobal True if 'new' was prefixed with '::'. 18230b57cec5SDimitry Andric /// \param PlacementLParen Opening paren of the placement arguments. 18240b57cec5SDimitry Andric /// \param PlacementArgs Placement new arguments. 18250b57cec5SDimitry Andric /// \param PlacementRParen Closing paren of the placement arguments. 18260b57cec5SDimitry Andric /// \param TypeIdParens If the type is in parens, the source range. 18270b57cec5SDimitry Andric /// \param D The type to be allocated, as well as array dimensions. 18280b57cec5SDimitry Andric /// \param Initializer The initializing expression or initializer-list, or null 18290b57cec5SDimitry Andric /// if there is none. 18300b57cec5SDimitry Andric ExprResult 18310b57cec5SDimitry Andric Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 18320b57cec5SDimitry Andric SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 18330b57cec5SDimitry Andric SourceLocation PlacementRParen, SourceRange TypeIdParens, 18340b57cec5SDimitry Andric Declarator &D, Expr *Initializer) { 18350b57cec5SDimitry Andric Optional<Expr *> ArraySize; 18360b57cec5SDimitry Andric // If the specified type is an array, unwrap it and save the expression. 18370b57cec5SDimitry Andric if (D.getNumTypeObjects() > 0 && 18380b57cec5SDimitry Andric D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 18390b57cec5SDimitry Andric DeclaratorChunk &Chunk = D.getTypeObject(0); 18400b57cec5SDimitry Andric if (D.getDeclSpec().hasAutoTypeSpec()) 18410b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 18420b57cec5SDimitry Andric << D.getSourceRange()); 18430b57cec5SDimitry Andric if (Chunk.Arr.hasStatic) 18440b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 18450b57cec5SDimitry Andric << D.getSourceRange()); 18460b57cec5SDimitry Andric if (!Chunk.Arr.NumElts && !Initializer) 18470b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 18480b57cec5SDimitry Andric << D.getSourceRange()); 18490b57cec5SDimitry Andric 18500b57cec5SDimitry Andric ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 18510b57cec5SDimitry Andric D.DropFirstTypeObject(); 18520b57cec5SDimitry Andric } 18530b57cec5SDimitry Andric 18540b57cec5SDimitry Andric // Every dimension shall be of constant size. 18550b57cec5SDimitry Andric if (ArraySize) { 18560b57cec5SDimitry Andric for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 18570b57cec5SDimitry Andric if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 18580b57cec5SDimitry Andric break; 18590b57cec5SDimitry Andric 18600b57cec5SDimitry Andric DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 18610b57cec5SDimitry Andric if (Expr *NumElts = (Expr *)Array.NumElts) { 18620b57cec5SDimitry Andric if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 1863e8d8bef9SDimitry Andric // FIXME: GCC permits constant folding here. We should either do so consistently 1864e8d8bef9SDimitry Andric // or not do so at all, rather than changing behavior in C++14 onwards. 18650b57cec5SDimitry Andric if (getLangOpts().CPlusPlus14) { 18660b57cec5SDimitry Andric // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 18670b57cec5SDimitry Andric // shall be a converted constant expression (5.19) of type std::size_t 18680b57cec5SDimitry Andric // and shall evaluate to a strictly positive value. 1869e8d8bef9SDimitry Andric llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); 18700b57cec5SDimitry Andric Array.NumElts 18710b57cec5SDimitry Andric = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 1872e8d8bef9SDimitry Andric CCEK_ArrayBound) 18730b57cec5SDimitry Andric .get(); 18740b57cec5SDimitry Andric } else { 1875e8d8bef9SDimitry Andric Array.NumElts = 1876e8d8bef9SDimitry Andric VerifyIntegerConstantExpression( 1877e8d8bef9SDimitry Andric NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) 18780b57cec5SDimitry Andric .get(); 18790b57cec5SDimitry Andric } 18800b57cec5SDimitry Andric if (!Array.NumElts) 18810b57cec5SDimitry Andric return ExprError(); 18820b57cec5SDimitry Andric } 18830b57cec5SDimitry Andric } 18840b57cec5SDimitry Andric } 18850b57cec5SDimitry Andric } 18860b57cec5SDimitry Andric 18870b57cec5SDimitry Andric TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); 18880b57cec5SDimitry Andric QualType AllocType = TInfo->getType(); 18890b57cec5SDimitry Andric if (D.isInvalidType()) 18900b57cec5SDimitry Andric return ExprError(); 18910b57cec5SDimitry Andric 18920b57cec5SDimitry Andric SourceRange DirectInitRange; 18930b57cec5SDimitry Andric if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 18940b57cec5SDimitry Andric DirectInitRange = List->getSourceRange(); 18950b57cec5SDimitry Andric 18960b57cec5SDimitry Andric return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, 18970b57cec5SDimitry Andric PlacementLParen, PlacementArgs, PlacementRParen, 18980b57cec5SDimitry Andric TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, 18990b57cec5SDimitry Andric Initializer); 19000b57cec5SDimitry Andric } 19010b57cec5SDimitry Andric 19020b57cec5SDimitry Andric static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 19030b57cec5SDimitry Andric Expr *Init) { 19040b57cec5SDimitry Andric if (!Init) 19050b57cec5SDimitry Andric return true; 19060b57cec5SDimitry Andric if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 19070b57cec5SDimitry Andric return PLE->getNumExprs() == 0; 19080b57cec5SDimitry Andric if (isa<ImplicitValueInitExpr>(Init)) 19090b57cec5SDimitry Andric return true; 19100b57cec5SDimitry Andric else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 19110b57cec5SDimitry Andric return !CCE->isListInitialization() && 19120b57cec5SDimitry Andric CCE->getConstructor()->isDefaultConstructor(); 19130b57cec5SDimitry Andric else if (Style == CXXNewExpr::ListInit) { 19140b57cec5SDimitry Andric assert(isa<InitListExpr>(Init) && 19150b57cec5SDimitry Andric "Shouldn't create list CXXConstructExprs for arrays."); 19160b57cec5SDimitry Andric return true; 19170b57cec5SDimitry Andric } 19180b57cec5SDimitry Andric return false; 19190b57cec5SDimitry Andric } 19200b57cec5SDimitry Andric 19210b57cec5SDimitry Andric bool 19220b57cec5SDimitry Andric Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { 19230b57cec5SDimitry Andric if (!getLangOpts().AlignedAllocationUnavailable) 19240b57cec5SDimitry Andric return false; 19250b57cec5SDimitry Andric if (FD.isDefined()) 19260b57cec5SDimitry Andric return false; 19275ffd83dbSDimitry Andric Optional<unsigned> AlignmentParam; 19285ffd83dbSDimitry Andric if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && 192981ad6265SDimitry Andric AlignmentParam) 19300b57cec5SDimitry Andric return true; 19310b57cec5SDimitry Andric return false; 19320b57cec5SDimitry Andric } 19330b57cec5SDimitry Andric 19340b57cec5SDimitry Andric // Emit a diagnostic if an aligned allocation/deallocation function that is not 19350b57cec5SDimitry Andric // implemented in the standard library is selected. 19360b57cec5SDimitry Andric void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 19370b57cec5SDimitry Andric SourceLocation Loc) { 19380b57cec5SDimitry Andric if (isUnavailableAlignedAllocationFunction(FD)) { 19390b57cec5SDimitry Andric const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 19400b57cec5SDimitry Andric StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( 19410b57cec5SDimitry Andric getASTContext().getTargetInfo().getPlatformName()); 1942e8d8bef9SDimitry Andric VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); 19430b57cec5SDimitry Andric 19440b57cec5SDimitry Andric OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); 19450b57cec5SDimitry Andric bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; 19460b57cec5SDimitry Andric Diag(Loc, diag::err_aligned_allocation_unavailable) 19470b57cec5SDimitry Andric << IsDelete << FD.getType().getAsString() << OSName 1948e8d8bef9SDimitry Andric << OSVersion.getAsString() << OSVersion.empty(); 19490b57cec5SDimitry Andric Diag(Loc, diag::note_silence_aligned_allocation_unavailable); 19500b57cec5SDimitry Andric } 19510b57cec5SDimitry Andric } 19520b57cec5SDimitry Andric 19530b57cec5SDimitry Andric ExprResult 19540b57cec5SDimitry Andric Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 19550b57cec5SDimitry Andric SourceLocation PlacementLParen, 19560b57cec5SDimitry Andric MultiExprArg PlacementArgs, 19570b57cec5SDimitry Andric SourceLocation PlacementRParen, 19580b57cec5SDimitry Andric SourceRange TypeIdParens, 19590b57cec5SDimitry Andric QualType AllocType, 19600b57cec5SDimitry Andric TypeSourceInfo *AllocTypeInfo, 19610b57cec5SDimitry Andric Optional<Expr *> ArraySize, 19620b57cec5SDimitry Andric SourceRange DirectInitRange, 19630b57cec5SDimitry Andric Expr *Initializer) { 19640b57cec5SDimitry Andric SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 19650b57cec5SDimitry Andric SourceLocation StartLoc = Range.getBegin(); 19660b57cec5SDimitry Andric 19670b57cec5SDimitry Andric CXXNewExpr::InitializationStyle initStyle; 19680b57cec5SDimitry Andric if (DirectInitRange.isValid()) { 19690b57cec5SDimitry Andric assert(Initializer && "Have parens but no initializer."); 19700b57cec5SDimitry Andric initStyle = CXXNewExpr::CallInit; 19710b57cec5SDimitry Andric } else if (Initializer && isa<InitListExpr>(Initializer)) 19720b57cec5SDimitry Andric initStyle = CXXNewExpr::ListInit; 19730b57cec5SDimitry Andric else { 19740b57cec5SDimitry Andric assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 19750b57cec5SDimitry Andric isa<CXXConstructExpr>(Initializer)) && 19760b57cec5SDimitry Andric "Initializer expression that cannot have been implicitly created."); 19770b57cec5SDimitry Andric initStyle = CXXNewExpr::NoInit; 19780b57cec5SDimitry Andric } 19790b57cec5SDimitry Andric 198081ad6265SDimitry Andric MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0); 19810b57cec5SDimitry Andric if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 19820b57cec5SDimitry Andric assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init"); 198381ad6265SDimitry Andric Exprs = MultiExprArg(List->getExprs(), List->getNumExprs()); 19840b57cec5SDimitry Andric } 19850b57cec5SDimitry Andric 19860b57cec5SDimitry Andric // C++11 [expr.new]p15: 19870b57cec5SDimitry Andric // A new-expression that creates an object of type T initializes that 19880b57cec5SDimitry Andric // object as follows: 19890b57cec5SDimitry Andric InitializationKind Kind 19900b57cec5SDimitry Andric // - If the new-initializer is omitted, the object is default- 19910b57cec5SDimitry Andric // initialized (8.5); if no initialization is performed, 19920b57cec5SDimitry Andric // the object has indeterminate value 19930b57cec5SDimitry Andric = initStyle == CXXNewExpr::NoInit 19940b57cec5SDimitry Andric ? InitializationKind::CreateDefault(TypeRange.getBegin()) 19950b57cec5SDimitry Andric // - Otherwise, the new-initializer is interpreted according to 19960b57cec5SDimitry Andric // the 19970b57cec5SDimitry Andric // initialization rules of 8.5 for direct-initialization. 19980b57cec5SDimitry Andric : initStyle == CXXNewExpr::ListInit 19990b57cec5SDimitry Andric ? InitializationKind::CreateDirectList( 20000b57cec5SDimitry Andric TypeRange.getBegin(), Initializer->getBeginLoc(), 20010b57cec5SDimitry Andric Initializer->getEndLoc()) 20020b57cec5SDimitry Andric : InitializationKind::CreateDirect(TypeRange.getBegin(), 20030b57cec5SDimitry Andric DirectInitRange.getBegin(), 20040b57cec5SDimitry Andric DirectInitRange.getEnd()); 20050b57cec5SDimitry Andric 20060b57cec5SDimitry Andric // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. 20070b57cec5SDimitry Andric auto *Deduced = AllocType->getContainedDeducedType(); 20080b57cec5SDimitry Andric if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 20090b57cec5SDimitry Andric if (ArraySize) 20100b57cec5SDimitry Andric return ExprError( 2011349cc55cSDimitry Andric Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), 20120b57cec5SDimitry Andric diag::err_deduced_class_template_compound_type) 20130b57cec5SDimitry Andric << /*array*/ 2 2014349cc55cSDimitry Andric << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); 20150b57cec5SDimitry Andric 20160b57cec5SDimitry Andric InitializedEntity Entity 20170b57cec5SDimitry Andric = InitializedEntity::InitializeNew(StartLoc, AllocType); 20180b57cec5SDimitry Andric AllocType = DeduceTemplateSpecializationFromInitializer( 201981ad6265SDimitry Andric AllocTypeInfo, Entity, Kind, Exprs); 20200b57cec5SDimitry Andric if (AllocType.isNull()) 20210b57cec5SDimitry Andric return ExprError(); 20220b57cec5SDimitry Andric } else if (Deduced) { 202381ad6265SDimitry Andric MultiExprArg Inits = Exprs; 20240b57cec5SDimitry Andric bool Braced = (initStyle == CXXNewExpr::ListInit); 202581ad6265SDimitry Andric if (Braced) { 202681ad6265SDimitry Andric auto *ILE = cast<InitListExpr>(Exprs[0]); 202781ad6265SDimitry Andric Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); 20280b57cec5SDimitry Andric } 20290b57cec5SDimitry Andric 203081ad6265SDimitry Andric if (initStyle == CXXNewExpr::NoInit || Inits.empty()) 20310b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 20320b57cec5SDimitry Andric << AllocType << TypeRange); 203381ad6265SDimitry Andric if (Inits.size() > 1) { 20340b57cec5SDimitry Andric Expr *FirstBad = Inits[1]; 20350b57cec5SDimitry Andric return ExprError(Diag(FirstBad->getBeginLoc(), 20360b57cec5SDimitry Andric diag::err_auto_new_ctor_multiple_expressions) 20370b57cec5SDimitry Andric << AllocType << TypeRange); 20380b57cec5SDimitry Andric } 20390b57cec5SDimitry Andric if (Braced && !getLangOpts().CPlusPlus17) 20400b57cec5SDimitry Andric Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) 20410b57cec5SDimitry Andric << AllocType << TypeRange; 20420b57cec5SDimitry Andric Expr *Deduce = Inits[0]; 204381ad6265SDimitry Andric if (isa<InitListExpr>(Deduce)) 204481ad6265SDimitry Andric return ExprError( 204581ad6265SDimitry Andric Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) 204681ad6265SDimitry Andric << Braced << AllocType << TypeRange); 20470b57cec5SDimitry Andric QualType DeducedType; 20480b57cec5SDimitry Andric if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 20490b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 20500b57cec5SDimitry Andric << AllocType << Deduce->getType() 20510b57cec5SDimitry Andric << TypeRange << Deduce->getSourceRange()); 20520b57cec5SDimitry Andric if (DeducedType.isNull()) 20530b57cec5SDimitry Andric return ExprError(); 20540b57cec5SDimitry Andric AllocType = DeducedType; 20550b57cec5SDimitry Andric } 20560b57cec5SDimitry Andric 20570b57cec5SDimitry Andric // Per C++0x [expr.new]p5, the type being constructed may be a 20580b57cec5SDimitry Andric // typedef of an array type. 20590b57cec5SDimitry Andric if (!ArraySize) { 20600b57cec5SDimitry Andric if (const ConstantArrayType *Array 20610b57cec5SDimitry Andric = Context.getAsConstantArrayType(AllocType)) { 20620b57cec5SDimitry Andric ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 20630b57cec5SDimitry Andric Context.getSizeType(), 20640b57cec5SDimitry Andric TypeRange.getEnd()); 20650b57cec5SDimitry Andric AllocType = Array->getElementType(); 20660b57cec5SDimitry Andric } 20670b57cec5SDimitry Andric } 20680b57cec5SDimitry Andric 20690b57cec5SDimitry Andric if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 20700b57cec5SDimitry Andric return ExprError(); 20710b57cec5SDimitry Andric 20720b57cec5SDimitry Andric // In ARC, infer 'retaining' for the allocated 20730b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 20740b57cec5SDimitry Andric AllocType.getObjCLifetime() == Qualifiers::OCL_None && 20750b57cec5SDimitry Andric AllocType->isObjCLifetimeType()) { 20760b57cec5SDimitry Andric AllocType = Context.getLifetimeQualifiedType(AllocType, 20770b57cec5SDimitry Andric AllocType->getObjCARCImplicitLifetime()); 20780b57cec5SDimitry Andric } 20790b57cec5SDimitry Andric 20800b57cec5SDimitry Andric QualType ResultType = Context.getPointerType(AllocType); 20810b57cec5SDimitry Andric 20820b57cec5SDimitry Andric if (ArraySize && *ArraySize && 20830b57cec5SDimitry Andric (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { 20840b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(*ArraySize); 20850b57cec5SDimitry Andric if (result.isInvalid()) return ExprError(); 20860b57cec5SDimitry Andric ArraySize = result.get(); 20870b57cec5SDimitry Andric } 20880b57cec5SDimitry Andric // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 20890b57cec5SDimitry Andric // integral or enumeration type with a non-negative value." 20900b57cec5SDimitry Andric // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 20910b57cec5SDimitry Andric // enumeration type, or a class type for which a single non-explicit 20920b57cec5SDimitry Andric // conversion function to integral or unscoped enumeration type exists. 20930b57cec5SDimitry Andric // C++1y [expr.new]p6: The expression [...] is implicitly converted to 20940b57cec5SDimitry Andric // std::size_t. 20950b57cec5SDimitry Andric llvm::Optional<uint64_t> KnownArraySize; 20960b57cec5SDimitry Andric if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { 20970b57cec5SDimitry Andric ExprResult ConvertedSize; 20980b57cec5SDimitry Andric if (getLangOpts().CPlusPlus14) { 20990b57cec5SDimitry Andric assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); 21000b57cec5SDimitry Andric 21010b57cec5SDimitry Andric ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), 21020b57cec5SDimitry Andric AA_Converting); 21030b57cec5SDimitry Andric 21040b57cec5SDimitry Andric if (!ConvertedSize.isInvalid() && 21050b57cec5SDimitry Andric (*ArraySize)->getType()->getAs<RecordType>()) 21060b57cec5SDimitry Andric // Diagnose the compatibility of this conversion. 21070b57cec5SDimitry Andric Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 21080b57cec5SDimitry Andric << (*ArraySize)->getType() << 0 << "'size_t'"; 21090b57cec5SDimitry Andric } else { 21100b57cec5SDimitry Andric class SizeConvertDiagnoser : public ICEConvertDiagnoser { 21110b57cec5SDimitry Andric protected: 21120b57cec5SDimitry Andric Expr *ArraySize; 21130b57cec5SDimitry Andric 21140b57cec5SDimitry Andric public: 21150b57cec5SDimitry Andric SizeConvertDiagnoser(Expr *ArraySize) 21160b57cec5SDimitry Andric : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 21170b57cec5SDimitry Andric ArraySize(ArraySize) {} 21180b57cec5SDimitry Andric 21190b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 21200b57cec5SDimitry Andric QualType T) override { 21210b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_not_integral) 21220b57cec5SDimitry Andric << S.getLangOpts().CPlusPlus11 << T; 21230b57cec5SDimitry Andric } 21240b57cec5SDimitry Andric 21250b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseIncomplete( 21260b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T) override { 21270b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_incomplete_type) 21280b57cec5SDimitry Andric << T << ArraySize->getSourceRange(); 21290b57cec5SDimitry Andric } 21300b57cec5SDimitry Andric 21310b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseExplicitConv( 21320b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 21330b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 21340b57cec5SDimitry Andric } 21350b57cec5SDimitry Andric 21360b57cec5SDimitry Andric SemaDiagnosticBuilder noteExplicitConv( 21370b57cec5SDimitry Andric Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 21380b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 21390b57cec5SDimitry Andric << ConvTy->isEnumeralType() << ConvTy; 21400b57cec5SDimitry Andric } 21410b57cec5SDimitry Andric 21420b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseAmbiguous( 21430b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T) override { 21440b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 21450b57cec5SDimitry Andric } 21460b57cec5SDimitry Andric 21470b57cec5SDimitry Andric SemaDiagnosticBuilder noteAmbiguous( 21480b57cec5SDimitry Andric Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 21490b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 21500b57cec5SDimitry Andric << ConvTy->isEnumeralType() << ConvTy; 21510b57cec5SDimitry Andric } 21520b57cec5SDimitry Andric 21530b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 21540b57cec5SDimitry Andric QualType T, 21550b57cec5SDimitry Andric QualType ConvTy) override { 21560b57cec5SDimitry Andric return S.Diag(Loc, 21570b57cec5SDimitry Andric S.getLangOpts().CPlusPlus11 21580b57cec5SDimitry Andric ? diag::warn_cxx98_compat_array_size_conversion 21590b57cec5SDimitry Andric : diag::ext_array_size_conversion) 21600b57cec5SDimitry Andric << T << ConvTy->isEnumeralType() << ConvTy; 21610b57cec5SDimitry Andric } 21620b57cec5SDimitry Andric } SizeDiagnoser(*ArraySize); 21630b57cec5SDimitry Andric 21640b57cec5SDimitry Andric ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, 21650b57cec5SDimitry Andric SizeDiagnoser); 21660b57cec5SDimitry Andric } 21670b57cec5SDimitry Andric if (ConvertedSize.isInvalid()) 21680b57cec5SDimitry Andric return ExprError(); 21690b57cec5SDimitry Andric 21700b57cec5SDimitry Andric ArraySize = ConvertedSize.get(); 21710b57cec5SDimitry Andric QualType SizeType = (*ArraySize)->getType(); 21720b57cec5SDimitry Andric 21730b57cec5SDimitry Andric if (!SizeType->isIntegralOrUnscopedEnumerationType()) 21740b57cec5SDimitry Andric return ExprError(); 21750b57cec5SDimitry Andric 21760b57cec5SDimitry Andric // C++98 [expr.new]p7: 21770b57cec5SDimitry Andric // The expression in a direct-new-declarator shall have integral type 21780b57cec5SDimitry Andric // with a non-negative value. 21790b57cec5SDimitry Andric // 21800b57cec5SDimitry Andric // Let's see if this is a constant < 0. If so, we reject it out of hand, 21810b57cec5SDimitry Andric // per CWG1464. Otherwise, if it's not a constant, we must have an 21820b57cec5SDimitry Andric // unparenthesized array type. 2183349cc55cSDimitry Andric 21840b57cec5SDimitry Andric // We've already performed any required implicit conversion to integer or 21850b57cec5SDimitry Andric // unscoped enumeration type. 21860b57cec5SDimitry Andric // FIXME: Per CWG1464, we are required to check the value prior to 21870b57cec5SDimitry Andric // converting to size_t. This will never find a negative array size in 21880b57cec5SDimitry Andric // C++14 onwards, because Value is always unsigned here! 2189e8d8bef9SDimitry Andric if (Optional<llvm::APSInt> Value = 2190e8d8bef9SDimitry Andric (*ArraySize)->getIntegerConstantExpr(Context)) { 2191e8d8bef9SDimitry Andric if (Value->isSigned() && Value->isNegative()) { 21920b57cec5SDimitry Andric return ExprError(Diag((*ArraySize)->getBeginLoc(), 21930b57cec5SDimitry Andric diag::err_typecheck_negative_array_size) 21940b57cec5SDimitry Andric << (*ArraySize)->getSourceRange()); 21950b57cec5SDimitry Andric } 21960b57cec5SDimitry Andric 21970b57cec5SDimitry Andric if (!AllocType->isDependentType()) { 2198349cc55cSDimitry Andric unsigned ActiveSizeBits = 2199349cc55cSDimitry Andric ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value); 22000b57cec5SDimitry Andric if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 22010b57cec5SDimitry Andric return ExprError( 22020b57cec5SDimitry Andric Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) 2203fe6060f1SDimitry Andric << toString(*Value, 10) << (*ArraySize)->getSourceRange()); 22040b57cec5SDimitry Andric } 22050b57cec5SDimitry Andric 2206e8d8bef9SDimitry Andric KnownArraySize = Value->getZExtValue(); 22070b57cec5SDimitry Andric } else if (TypeIdParens.isValid()) { 22080b57cec5SDimitry Andric // Can't have dynamic array size when the type-id is in parentheses. 22090b57cec5SDimitry Andric Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) 22100b57cec5SDimitry Andric << (*ArraySize)->getSourceRange() 22110b57cec5SDimitry Andric << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 22120b57cec5SDimitry Andric << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 22130b57cec5SDimitry Andric 22140b57cec5SDimitry Andric TypeIdParens = SourceRange(); 22150b57cec5SDimitry Andric } 22160b57cec5SDimitry Andric 22170b57cec5SDimitry Andric // Note that we do *not* convert the argument in any way. It can 22180b57cec5SDimitry Andric // be signed, larger than size_t, whatever. 22190b57cec5SDimitry Andric } 22200b57cec5SDimitry Andric 22210b57cec5SDimitry Andric FunctionDecl *OperatorNew = nullptr; 22220b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 22230b57cec5SDimitry Andric unsigned Alignment = 22240b57cec5SDimitry Andric AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 22250b57cec5SDimitry Andric unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 22260b57cec5SDimitry Andric bool PassAlignment = getLangOpts().AlignedAllocation && 22270b57cec5SDimitry Andric Alignment > NewAlignment; 22280b57cec5SDimitry Andric 22290b57cec5SDimitry Andric AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; 22300b57cec5SDimitry Andric if (!AllocType->isDependentType() && 22310b57cec5SDimitry Andric !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 22320b57cec5SDimitry Andric FindAllocationFunctions( 22330b57cec5SDimitry Andric StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, 223481ad6265SDimitry Andric AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs, 22350b57cec5SDimitry Andric OperatorNew, OperatorDelete)) 22360b57cec5SDimitry Andric return ExprError(); 22370b57cec5SDimitry Andric 22380b57cec5SDimitry Andric // If this is an array allocation, compute whether the usual array 22390b57cec5SDimitry Andric // deallocation function for the type has a size_t parameter. 22400b57cec5SDimitry Andric bool UsualArrayDeleteWantsSize = false; 22410b57cec5SDimitry Andric if (ArraySize && !AllocType->isDependentType()) 22420b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 22430b57cec5SDimitry Andric doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 22440b57cec5SDimitry Andric 22450b57cec5SDimitry Andric SmallVector<Expr *, 8> AllPlaceArgs; 22460b57cec5SDimitry Andric if (OperatorNew) { 22475ffd83dbSDimitry Andric auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 22480b57cec5SDimitry Andric VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 22490b57cec5SDimitry Andric : VariadicDoesNotApply; 22500b57cec5SDimitry Andric 22510b57cec5SDimitry Andric // We've already converted the placement args, just fill in any default 22520b57cec5SDimitry Andric // arguments. Skip the first parameter because we don't have a corresponding 22530b57cec5SDimitry Andric // argument. Skip the second parameter too if we're passing in the 22540b57cec5SDimitry Andric // alignment; we've already filled it in. 22555ffd83dbSDimitry Andric unsigned NumImplicitArgs = PassAlignment ? 2 : 1; 22560b57cec5SDimitry Andric if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 22575ffd83dbSDimitry Andric NumImplicitArgs, PlacementArgs, AllPlaceArgs, 22585ffd83dbSDimitry Andric CallType)) 22590b57cec5SDimitry Andric return ExprError(); 22600b57cec5SDimitry Andric 22610b57cec5SDimitry Andric if (!AllPlaceArgs.empty()) 22620b57cec5SDimitry Andric PlacementArgs = AllPlaceArgs; 22630b57cec5SDimitry Andric 22645ffd83dbSDimitry Andric // We would like to perform some checking on the given `operator new` call, 22655ffd83dbSDimitry Andric // but the PlacementArgs does not contain the implicit arguments, 22665ffd83dbSDimitry Andric // namely allocation size and maybe allocation alignment, 22675ffd83dbSDimitry Andric // so we need to conjure them. 22680b57cec5SDimitry Andric 22695ffd83dbSDimitry Andric QualType SizeTy = Context.getSizeType(); 22705ffd83dbSDimitry Andric unsigned SizeTyWidth = Context.getTypeSize(SizeTy); 22715ffd83dbSDimitry Andric 22725ffd83dbSDimitry Andric llvm::APInt SingleEltSize( 22735ffd83dbSDimitry Andric SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); 22745ffd83dbSDimitry Andric 22755ffd83dbSDimitry Andric // How many bytes do we want to allocate here? 22765ffd83dbSDimitry Andric llvm::Optional<llvm::APInt> AllocationSize; 227781ad6265SDimitry Andric if (!ArraySize && !AllocType->isDependentType()) { 22785ffd83dbSDimitry Andric // For non-array operator new, we only want to allocate one element. 22795ffd83dbSDimitry Andric AllocationSize = SingleEltSize; 228081ad6265SDimitry Andric } else if (KnownArraySize && !AllocType->isDependentType()) { 22815ffd83dbSDimitry Andric // For array operator new, only deal with static array size case. 22825ffd83dbSDimitry Andric bool Overflow; 22835ffd83dbSDimitry Andric AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) 22845ffd83dbSDimitry Andric .umul_ov(SingleEltSize, Overflow); 22855ffd83dbSDimitry Andric (void)Overflow; 22865ffd83dbSDimitry Andric assert( 22875ffd83dbSDimitry Andric !Overflow && 22885ffd83dbSDimitry Andric "Expected that all the overflows would have been handled already."); 22895ffd83dbSDimitry Andric } 22905ffd83dbSDimitry Andric 22915ffd83dbSDimitry Andric IntegerLiteral AllocationSizeLiteral( 229281ad6265SDimitry Andric Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)), 22935ffd83dbSDimitry Andric SizeTy, SourceLocation()); 22945ffd83dbSDimitry Andric // Otherwise, if we failed to constant-fold the allocation size, we'll 22955ffd83dbSDimitry Andric // just give up and pass-in something opaque, that isn't a null pointer. 2296fe6060f1SDimitry Andric OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue, 22975ffd83dbSDimitry Andric OK_Ordinary, /*SourceExpr=*/nullptr); 22985ffd83dbSDimitry Andric 22995ffd83dbSDimitry Andric // Let's synthesize the alignment argument in case we will need it. 23005ffd83dbSDimitry Andric // Since we *really* want to allocate these on stack, this is slightly ugly 23015ffd83dbSDimitry Andric // because there might not be a `std::align_val_t` type. 23025ffd83dbSDimitry Andric EnumDecl *StdAlignValT = getStdAlignValT(); 23035ffd83dbSDimitry Andric QualType AlignValT = 23045ffd83dbSDimitry Andric StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; 23055ffd83dbSDimitry Andric IntegerLiteral AlignmentLiteral( 23065ffd83dbSDimitry Andric Context, 23075ffd83dbSDimitry Andric llvm::APInt(Context.getTypeSize(SizeTy), 23085ffd83dbSDimitry Andric Alignment / Context.getCharWidth()), 23095ffd83dbSDimitry Andric SizeTy, SourceLocation()); 23105ffd83dbSDimitry Andric ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, 23115ffd83dbSDimitry Andric CK_IntegralCast, &AlignmentLiteral, 2312fe6060f1SDimitry Andric VK_PRValue, FPOptionsOverride()); 23135ffd83dbSDimitry Andric 23145ffd83dbSDimitry Andric // Adjust placement args by prepending conjured size and alignment exprs. 23155ffd83dbSDimitry Andric llvm::SmallVector<Expr *, 8> CallArgs; 23165ffd83dbSDimitry Andric CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); 231781ad6265SDimitry Andric CallArgs.emplace_back(AllocationSize 23185ffd83dbSDimitry Andric ? static_cast<Expr *>(&AllocationSizeLiteral) 23195ffd83dbSDimitry Andric : &OpaqueAllocationSize); 23205ffd83dbSDimitry Andric if (PassAlignment) 23215ffd83dbSDimitry Andric CallArgs.emplace_back(&DesiredAlignment); 23225ffd83dbSDimitry Andric CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end()); 23235ffd83dbSDimitry Andric 23245ffd83dbSDimitry Andric DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); 23255ffd83dbSDimitry Andric 23265ffd83dbSDimitry Andric checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, 23275ffd83dbSDimitry Andric /*IsMemberFunction=*/false, StartLoc, Range, CallType); 23280b57cec5SDimitry Andric 23290b57cec5SDimitry Andric // Warn if the type is over-aligned and is being allocated by (unaligned) 23300b57cec5SDimitry Andric // global operator new. 23310b57cec5SDimitry Andric if (PlacementArgs.empty() && !PassAlignment && 23320b57cec5SDimitry Andric (OperatorNew->isImplicit() || 23330b57cec5SDimitry Andric (OperatorNew->getBeginLoc().isValid() && 23340b57cec5SDimitry Andric getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { 23350b57cec5SDimitry Andric if (Alignment > NewAlignment) 23360b57cec5SDimitry Andric Diag(StartLoc, diag::warn_overaligned_type) 23370b57cec5SDimitry Andric << AllocType 23380b57cec5SDimitry Andric << unsigned(Alignment / Context.getCharWidth()) 23390b57cec5SDimitry Andric << unsigned(NewAlignment / Context.getCharWidth()); 23400b57cec5SDimitry Andric } 23410b57cec5SDimitry Andric } 23420b57cec5SDimitry Andric 23430b57cec5SDimitry Andric // Array 'new' can't have any initializers except empty parentheses. 23440b57cec5SDimitry Andric // Initializer lists are also allowed, in C++11. Rely on the parser for the 23450b57cec5SDimitry Andric // dialect distinction. 23460b57cec5SDimitry Andric if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { 234781ad6265SDimitry Andric SourceRange InitRange(Exprs.front()->getBeginLoc(), 234881ad6265SDimitry Andric Exprs.back()->getEndLoc()); 23490b57cec5SDimitry Andric Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 23500b57cec5SDimitry Andric return ExprError(); 23510b57cec5SDimitry Andric } 23520b57cec5SDimitry Andric 23530b57cec5SDimitry Andric // If we can perform the initialization, and we've not already done so, 23540b57cec5SDimitry Andric // do it now. 23550b57cec5SDimitry Andric if (!AllocType->isDependentType() && 235681ad6265SDimitry Andric !Expr::hasAnyTypeDependentArguments(Exprs)) { 23570b57cec5SDimitry Andric // The type we initialize is the complete type, including the array bound. 23580b57cec5SDimitry Andric QualType InitType; 23590b57cec5SDimitry Andric if (KnownArraySize) 23600b57cec5SDimitry Andric InitType = Context.getConstantArrayType( 2361a7dea167SDimitry Andric AllocType, 2362a7dea167SDimitry Andric llvm::APInt(Context.getTypeSize(Context.getSizeType()), 23630b57cec5SDimitry Andric *KnownArraySize), 2364a7dea167SDimitry Andric *ArraySize, ArrayType::Normal, 0); 23650b57cec5SDimitry Andric else if (ArraySize) 23660b57cec5SDimitry Andric InitType = 23670b57cec5SDimitry Andric Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); 23680b57cec5SDimitry Andric else 23690b57cec5SDimitry Andric InitType = AllocType; 23700b57cec5SDimitry Andric 23710b57cec5SDimitry Andric InitializedEntity Entity 23720b57cec5SDimitry Andric = InitializedEntity::InitializeNew(StartLoc, InitType); 237381ad6265SDimitry Andric InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 237481ad6265SDimitry Andric ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs); 23750b57cec5SDimitry Andric if (FullInit.isInvalid()) 23760b57cec5SDimitry Andric return ExprError(); 23770b57cec5SDimitry Andric 23780b57cec5SDimitry Andric // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 23790b57cec5SDimitry Andric // we don't want the initialized object to be destructed. 23800b57cec5SDimitry Andric // FIXME: We should not create these in the first place. 23810b57cec5SDimitry Andric if (CXXBindTemporaryExpr *Binder = 23820b57cec5SDimitry Andric dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 23830b57cec5SDimitry Andric FullInit = Binder->getSubExpr(); 23840b57cec5SDimitry Andric 23850b57cec5SDimitry Andric Initializer = FullInit.get(); 23860b57cec5SDimitry Andric 23870b57cec5SDimitry Andric // FIXME: If we have a KnownArraySize, check that the array bound of the 23880b57cec5SDimitry Andric // initializer is no greater than that constant value. 23890b57cec5SDimitry Andric 23900b57cec5SDimitry Andric if (ArraySize && !*ArraySize) { 23910b57cec5SDimitry Andric auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); 23920b57cec5SDimitry Andric if (CAT) { 23930b57cec5SDimitry Andric // FIXME: Track that the array size was inferred rather than explicitly 23940b57cec5SDimitry Andric // specified. 23950b57cec5SDimitry Andric ArraySize = IntegerLiteral::Create( 23960b57cec5SDimitry Andric Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); 23970b57cec5SDimitry Andric } else { 23980b57cec5SDimitry Andric Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) 23990b57cec5SDimitry Andric << Initializer->getSourceRange(); 24000b57cec5SDimitry Andric } 24010b57cec5SDimitry Andric } 24020b57cec5SDimitry Andric } 24030b57cec5SDimitry Andric 24040b57cec5SDimitry Andric // Mark the new and delete operators as referenced. 24050b57cec5SDimitry Andric if (OperatorNew) { 24060b57cec5SDimitry Andric if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 24070b57cec5SDimitry Andric return ExprError(); 24080b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorNew); 24090b57cec5SDimitry Andric } 24100b57cec5SDimitry Andric if (OperatorDelete) { 24110b57cec5SDimitry Andric if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 24120b57cec5SDimitry Andric return ExprError(); 24130b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorDelete); 24140b57cec5SDimitry Andric } 24150b57cec5SDimitry Andric 24160b57cec5SDimitry Andric return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, 24170b57cec5SDimitry Andric PassAlignment, UsualArrayDeleteWantsSize, 24180b57cec5SDimitry Andric PlacementArgs, TypeIdParens, ArraySize, initStyle, 24190b57cec5SDimitry Andric Initializer, ResultType, AllocTypeInfo, Range, 24200b57cec5SDimitry Andric DirectInitRange); 24210b57cec5SDimitry Andric } 24220b57cec5SDimitry Andric 24230b57cec5SDimitry Andric /// Checks that a type is suitable as the allocated type 24240b57cec5SDimitry Andric /// in a new-expression. 24250b57cec5SDimitry Andric bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 24260b57cec5SDimitry Andric SourceRange R) { 24270b57cec5SDimitry Andric // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 24280b57cec5SDimitry Andric // abstract class type or array thereof. 24290b57cec5SDimitry Andric if (AllocType->isFunctionType()) 24300b57cec5SDimitry Andric return Diag(Loc, diag::err_bad_new_type) 24310b57cec5SDimitry Andric << AllocType << 0 << R; 24320b57cec5SDimitry Andric else if (AllocType->isReferenceType()) 24330b57cec5SDimitry Andric return Diag(Loc, diag::err_bad_new_type) 24340b57cec5SDimitry Andric << AllocType << 1 << R; 24350b57cec5SDimitry Andric else if (!AllocType->isDependentType() && 24365ffd83dbSDimitry Andric RequireCompleteSizedType( 24375ffd83dbSDimitry Andric Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) 24380b57cec5SDimitry Andric return true; 24390b57cec5SDimitry Andric else if (RequireNonAbstractType(Loc, AllocType, 24400b57cec5SDimitry Andric diag::err_allocation_of_abstract_type)) 24410b57cec5SDimitry Andric return true; 24420b57cec5SDimitry Andric else if (AllocType->isVariablyModifiedType()) 24430b57cec5SDimitry Andric return Diag(Loc, diag::err_variably_modified_new_type) 24440b57cec5SDimitry Andric << AllocType; 24450b57cec5SDimitry Andric else if (AllocType.getAddressSpace() != LangAS::Default && 24460b57cec5SDimitry Andric !getLangOpts().OpenCLCPlusPlus) 24470b57cec5SDimitry Andric return Diag(Loc, diag::err_address_space_qualified_new) 24480b57cec5SDimitry Andric << AllocType.getUnqualifiedType() 24490b57cec5SDimitry Andric << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); 24500b57cec5SDimitry Andric else if (getLangOpts().ObjCAutoRefCount) { 24510b57cec5SDimitry Andric if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 24520b57cec5SDimitry Andric QualType BaseAllocType = Context.getBaseElementType(AT); 24530b57cec5SDimitry Andric if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 24540b57cec5SDimitry Andric BaseAllocType->isObjCLifetimeType()) 24550b57cec5SDimitry Andric return Diag(Loc, diag::err_arc_new_array_without_ownership) 24560b57cec5SDimitry Andric << BaseAllocType; 24570b57cec5SDimitry Andric } 24580b57cec5SDimitry Andric } 24590b57cec5SDimitry Andric 24600b57cec5SDimitry Andric return false; 24610b57cec5SDimitry Andric } 24620b57cec5SDimitry Andric 24630b57cec5SDimitry Andric static bool resolveAllocationOverload( 24640b57cec5SDimitry Andric Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, 24650b57cec5SDimitry Andric bool &PassAlignment, FunctionDecl *&Operator, 24660b57cec5SDimitry Andric OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { 24670b57cec5SDimitry Andric OverloadCandidateSet Candidates(R.getNameLoc(), 24680b57cec5SDimitry Andric OverloadCandidateSet::CSK_Normal); 24690b57cec5SDimitry Andric for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 24700b57cec5SDimitry Andric Alloc != AllocEnd; ++Alloc) { 24710b57cec5SDimitry Andric // Even member operator new/delete are implicitly treated as 24720b57cec5SDimitry Andric // static, so don't use AddMemberCandidate. 24730b57cec5SDimitry Andric NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 24740b57cec5SDimitry Andric 24750b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 24760b57cec5SDimitry Andric S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 24770b57cec5SDimitry Andric /*ExplicitTemplateArgs=*/nullptr, Args, 24780b57cec5SDimitry Andric Candidates, 24790b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 24800b57cec5SDimitry Andric continue; 24810b57cec5SDimitry Andric } 24820b57cec5SDimitry Andric 24830b57cec5SDimitry Andric FunctionDecl *Fn = cast<FunctionDecl>(D); 24840b57cec5SDimitry Andric S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 24850b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 24860b57cec5SDimitry Andric } 24870b57cec5SDimitry Andric 24880b57cec5SDimitry Andric // Do the resolution. 24890b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 24900b57cec5SDimitry Andric switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 24910b57cec5SDimitry Andric case OR_Success: { 24920b57cec5SDimitry Andric // Got one! 24930b57cec5SDimitry Andric FunctionDecl *FnDecl = Best->Function; 24940b57cec5SDimitry Andric if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 24950b57cec5SDimitry Andric Best->FoundDecl) == Sema::AR_inaccessible) 24960b57cec5SDimitry Andric return true; 24970b57cec5SDimitry Andric 24980b57cec5SDimitry Andric Operator = FnDecl; 24990b57cec5SDimitry Andric return false; 25000b57cec5SDimitry Andric } 25010b57cec5SDimitry Andric 25020b57cec5SDimitry Andric case OR_No_Viable_Function: 25030b57cec5SDimitry Andric // C++17 [expr.new]p13: 25040b57cec5SDimitry Andric // If no matching function is found and the allocated object type has 25050b57cec5SDimitry Andric // new-extended alignment, the alignment argument is removed from the 25060b57cec5SDimitry Andric // argument list, and overload resolution is performed again. 25070b57cec5SDimitry Andric if (PassAlignment) { 25080b57cec5SDimitry Andric PassAlignment = false; 25090b57cec5SDimitry Andric AlignArg = Args[1]; 25100b57cec5SDimitry Andric Args.erase(Args.begin() + 1); 25110b57cec5SDimitry Andric return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 25120b57cec5SDimitry Andric Operator, &Candidates, AlignArg, 25130b57cec5SDimitry Andric Diagnose); 25140b57cec5SDimitry Andric } 25150b57cec5SDimitry Andric 25160b57cec5SDimitry Andric // MSVC will fall back on trying to find a matching global operator new 25170b57cec5SDimitry Andric // if operator new[] cannot be found. Also, MSVC will leak by not 25180b57cec5SDimitry Andric // generating a call to operator delete or operator delete[], but we 25190b57cec5SDimitry Andric // will not replicate that bug. 25200b57cec5SDimitry Andric // FIXME: Find out how this interacts with the std::align_val_t fallback 25210b57cec5SDimitry Andric // once MSVC implements it. 25220b57cec5SDimitry Andric if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 25230b57cec5SDimitry Andric S.Context.getLangOpts().MSVCCompat) { 25240b57cec5SDimitry Andric R.clear(); 25250b57cec5SDimitry Andric R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 25260b57cec5SDimitry Andric S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 25270b57cec5SDimitry Andric // FIXME: This will give bad diagnostics pointing at the wrong functions. 25280b57cec5SDimitry Andric return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 25290b57cec5SDimitry Andric Operator, /*Candidates=*/nullptr, 25300b57cec5SDimitry Andric /*AlignArg=*/nullptr, Diagnose); 25310b57cec5SDimitry Andric } 25320b57cec5SDimitry Andric 25330b57cec5SDimitry Andric if (Diagnose) { 2534fe6060f1SDimitry Andric // If this is an allocation of the form 'new (p) X' for some object 2535fe6060f1SDimitry Andric // pointer p (or an expression that will decay to such a pointer), 2536fe6060f1SDimitry Andric // diagnose the missing inclusion of <new>. 2537fe6060f1SDimitry Andric if (!R.isClassLookup() && Args.size() == 2 && 2538fe6060f1SDimitry Andric (Args[1]->getType()->isObjectPointerType() || 2539fe6060f1SDimitry Andric Args[1]->getType()->isArrayType())) { 2540fe6060f1SDimitry Andric S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) 2541fe6060f1SDimitry Andric << R.getLookupName() << Range; 2542fe6060f1SDimitry Andric // Listing the candidates is unlikely to be useful; skip it. 2543fe6060f1SDimitry Andric return true; 2544fe6060f1SDimitry Andric } 25450b57cec5SDimitry Andric 2546fe6060f1SDimitry Andric // Finish checking all candidates before we note any. This checking can 2547fe6060f1SDimitry Andric // produce additional diagnostics so can't be interleaved with our 2548fe6060f1SDimitry Andric // emission of notes. 2549fe6060f1SDimitry Andric // 2550fe6060f1SDimitry Andric // For an aligned allocation, separately check the aligned and unaligned 2551fe6060f1SDimitry Andric // candidates with their respective argument lists. 2552fe6060f1SDimitry Andric SmallVector<OverloadCandidate*, 32> Cands; 2553fe6060f1SDimitry Andric SmallVector<OverloadCandidate*, 32> AlignedCands; 2554fe6060f1SDimitry Andric llvm::SmallVector<Expr*, 4> AlignedArgs; 25550b57cec5SDimitry Andric if (AlignedCandidates) { 25560b57cec5SDimitry Andric auto IsAligned = [](OverloadCandidate &C) { 25570b57cec5SDimitry Andric return C.Function->getNumParams() > 1 && 25580b57cec5SDimitry Andric C.Function->getParamDecl(1)->getType()->isAlignValT(); 25590b57cec5SDimitry Andric }; 25600b57cec5SDimitry Andric auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 25610b57cec5SDimitry Andric 2562fe6060f1SDimitry Andric AlignedArgs.reserve(Args.size() + 1); 2563fe6060f1SDimitry Andric AlignedArgs.push_back(Args[0]); 2564fe6060f1SDimitry Andric AlignedArgs.push_back(AlignArg); 2565fe6060f1SDimitry Andric AlignedArgs.append(Args.begin() + 1, Args.end()); 2566fe6060f1SDimitry Andric AlignedCands = AlignedCandidates->CompleteCandidates( 2567fe6060f1SDimitry Andric S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); 2568fe6060f1SDimitry Andric 2569fe6060f1SDimitry Andric Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2570fe6060f1SDimitry Andric R.getNameLoc(), IsUnaligned); 25710b57cec5SDimitry Andric } else { 2572fe6060f1SDimitry Andric Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2573fe6060f1SDimitry Andric R.getNameLoc()); 25740b57cec5SDimitry Andric } 2575fe6060f1SDimitry Andric 2576fe6060f1SDimitry Andric S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) 2577fe6060f1SDimitry Andric << R.getLookupName() << Range; 2578fe6060f1SDimitry Andric if (AlignedCandidates) 2579fe6060f1SDimitry Andric AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "", 2580fe6060f1SDimitry Andric R.getNameLoc()); 2581fe6060f1SDimitry Andric Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc()); 25820b57cec5SDimitry Andric } 25830b57cec5SDimitry Andric return true; 25840b57cec5SDimitry Andric 25850b57cec5SDimitry Andric case OR_Ambiguous: 25860b57cec5SDimitry Andric if (Diagnose) { 25870b57cec5SDimitry Andric Candidates.NoteCandidates( 25880b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 25890b57cec5SDimitry Andric S.PDiag(diag::err_ovl_ambiguous_call) 25900b57cec5SDimitry Andric << R.getLookupName() << Range), 2591480093f4SDimitry Andric S, OCD_AmbiguousCandidates, Args); 25920b57cec5SDimitry Andric } 25930b57cec5SDimitry Andric return true; 25940b57cec5SDimitry Andric 25950b57cec5SDimitry Andric case OR_Deleted: { 25960b57cec5SDimitry Andric if (Diagnose) { 25970b57cec5SDimitry Andric Candidates.NoteCandidates( 25980b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 25990b57cec5SDimitry Andric S.PDiag(diag::err_ovl_deleted_call) 26000b57cec5SDimitry Andric << R.getLookupName() << Range), 26010b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 26020b57cec5SDimitry Andric } 26030b57cec5SDimitry Andric return true; 26040b57cec5SDimitry Andric } 26050b57cec5SDimitry Andric } 26060b57cec5SDimitry Andric llvm_unreachable("Unreachable, bad result from BestViableFunction"); 26070b57cec5SDimitry Andric } 26080b57cec5SDimitry Andric 26090b57cec5SDimitry Andric bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 26100b57cec5SDimitry Andric AllocationFunctionScope NewScope, 26110b57cec5SDimitry Andric AllocationFunctionScope DeleteScope, 26120b57cec5SDimitry Andric QualType AllocType, bool IsArray, 26130b57cec5SDimitry Andric bool &PassAlignment, MultiExprArg PlaceArgs, 26140b57cec5SDimitry Andric FunctionDecl *&OperatorNew, 26150b57cec5SDimitry Andric FunctionDecl *&OperatorDelete, 26160b57cec5SDimitry Andric bool Diagnose) { 26170b57cec5SDimitry Andric // --- Choosing an allocation function --- 26180b57cec5SDimitry Andric // C++ 5.3.4p8 - 14 & 18 26190b57cec5SDimitry Andric // 1) If looking in AFS_Global scope for allocation functions, only look in 26200b57cec5SDimitry Andric // the global scope. Else, if AFS_Class, only look in the scope of the 26210b57cec5SDimitry Andric // allocated class. If AFS_Both, look in both. 26220b57cec5SDimitry Andric // 2) If an array size is given, look for operator new[], else look for 26230b57cec5SDimitry Andric // operator new. 26240b57cec5SDimitry Andric // 3) The first argument is always size_t. Append the arguments from the 26250b57cec5SDimitry Andric // placement form. 26260b57cec5SDimitry Andric 26270b57cec5SDimitry Andric SmallVector<Expr*, 8> AllocArgs; 26280b57cec5SDimitry Andric AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 26290b57cec5SDimitry Andric 26300b57cec5SDimitry Andric // We don't care about the actual value of these arguments. 26310b57cec5SDimitry Andric // FIXME: Should the Sema create the expression and embed it in the syntax 26320b57cec5SDimitry Andric // tree? Or should the consumer just recalculate the value? 26330b57cec5SDimitry Andric // FIXME: Using a dummy value will interact poorly with attribute enable_if. 2634349cc55cSDimitry Andric IntegerLiteral Size( 2635349cc55cSDimitry Andric Context, llvm::APInt::getZero(Context.getTargetInfo().getPointerWidth(0)), 2636349cc55cSDimitry Andric Context.getSizeType(), SourceLocation()); 26370b57cec5SDimitry Andric AllocArgs.push_back(&Size); 26380b57cec5SDimitry Andric 26390b57cec5SDimitry Andric QualType AlignValT = Context.VoidTy; 26400b57cec5SDimitry Andric if (PassAlignment) { 26410b57cec5SDimitry Andric DeclareGlobalNewDelete(); 26420b57cec5SDimitry Andric AlignValT = Context.getTypeDeclType(getStdAlignValT()); 26430b57cec5SDimitry Andric } 26440b57cec5SDimitry Andric CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 26450b57cec5SDimitry Andric if (PassAlignment) 26460b57cec5SDimitry Andric AllocArgs.push_back(&Align); 26470b57cec5SDimitry Andric 26480b57cec5SDimitry Andric AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 26490b57cec5SDimitry Andric 26500b57cec5SDimitry Andric // C++ [expr.new]p8: 26510b57cec5SDimitry Andric // If the allocated type is a non-array type, the allocation 26520b57cec5SDimitry Andric // function's name is operator new and the deallocation function's 26530b57cec5SDimitry Andric // name is operator delete. If the allocated type is an array 26540b57cec5SDimitry Andric // type, the allocation function's name is operator new[] and the 26550b57cec5SDimitry Andric // deallocation function's name is operator delete[]. 26560b57cec5SDimitry Andric DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 26570b57cec5SDimitry Andric IsArray ? OO_Array_New : OO_New); 26580b57cec5SDimitry Andric 26590b57cec5SDimitry Andric QualType AllocElemType = Context.getBaseElementType(AllocType); 26600b57cec5SDimitry Andric 26610b57cec5SDimitry Andric // Find the allocation function. 26620b57cec5SDimitry Andric { 26630b57cec5SDimitry Andric LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 26640b57cec5SDimitry Andric 26650b57cec5SDimitry Andric // C++1z [expr.new]p9: 26660b57cec5SDimitry Andric // If the new-expression begins with a unary :: operator, the allocation 26670b57cec5SDimitry Andric // function's name is looked up in the global scope. Otherwise, if the 26680b57cec5SDimitry Andric // allocated type is a class type T or array thereof, the allocation 26690b57cec5SDimitry Andric // function's name is looked up in the scope of T. 26700b57cec5SDimitry Andric if (AllocElemType->isRecordType() && NewScope != AFS_Global) 26710b57cec5SDimitry Andric LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 26720b57cec5SDimitry Andric 26730b57cec5SDimitry Andric // We can see ambiguity here if the allocation function is found in 26740b57cec5SDimitry Andric // multiple base classes. 26750b57cec5SDimitry Andric if (R.isAmbiguous()) 26760b57cec5SDimitry Andric return true; 26770b57cec5SDimitry Andric 26780b57cec5SDimitry Andric // If this lookup fails to find the name, or if the allocated type is not 26790b57cec5SDimitry Andric // a class type, the allocation function's name is looked up in the 26800b57cec5SDimitry Andric // global scope. 26810b57cec5SDimitry Andric if (R.empty()) { 26820b57cec5SDimitry Andric if (NewScope == AFS_Class) 26830b57cec5SDimitry Andric return true; 26840b57cec5SDimitry Andric 26850b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 26860b57cec5SDimitry Andric } 26870b57cec5SDimitry Andric 26880b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus && R.empty()) { 26890b57cec5SDimitry Andric if (PlaceArgs.empty()) { 26900b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; 26910b57cec5SDimitry Andric } else { 26920b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_placement_new); 26930b57cec5SDimitry Andric } 26940b57cec5SDimitry Andric return true; 26950b57cec5SDimitry Andric } 26960b57cec5SDimitry Andric 26970b57cec5SDimitry Andric assert(!R.empty() && "implicitly declared allocation functions not found"); 26980b57cec5SDimitry Andric assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 26990b57cec5SDimitry Andric 27000b57cec5SDimitry Andric // We do our own custom access checks below. 27010b57cec5SDimitry Andric R.suppressDiagnostics(); 27020b57cec5SDimitry Andric 27030b57cec5SDimitry Andric if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 27040b57cec5SDimitry Andric OperatorNew, /*Candidates=*/nullptr, 27050b57cec5SDimitry Andric /*AlignArg=*/nullptr, Diagnose)) 27060b57cec5SDimitry Andric return true; 27070b57cec5SDimitry Andric } 27080b57cec5SDimitry Andric 27090b57cec5SDimitry Andric // We don't need an operator delete if we're running under -fno-exceptions. 27100b57cec5SDimitry Andric if (!getLangOpts().Exceptions) { 27110b57cec5SDimitry Andric OperatorDelete = nullptr; 27120b57cec5SDimitry Andric return false; 27130b57cec5SDimitry Andric } 27140b57cec5SDimitry Andric 27150b57cec5SDimitry Andric // Note, the name of OperatorNew might have been changed from array to 27160b57cec5SDimitry Andric // non-array by resolveAllocationOverload. 27170b57cec5SDimitry Andric DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 27180b57cec5SDimitry Andric OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 27190b57cec5SDimitry Andric ? OO_Array_Delete 27200b57cec5SDimitry Andric : OO_Delete); 27210b57cec5SDimitry Andric 27220b57cec5SDimitry Andric // C++ [expr.new]p19: 27230b57cec5SDimitry Andric // 27240b57cec5SDimitry Andric // If the new-expression begins with a unary :: operator, the 27250b57cec5SDimitry Andric // deallocation function's name is looked up in the global 27260b57cec5SDimitry Andric // scope. Otherwise, if the allocated type is a class type T or an 27270b57cec5SDimitry Andric // array thereof, the deallocation function's name is looked up in 27280b57cec5SDimitry Andric // the scope of T. If this lookup fails to find the name, or if 27290b57cec5SDimitry Andric // the allocated type is not a class type or array thereof, the 27300b57cec5SDimitry Andric // deallocation function's name is looked up in the global scope. 27310b57cec5SDimitry Andric LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 27320b57cec5SDimitry Andric if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { 2733a7dea167SDimitry Andric auto *RD = 2734a7dea167SDimitry Andric cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); 27350b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, RD); 27360b57cec5SDimitry Andric } 27370b57cec5SDimitry Andric if (FoundDelete.isAmbiguous()) 27380b57cec5SDimitry Andric return true; // FIXME: clean up expressions? 27390b57cec5SDimitry Andric 2740e8d8bef9SDimitry Andric // Filter out any destroying operator deletes. We can't possibly call such a 2741e8d8bef9SDimitry Andric // function in this context, because we're handling the case where the object 2742e8d8bef9SDimitry Andric // was not successfully constructed. 2743e8d8bef9SDimitry Andric // FIXME: This is not covered by the language rules yet. 2744e8d8bef9SDimitry Andric { 2745e8d8bef9SDimitry Andric LookupResult::Filter Filter = FoundDelete.makeFilter(); 2746e8d8bef9SDimitry Andric while (Filter.hasNext()) { 2747e8d8bef9SDimitry Andric auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); 2748e8d8bef9SDimitry Andric if (FD && FD->isDestroyingOperatorDelete()) 2749e8d8bef9SDimitry Andric Filter.erase(); 2750e8d8bef9SDimitry Andric } 2751e8d8bef9SDimitry Andric Filter.done(); 2752e8d8bef9SDimitry Andric } 2753e8d8bef9SDimitry Andric 27540b57cec5SDimitry Andric bool FoundGlobalDelete = FoundDelete.empty(); 27550b57cec5SDimitry Andric if (FoundDelete.empty()) { 2756e8d8bef9SDimitry Andric FoundDelete.clear(LookupOrdinaryName); 2757e8d8bef9SDimitry Andric 27580b57cec5SDimitry Andric if (DeleteScope == AFS_Class) 27590b57cec5SDimitry Andric return true; 27600b57cec5SDimitry Andric 27610b57cec5SDimitry Andric DeclareGlobalNewDelete(); 27620b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 27630b57cec5SDimitry Andric } 27640b57cec5SDimitry Andric 27650b57cec5SDimitry Andric FoundDelete.suppressDiagnostics(); 27660b57cec5SDimitry Andric 27670b57cec5SDimitry Andric SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 27680b57cec5SDimitry Andric 27690b57cec5SDimitry Andric // Whether we're looking for a placement operator delete is dictated 27700b57cec5SDimitry Andric // by whether we selected a placement operator new, not by whether 27710b57cec5SDimitry Andric // we had explicit placement arguments. This matters for things like 27720b57cec5SDimitry Andric // struct A { void *operator new(size_t, int = 0); ... }; 27730b57cec5SDimitry Andric // A *a = new A() 27740b57cec5SDimitry Andric // 27750b57cec5SDimitry Andric // We don't have any definition for what a "placement allocation function" 27760b57cec5SDimitry Andric // is, but we assume it's any allocation function whose 27770b57cec5SDimitry Andric // parameter-declaration-clause is anything other than (size_t). 27780b57cec5SDimitry Andric // 27790b57cec5SDimitry Andric // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 27800b57cec5SDimitry Andric // This affects whether an exception from the constructor of an overaligned 27810b57cec5SDimitry Andric // type uses the sized or non-sized form of aligned operator delete. 27820b57cec5SDimitry Andric bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 27830b57cec5SDimitry Andric OperatorNew->isVariadic(); 27840b57cec5SDimitry Andric 27850b57cec5SDimitry Andric if (isPlacementNew) { 27860b57cec5SDimitry Andric // C++ [expr.new]p20: 27870b57cec5SDimitry Andric // A declaration of a placement deallocation function matches the 27880b57cec5SDimitry Andric // declaration of a placement allocation function if it has the 27890b57cec5SDimitry Andric // same number of parameters and, after parameter transformations 27900b57cec5SDimitry Andric // (8.3.5), all parameter types except the first are 27910b57cec5SDimitry Andric // identical. [...] 27920b57cec5SDimitry Andric // 27930b57cec5SDimitry Andric // To perform this comparison, we compute the function type that 27940b57cec5SDimitry Andric // the deallocation function should have, and use that type both 27950b57cec5SDimitry Andric // for template argument deduction and for comparison purposes. 27960b57cec5SDimitry Andric QualType ExpectedFunctionType; 27970b57cec5SDimitry Andric { 27985ffd83dbSDimitry Andric auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 27990b57cec5SDimitry Andric 28000b57cec5SDimitry Andric SmallVector<QualType, 4> ArgTypes; 28010b57cec5SDimitry Andric ArgTypes.push_back(Context.VoidPtrTy); 28020b57cec5SDimitry Andric for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 28030b57cec5SDimitry Andric ArgTypes.push_back(Proto->getParamType(I)); 28040b57cec5SDimitry Andric 28050b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI; 28060b57cec5SDimitry Andric // FIXME: This is not part of the standard's rule. 28070b57cec5SDimitry Andric EPI.Variadic = Proto->isVariadic(); 28080b57cec5SDimitry Andric 28090b57cec5SDimitry Andric ExpectedFunctionType 28100b57cec5SDimitry Andric = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 28110b57cec5SDimitry Andric } 28120b57cec5SDimitry Andric 28130b57cec5SDimitry Andric for (LookupResult::iterator D = FoundDelete.begin(), 28140b57cec5SDimitry Andric DEnd = FoundDelete.end(); 28150b57cec5SDimitry Andric D != DEnd; ++D) { 28160b57cec5SDimitry Andric FunctionDecl *Fn = nullptr; 28170b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTmpl = 28180b57cec5SDimitry Andric dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 28190b57cec5SDimitry Andric // Perform template argument deduction to try to match the 28200b57cec5SDimitry Andric // expected function type. 28210b57cec5SDimitry Andric TemplateDeductionInfo Info(StartLoc); 28220b57cec5SDimitry Andric if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 28230b57cec5SDimitry Andric Info)) 28240b57cec5SDimitry Andric continue; 28250b57cec5SDimitry Andric } else 28260b57cec5SDimitry Andric Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 28270b57cec5SDimitry Andric 28280b57cec5SDimitry Andric if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), 28290b57cec5SDimitry Andric ExpectedFunctionType, 28300b57cec5SDimitry Andric /*AdjustExcpetionSpec*/true), 28310b57cec5SDimitry Andric ExpectedFunctionType)) 28320b57cec5SDimitry Andric Matches.push_back(std::make_pair(D.getPair(), Fn)); 28330b57cec5SDimitry Andric } 28340b57cec5SDimitry Andric 28350b57cec5SDimitry Andric if (getLangOpts().CUDA) 283681ad6265SDimitry Andric EraseUnwantedCUDAMatches(getCurFunctionDecl(/*AllowLambda=*/true), 283781ad6265SDimitry Andric Matches); 28380b57cec5SDimitry Andric } else { 28390b57cec5SDimitry Andric // C++1y [expr.new]p22: 28400b57cec5SDimitry Andric // For a non-placement allocation function, the normal deallocation 28410b57cec5SDimitry Andric // function lookup is used 28420b57cec5SDimitry Andric // 28430b57cec5SDimitry Andric // Per [expr.delete]p10, this lookup prefers a member operator delete 28440b57cec5SDimitry Andric // without a size_t argument, but prefers a non-member operator delete 28450b57cec5SDimitry Andric // with a size_t where possible (which it always is in this case). 28460b57cec5SDimitry Andric llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 28470b57cec5SDimitry Andric UsualDeallocFnInfo Selected = resolveDeallocationOverload( 28480b57cec5SDimitry Andric *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 28490b57cec5SDimitry Andric /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 28500b57cec5SDimitry Andric &BestDeallocFns); 28510b57cec5SDimitry Andric if (Selected) 28520b57cec5SDimitry Andric Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 28530b57cec5SDimitry Andric else { 28540b57cec5SDimitry Andric // If we failed to select an operator, all remaining functions are viable 28550b57cec5SDimitry Andric // but ambiguous. 28560b57cec5SDimitry Andric for (auto Fn : BestDeallocFns) 28570b57cec5SDimitry Andric Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 28580b57cec5SDimitry Andric } 28590b57cec5SDimitry Andric } 28600b57cec5SDimitry Andric 28610b57cec5SDimitry Andric // C++ [expr.new]p20: 28620b57cec5SDimitry Andric // [...] If the lookup finds a single matching deallocation 28630b57cec5SDimitry Andric // function, that function will be called; otherwise, no 28640b57cec5SDimitry Andric // deallocation function will be called. 28650b57cec5SDimitry Andric if (Matches.size() == 1) { 28660b57cec5SDimitry Andric OperatorDelete = Matches[0].second; 28670b57cec5SDimitry Andric 28680b57cec5SDimitry Andric // C++1z [expr.new]p23: 28690b57cec5SDimitry Andric // If the lookup finds a usual deallocation function (3.7.4.2) 28700b57cec5SDimitry Andric // with a parameter of type std::size_t and that function, considered 28710b57cec5SDimitry Andric // as a placement deallocation function, would have been 28720b57cec5SDimitry Andric // selected as a match for the allocation function, the program 28730b57cec5SDimitry Andric // is ill-formed. 28740b57cec5SDimitry Andric if (getLangOpts().CPlusPlus11 && isPlacementNew && 28750b57cec5SDimitry Andric isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 28760b57cec5SDimitry Andric UsualDeallocFnInfo Info(*this, 28770b57cec5SDimitry Andric DeclAccessPair::make(OperatorDelete, AS_public)); 28780b57cec5SDimitry Andric // Core issue, per mail to core reflector, 2016-10-09: 28790b57cec5SDimitry Andric // If this is a member operator delete, and there is a corresponding 28800b57cec5SDimitry Andric // non-sized member operator delete, this isn't /really/ a sized 28810b57cec5SDimitry Andric // deallocation function, it just happens to have a size_t parameter. 28820b57cec5SDimitry Andric bool IsSizedDelete = Info.HasSizeT; 28830b57cec5SDimitry Andric if (IsSizedDelete && !FoundGlobalDelete) { 28840b57cec5SDimitry Andric auto NonSizedDelete = 28850b57cec5SDimitry Andric resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 28860b57cec5SDimitry Andric /*WantAlign*/Info.HasAlignValT); 28870b57cec5SDimitry Andric if (NonSizedDelete && !NonSizedDelete.HasSizeT && 28880b57cec5SDimitry Andric NonSizedDelete.HasAlignValT == Info.HasAlignValT) 28890b57cec5SDimitry Andric IsSizedDelete = false; 28900b57cec5SDimitry Andric } 28910b57cec5SDimitry Andric 28920b57cec5SDimitry Andric if (IsSizedDelete) { 28930b57cec5SDimitry Andric SourceRange R = PlaceArgs.empty() 28940b57cec5SDimitry Andric ? SourceRange() 28950b57cec5SDimitry Andric : SourceRange(PlaceArgs.front()->getBeginLoc(), 28960b57cec5SDimitry Andric PlaceArgs.back()->getEndLoc()); 28970b57cec5SDimitry Andric Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 28980b57cec5SDimitry Andric if (!OperatorDelete->isImplicit()) 28990b57cec5SDimitry Andric Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 29000b57cec5SDimitry Andric << DeleteName; 29010b57cec5SDimitry Andric } 29020b57cec5SDimitry Andric } 29030b57cec5SDimitry Andric 29040b57cec5SDimitry Andric CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 29050b57cec5SDimitry Andric Matches[0].first); 29060b57cec5SDimitry Andric } else if (!Matches.empty()) { 29070b57cec5SDimitry Andric // We found multiple suitable operators. Per [expr.new]p20, that means we 29080b57cec5SDimitry Andric // call no 'operator delete' function, but we should at least warn the user. 29090b57cec5SDimitry Andric // FIXME: Suppress this warning if the construction cannot throw. 29100b57cec5SDimitry Andric Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 29110b57cec5SDimitry Andric << DeleteName << AllocElemType; 29120b57cec5SDimitry Andric 29130b57cec5SDimitry Andric for (auto &Match : Matches) 29140b57cec5SDimitry Andric Diag(Match.second->getLocation(), 29150b57cec5SDimitry Andric diag::note_member_declared_here) << DeleteName; 29160b57cec5SDimitry Andric } 29170b57cec5SDimitry Andric 29180b57cec5SDimitry Andric return false; 29190b57cec5SDimitry Andric } 29200b57cec5SDimitry Andric 29210b57cec5SDimitry Andric /// DeclareGlobalNewDelete - Declare the global forms of operator new and 29220b57cec5SDimitry Andric /// delete. These are: 29230b57cec5SDimitry Andric /// @code 29240b57cec5SDimitry Andric /// // C++03: 29250b57cec5SDimitry Andric /// void* operator new(std::size_t) throw(std::bad_alloc); 29260b57cec5SDimitry Andric /// void* operator new[](std::size_t) throw(std::bad_alloc); 29270b57cec5SDimitry Andric /// void operator delete(void *) throw(); 29280b57cec5SDimitry Andric /// void operator delete[](void *) throw(); 29290b57cec5SDimitry Andric /// // C++11: 29300b57cec5SDimitry Andric /// void* operator new(std::size_t); 29310b57cec5SDimitry Andric /// void* operator new[](std::size_t); 29320b57cec5SDimitry Andric /// void operator delete(void *) noexcept; 29330b57cec5SDimitry Andric /// void operator delete[](void *) noexcept; 29340b57cec5SDimitry Andric /// // C++1y: 29350b57cec5SDimitry Andric /// void* operator new(std::size_t); 29360b57cec5SDimitry Andric /// void* operator new[](std::size_t); 29370b57cec5SDimitry Andric /// void operator delete(void *) noexcept; 29380b57cec5SDimitry Andric /// void operator delete[](void *) noexcept; 29390b57cec5SDimitry Andric /// void operator delete(void *, std::size_t) noexcept; 29400b57cec5SDimitry Andric /// void operator delete[](void *, std::size_t) noexcept; 29410b57cec5SDimitry Andric /// @endcode 29420b57cec5SDimitry Andric /// Note that the placement and nothrow forms of new are *not* implicitly 29430b57cec5SDimitry Andric /// declared. Their use requires including \<new\>. 29440b57cec5SDimitry Andric void Sema::DeclareGlobalNewDelete() { 29450b57cec5SDimitry Andric if (GlobalNewDeleteDeclared) 29460b57cec5SDimitry Andric return; 29470b57cec5SDimitry Andric 29480b57cec5SDimitry Andric // The implicitly declared new and delete operators 29490b57cec5SDimitry Andric // are not supported in OpenCL. 29500b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) 29510b57cec5SDimitry Andric return; 29520b57cec5SDimitry Andric 29530b57cec5SDimitry Andric // C++ [basic.std.dynamic]p2: 29540b57cec5SDimitry Andric // [...] The following allocation and deallocation functions (18.4) are 29550b57cec5SDimitry Andric // implicitly declared in global scope in each translation unit of a 29560b57cec5SDimitry Andric // program 29570b57cec5SDimitry Andric // 29580b57cec5SDimitry Andric // C++03: 29590b57cec5SDimitry Andric // void* operator new(std::size_t) throw(std::bad_alloc); 29600b57cec5SDimitry Andric // void* operator new[](std::size_t) throw(std::bad_alloc); 29610b57cec5SDimitry Andric // void operator delete(void*) throw(); 29620b57cec5SDimitry Andric // void operator delete[](void*) throw(); 29630b57cec5SDimitry Andric // C++11: 29640b57cec5SDimitry Andric // void* operator new(std::size_t); 29650b57cec5SDimitry Andric // void* operator new[](std::size_t); 29660b57cec5SDimitry Andric // void operator delete(void*) noexcept; 29670b57cec5SDimitry Andric // void operator delete[](void*) noexcept; 29680b57cec5SDimitry Andric // C++1y: 29690b57cec5SDimitry Andric // void* operator new(std::size_t); 29700b57cec5SDimitry Andric // void* operator new[](std::size_t); 29710b57cec5SDimitry Andric // void operator delete(void*) noexcept; 29720b57cec5SDimitry Andric // void operator delete[](void*) noexcept; 29730b57cec5SDimitry Andric // void operator delete(void*, std::size_t) noexcept; 29740b57cec5SDimitry Andric // void operator delete[](void*, std::size_t) noexcept; 29750b57cec5SDimitry Andric // 29760b57cec5SDimitry Andric // These implicit declarations introduce only the function names operator 29770b57cec5SDimitry Andric // new, operator new[], operator delete, operator delete[]. 29780b57cec5SDimitry Andric // 29790b57cec5SDimitry Andric // Here, we need to refer to std::bad_alloc, so we will implicitly declare 29800b57cec5SDimitry Andric // "std" or "bad_alloc" as necessary to form the exception specification. 29810b57cec5SDimitry Andric // However, we do not make these implicit declarations visible to name 29820b57cec5SDimitry Andric // lookup. 29830b57cec5SDimitry Andric if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 29840b57cec5SDimitry Andric // The "std::bad_alloc" class has not yet been declared, so build it 29850b57cec5SDimitry Andric // implicitly. 29860b57cec5SDimitry Andric StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 29870b57cec5SDimitry Andric getOrCreateStdNamespace(), 29880b57cec5SDimitry Andric SourceLocation(), SourceLocation(), 29890b57cec5SDimitry Andric &PP.getIdentifierTable().get("bad_alloc"), 29900b57cec5SDimitry Andric nullptr); 29910b57cec5SDimitry Andric getStdBadAlloc()->setImplicit(true); 29920b57cec5SDimitry Andric } 29930b57cec5SDimitry Andric if (!StdAlignValT && getLangOpts().AlignedAllocation) { 29940b57cec5SDimitry Andric // The "std::align_val_t" enum class has not yet been declared, so build it 29950b57cec5SDimitry Andric // implicitly. 29960b57cec5SDimitry Andric auto *AlignValT = EnumDecl::Create( 29970b57cec5SDimitry Andric Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 29980b57cec5SDimitry Andric &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 29990b57cec5SDimitry Andric AlignValT->setIntegerType(Context.getSizeType()); 30000b57cec5SDimitry Andric AlignValT->setPromotionType(Context.getSizeType()); 30010b57cec5SDimitry Andric AlignValT->setImplicit(true); 30020b57cec5SDimitry Andric StdAlignValT = AlignValT; 30030b57cec5SDimitry Andric } 30040b57cec5SDimitry Andric 30050b57cec5SDimitry Andric GlobalNewDeleteDeclared = true; 30060b57cec5SDimitry Andric 30070b57cec5SDimitry Andric QualType VoidPtr = Context.getPointerType(Context.VoidTy); 30080b57cec5SDimitry Andric QualType SizeT = Context.getSizeType(); 30090b57cec5SDimitry Andric 30100b57cec5SDimitry Andric auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 30110b57cec5SDimitry Andric QualType Return, QualType Param) { 30120b57cec5SDimitry Andric llvm::SmallVector<QualType, 3> Params; 30130b57cec5SDimitry Andric Params.push_back(Param); 30140b57cec5SDimitry Andric 30150b57cec5SDimitry Andric // Create up to four variants of the function (sized/aligned). 30160b57cec5SDimitry Andric bool HasSizedVariant = getLangOpts().SizedDeallocation && 30170b57cec5SDimitry Andric (Kind == OO_Delete || Kind == OO_Array_Delete); 30180b57cec5SDimitry Andric bool HasAlignedVariant = getLangOpts().AlignedAllocation; 30190b57cec5SDimitry Andric 30200b57cec5SDimitry Andric int NumSizeVariants = (HasSizedVariant ? 2 : 1); 30210b57cec5SDimitry Andric int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 30220b57cec5SDimitry Andric for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 30230b57cec5SDimitry Andric if (Sized) 30240b57cec5SDimitry Andric Params.push_back(SizeT); 30250b57cec5SDimitry Andric 30260b57cec5SDimitry Andric for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 30270b57cec5SDimitry Andric if (Aligned) 30280b57cec5SDimitry Andric Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 30290b57cec5SDimitry Andric 30300b57cec5SDimitry Andric DeclareGlobalAllocationFunction( 30310b57cec5SDimitry Andric Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 30320b57cec5SDimitry Andric 30330b57cec5SDimitry Andric if (Aligned) 30340b57cec5SDimitry Andric Params.pop_back(); 30350b57cec5SDimitry Andric } 30360b57cec5SDimitry Andric } 30370b57cec5SDimitry Andric }; 30380b57cec5SDimitry Andric 30390b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 30400b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 30410b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 30420b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 30430b57cec5SDimitry Andric } 30440b57cec5SDimitry Andric 30450b57cec5SDimitry Andric /// DeclareGlobalAllocationFunction - Declares a single implicit global 30460b57cec5SDimitry Andric /// allocation function if it doesn't already exist. 30470b57cec5SDimitry Andric void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 30480b57cec5SDimitry Andric QualType Return, 30490b57cec5SDimitry Andric ArrayRef<QualType> Params) { 30500b57cec5SDimitry Andric DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 30510b57cec5SDimitry Andric 30520b57cec5SDimitry Andric // Check if this function is already declared. 30530b57cec5SDimitry Andric DeclContext::lookup_result R = GlobalCtx->lookup(Name); 30540b57cec5SDimitry Andric for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 30550b57cec5SDimitry Andric Alloc != AllocEnd; ++Alloc) { 30560b57cec5SDimitry Andric // Only look at non-template functions, as it is the predefined, 30570b57cec5SDimitry Andric // non-templated allocation function we are trying to declare here. 30580b57cec5SDimitry Andric if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 30590b57cec5SDimitry Andric if (Func->getNumParams() == Params.size()) { 30600b57cec5SDimitry Andric llvm::SmallVector<QualType, 3> FuncParams; 30610b57cec5SDimitry Andric for (auto *P : Func->parameters()) 30620b57cec5SDimitry Andric FuncParams.push_back( 30630b57cec5SDimitry Andric Context.getCanonicalType(P->getType().getUnqualifiedType())); 30640b57cec5SDimitry Andric if (llvm::makeArrayRef(FuncParams) == Params) { 30650b57cec5SDimitry Andric // Make the function visible to name lookup, even if we found it in 30660b57cec5SDimitry Andric // an unimported module. It either is an implicitly-declared global 30670b57cec5SDimitry Andric // allocation function, or is suppressing that function. 30680b57cec5SDimitry Andric Func->setVisibleDespiteOwningModule(); 30690b57cec5SDimitry Andric return; 30700b57cec5SDimitry Andric } 30710b57cec5SDimitry Andric } 30720b57cec5SDimitry Andric } 30730b57cec5SDimitry Andric } 30740b57cec5SDimitry Andric 30750b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 30760b57cec5SDimitry Andric /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 30770b57cec5SDimitry Andric 30780b57cec5SDimitry Andric QualType BadAllocType; 30790b57cec5SDimitry Andric bool HasBadAllocExceptionSpec 30800b57cec5SDimitry Andric = (Name.getCXXOverloadedOperator() == OO_New || 30810b57cec5SDimitry Andric Name.getCXXOverloadedOperator() == OO_Array_New); 30820b57cec5SDimitry Andric if (HasBadAllocExceptionSpec) { 30830b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus11) { 30840b57cec5SDimitry Andric BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 30850b57cec5SDimitry Andric assert(StdBadAlloc && "Must have std::bad_alloc declared"); 30860b57cec5SDimitry Andric EPI.ExceptionSpec.Type = EST_Dynamic; 30870b57cec5SDimitry Andric EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); 30880b57cec5SDimitry Andric } 3089349cc55cSDimitry Andric if (getLangOpts().NewInfallible) { 3090349cc55cSDimitry Andric EPI.ExceptionSpec.Type = EST_DynamicNone; 3091349cc55cSDimitry Andric } 30920b57cec5SDimitry Andric } else { 30930b57cec5SDimitry Andric EPI.ExceptionSpec = 30940b57cec5SDimitry Andric getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 30950b57cec5SDimitry Andric } 30960b57cec5SDimitry Andric 30970b57cec5SDimitry Andric auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 30980b57cec5SDimitry Andric QualType FnType = Context.getFunctionType(Return, Params, EPI); 30990b57cec5SDimitry Andric FunctionDecl *Alloc = FunctionDecl::Create( 3100349cc55cSDimitry Andric Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType, 3101349cc55cSDimitry Andric /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false, 3102349cc55cSDimitry Andric true); 31030b57cec5SDimitry Andric Alloc->setImplicit(); 31040b57cec5SDimitry Andric // Global allocation functions should always be visible. 31050b57cec5SDimitry Andric Alloc->setVisibleDespiteOwningModule(); 31060b57cec5SDimitry Andric 3107349cc55cSDimitry Andric if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible) 3108349cc55cSDimitry Andric Alloc->addAttr( 3109349cc55cSDimitry Andric ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation())); 3110349cc55cSDimitry Andric 31110b57cec5SDimitry Andric Alloc->addAttr(VisibilityAttr::CreateImplicit( 31120b57cec5SDimitry Andric Context, LangOpts.GlobalAllocationFunctionVisibilityHidden 31130b57cec5SDimitry Andric ? VisibilityAttr::Hidden 31140b57cec5SDimitry Andric : VisibilityAttr::Default)); 31150b57cec5SDimitry Andric 31160b57cec5SDimitry Andric llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 31170b57cec5SDimitry Andric for (QualType T : Params) { 31180b57cec5SDimitry Andric ParamDecls.push_back(ParmVarDecl::Create( 31190b57cec5SDimitry Andric Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 31200b57cec5SDimitry Andric /*TInfo=*/nullptr, SC_None, nullptr)); 31210b57cec5SDimitry Andric ParamDecls.back()->setImplicit(); 31220b57cec5SDimitry Andric } 31230b57cec5SDimitry Andric Alloc->setParams(ParamDecls); 31240b57cec5SDimitry Andric if (ExtraAttr) 31250b57cec5SDimitry Andric Alloc->addAttr(ExtraAttr); 31265ffd83dbSDimitry Andric AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); 31270b57cec5SDimitry Andric Context.getTranslationUnitDecl()->addDecl(Alloc); 31280b57cec5SDimitry Andric IdResolver.tryAddTopLevelDecl(Alloc, Name); 31290b57cec5SDimitry Andric }; 31300b57cec5SDimitry Andric 31310b57cec5SDimitry Andric if (!LangOpts.CUDA) 31320b57cec5SDimitry Andric CreateAllocationFunctionDecl(nullptr); 31330b57cec5SDimitry Andric else { 31340b57cec5SDimitry Andric // Host and device get their own declaration so each can be 31350b57cec5SDimitry Andric // defined or re-declared independently. 31360b57cec5SDimitry Andric CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 31370b57cec5SDimitry Andric CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 31380b57cec5SDimitry Andric } 31390b57cec5SDimitry Andric } 31400b57cec5SDimitry Andric 31410b57cec5SDimitry Andric FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 31420b57cec5SDimitry Andric bool CanProvideSize, 31430b57cec5SDimitry Andric bool Overaligned, 31440b57cec5SDimitry Andric DeclarationName Name) { 31450b57cec5SDimitry Andric DeclareGlobalNewDelete(); 31460b57cec5SDimitry Andric 31470b57cec5SDimitry Andric LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 31480b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 31490b57cec5SDimitry Andric 31500b57cec5SDimitry Andric // FIXME: It's possible for this to result in ambiguity, through a 31510b57cec5SDimitry Andric // user-declared variadic operator delete or the enable_if attribute. We 31520b57cec5SDimitry Andric // should probably not consider those cases to be usual deallocation 31530b57cec5SDimitry Andric // functions. But for now we just make an arbitrary choice in that case. 31540b57cec5SDimitry Andric auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 31550b57cec5SDimitry Andric Overaligned); 31560b57cec5SDimitry Andric assert(Result.FD && "operator delete missing from global scope?"); 31570b57cec5SDimitry Andric return Result.FD; 31580b57cec5SDimitry Andric } 31590b57cec5SDimitry Andric 31600b57cec5SDimitry Andric FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 31610b57cec5SDimitry Andric CXXRecordDecl *RD) { 31620b57cec5SDimitry Andric DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 31630b57cec5SDimitry Andric 31640b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 31650b57cec5SDimitry Andric if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 31660b57cec5SDimitry Andric return nullptr; 31670b57cec5SDimitry Andric if (OperatorDelete) 31680b57cec5SDimitry Andric return OperatorDelete; 31690b57cec5SDimitry Andric 31700b57cec5SDimitry Andric // If there's no class-specific operator delete, look up the global 31710b57cec5SDimitry Andric // non-array delete. 31720b57cec5SDimitry Andric return FindUsualDeallocationFunction( 31730b57cec5SDimitry Andric Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 31740b57cec5SDimitry Andric Name); 31750b57cec5SDimitry Andric } 31760b57cec5SDimitry Andric 31770b57cec5SDimitry Andric bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 31780b57cec5SDimitry Andric DeclarationName Name, 31790b57cec5SDimitry Andric FunctionDecl *&Operator, bool Diagnose) { 31800b57cec5SDimitry Andric LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 31810b57cec5SDimitry Andric // Try to find operator delete/operator delete[] in class scope. 31820b57cec5SDimitry Andric LookupQualifiedName(Found, RD); 31830b57cec5SDimitry Andric 31840b57cec5SDimitry Andric if (Found.isAmbiguous()) 31850b57cec5SDimitry Andric return true; 31860b57cec5SDimitry Andric 31870b57cec5SDimitry Andric Found.suppressDiagnostics(); 31880b57cec5SDimitry Andric 31890b57cec5SDimitry Andric bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 31900b57cec5SDimitry Andric 31910b57cec5SDimitry Andric // C++17 [expr.delete]p10: 31920b57cec5SDimitry Andric // If the deallocation functions have class scope, the one without a 31930b57cec5SDimitry Andric // parameter of type std::size_t is selected. 31940b57cec5SDimitry Andric llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 31950b57cec5SDimitry Andric resolveDeallocationOverload(*this, Found, /*WantSize*/ false, 31960b57cec5SDimitry Andric /*WantAlign*/ Overaligned, &Matches); 31970b57cec5SDimitry Andric 31980b57cec5SDimitry Andric // If we could find an overload, use it. 31990b57cec5SDimitry Andric if (Matches.size() == 1) { 32000b57cec5SDimitry Andric Operator = cast<CXXMethodDecl>(Matches[0].FD); 32010b57cec5SDimitry Andric 32020b57cec5SDimitry Andric // FIXME: DiagnoseUseOfDecl? 32030b57cec5SDimitry Andric if (Operator->isDeleted()) { 32040b57cec5SDimitry Andric if (Diagnose) { 32050b57cec5SDimitry Andric Diag(StartLoc, diag::err_deleted_function_use); 32060b57cec5SDimitry Andric NoteDeletedFunction(Operator); 32070b57cec5SDimitry Andric } 32080b57cec5SDimitry Andric return true; 32090b57cec5SDimitry Andric } 32100b57cec5SDimitry Andric 32110b57cec5SDimitry Andric if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 32120b57cec5SDimitry Andric Matches[0].Found, Diagnose) == AR_inaccessible) 32130b57cec5SDimitry Andric return true; 32140b57cec5SDimitry Andric 32150b57cec5SDimitry Andric return false; 32160b57cec5SDimitry Andric } 32170b57cec5SDimitry Andric 32180b57cec5SDimitry Andric // We found multiple suitable operators; complain about the ambiguity. 32190b57cec5SDimitry Andric // FIXME: The standard doesn't say to do this; it appears that the intent 32200b57cec5SDimitry Andric // is that this should never happen. 32210b57cec5SDimitry Andric if (!Matches.empty()) { 32220b57cec5SDimitry Andric if (Diagnose) { 32230b57cec5SDimitry Andric Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 32240b57cec5SDimitry Andric << Name << RD; 32250b57cec5SDimitry Andric for (auto &Match : Matches) 32260b57cec5SDimitry Andric Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 32270b57cec5SDimitry Andric } 32280b57cec5SDimitry Andric return true; 32290b57cec5SDimitry Andric } 32300b57cec5SDimitry Andric 32310b57cec5SDimitry Andric // We did find operator delete/operator delete[] declarations, but 32320b57cec5SDimitry Andric // none of them were suitable. 32330b57cec5SDimitry Andric if (!Found.empty()) { 32340b57cec5SDimitry Andric if (Diagnose) { 32350b57cec5SDimitry Andric Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 32360b57cec5SDimitry Andric << Name << RD; 32370b57cec5SDimitry Andric 32380b57cec5SDimitry Andric for (NamedDecl *D : Found) 32390b57cec5SDimitry Andric Diag(D->getUnderlyingDecl()->getLocation(), 32400b57cec5SDimitry Andric diag::note_member_declared_here) << Name; 32410b57cec5SDimitry Andric } 32420b57cec5SDimitry Andric return true; 32430b57cec5SDimitry Andric } 32440b57cec5SDimitry Andric 32450b57cec5SDimitry Andric Operator = nullptr; 32460b57cec5SDimitry Andric return false; 32470b57cec5SDimitry Andric } 32480b57cec5SDimitry Andric 32490b57cec5SDimitry Andric namespace { 32500b57cec5SDimitry Andric /// Checks whether delete-expression, and new-expression used for 32510b57cec5SDimitry Andric /// initializing deletee have the same array form. 32520b57cec5SDimitry Andric class MismatchingNewDeleteDetector { 32530b57cec5SDimitry Andric public: 32540b57cec5SDimitry Andric enum MismatchResult { 32550b57cec5SDimitry Andric /// Indicates that there is no mismatch or a mismatch cannot be proven. 32560b57cec5SDimitry Andric NoMismatch, 32570b57cec5SDimitry Andric /// Indicates that variable is initialized with mismatching form of \a new. 32580b57cec5SDimitry Andric VarInitMismatches, 32590b57cec5SDimitry Andric /// Indicates that member is initialized with mismatching form of \a new. 32600b57cec5SDimitry Andric MemberInitMismatches, 32610b57cec5SDimitry Andric /// Indicates that 1 or more constructors' definitions could not been 32620b57cec5SDimitry Andric /// analyzed, and they will be checked again at the end of translation unit. 32630b57cec5SDimitry Andric AnalyzeLater 32640b57cec5SDimitry Andric }; 32650b57cec5SDimitry Andric 32660b57cec5SDimitry Andric /// \param EndOfTU True, if this is the final analysis at the end of 32670b57cec5SDimitry Andric /// translation unit. False, if this is the initial analysis at the point 32680b57cec5SDimitry Andric /// delete-expression was encountered. 32690b57cec5SDimitry Andric explicit MismatchingNewDeleteDetector(bool EndOfTU) 32700b57cec5SDimitry Andric : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 32710b57cec5SDimitry Andric HasUndefinedConstructors(false) {} 32720b57cec5SDimitry Andric 32730b57cec5SDimitry Andric /// Checks whether pointee of a delete-expression is initialized with 32740b57cec5SDimitry Andric /// matching form of new-expression. 32750b57cec5SDimitry Andric /// 32760b57cec5SDimitry Andric /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 32770b57cec5SDimitry Andric /// point where delete-expression is encountered, then a warning will be 32780b57cec5SDimitry Andric /// issued immediately. If return value is \c AnalyzeLater at the point where 32790b57cec5SDimitry Andric /// delete-expression is seen, then member will be analyzed at the end of 32800b57cec5SDimitry Andric /// translation unit. \c AnalyzeLater is returned iff at least one constructor 32810b57cec5SDimitry Andric /// couldn't be analyzed. If at least one constructor initializes the member 32820b57cec5SDimitry Andric /// with matching type of new, the return value is \c NoMismatch. 32830b57cec5SDimitry Andric MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 32840b57cec5SDimitry Andric /// Analyzes a class member. 32850b57cec5SDimitry Andric /// \param Field Class member to analyze. 32860b57cec5SDimitry Andric /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 32870b57cec5SDimitry Andric /// for deleting the \p Field. 32880b57cec5SDimitry Andric MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 32890b57cec5SDimitry Andric FieldDecl *Field; 32900b57cec5SDimitry Andric /// List of mismatching new-expressions used for initialization of the pointee 32910b57cec5SDimitry Andric llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 32920b57cec5SDimitry Andric /// Indicates whether delete-expression was in array form. 32930b57cec5SDimitry Andric bool IsArrayForm; 32940b57cec5SDimitry Andric 32950b57cec5SDimitry Andric private: 32960b57cec5SDimitry Andric const bool EndOfTU; 32970b57cec5SDimitry Andric /// Indicates that there is at least one constructor without body. 32980b57cec5SDimitry Andric bool HasUndefinedConstructors; 32990b57cec5SDimitry Andric /// Returns \c CXXNewExpr from given initialization expression. 33000b57cec5SDimitry Andric /// \param E Expression used for initializing pointee in delete-expression. 33010b57cec5SDimitry Andric /// E can be a single-element \c InitListExpr consisting of new-expression. 33020b57cec5SDimitry Andric const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 33030b57cec5SDimitry Andric /// Returns whether member is initialized with mismatching form of 33040b57cec5SDimitry Andric /// \c new either by the member initializer or in-class initialization. 33050b57cec5SDimitry Andric /// 33060b57cec5SDimitry Andric /// If bodies of all constructors are not visible at the end of translation 33070b57cec5SDimitry Andric /// unit or at least one constructor initializes member with the matching 33080b57cec5SDimitry Andric /// form of \c new, mismatch cannot be proven, and this function will return 33090b57cec5SDimitry Andric /// \c NoMismatch. 33100b57cec5SDimitry Andric MismatchResult analyzeMemberExpr(const MemberExpr *ME); 33110b57cec5SDimitry Andric /// Returns whether variable is initialized with mismatching form of 33120b57cec5SDimitry Andric /// \c new. 33130b57cec5SDimitry Andric /// 33140b57cec5SDimitry Andric /// If variable is initialized with matching form of \c new or variable is not 33150b57cec5SDimitry Andric /// initialized with a \c new expression, this function will return true. 33160b57cec5SDimitry Andric /// If variable is initialized with mismatching form of \c new, returns false. 33170b57cec5SDimitry Andric /// \param D Variable to analyze. 33180b57cec5SDimitry Andric bool hasMatchingVarInit(const DeclRefExpr *D); 33190b57cec5SDimitry Andric /// Checks whether the constructor initializes pointee with mismatching 33200b57cec5SDimitry Andric /// form of \c new. 33210b57cec5SDimitry Andric /// 33220b57cec5SDimitry Andric /// Returns true, if member is initialized with matching form of \c new in 33230b57cec5SDimitry Andric /// member initializer list. Returns false, if member is initialized with the 33240b57cec5SDimitry Andric /// matching form of \c new in this constructor's initializer or given 33250b57cec5SDimitry Andric /// constructor isn't defined at the point where delete-expression is seen, or 33260b57cec5SDimitry Andric /// member isn't initialized by the constructor. 33270b57cec5SDimitry Andric bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 33280b57cec5SDimitry Andric /// Checks whether member is initialized with matching form of 33290b57cec5SDimitry Andric /// \c new in member initializer list. 33300b57cec5SDimitry Andric bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 33310b57cec5SDimitry Andric /// Checks whether member is initialized with mismatching form of \c new by 33320b57cec5SDimitry Andric /// in-class initializer. 33330b57cec5SDimitry Andric MismatchResult analyzeInClassInitializer(); 33340b57cec5SDimitry Andric }; 33350b57cec5SDimitry Andric } 33360b57cec5SDimitry Andric 33370b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 33380b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 33390b57cec5SDimitry Andric NewExprs.clear(); 33400b57cec5SDimitry Andric assert(DE && "Expected delete-expression"); 33410b57cec5SDimitry Andric IsArrayForm = DE->isArrayForm(); 33420b57cec5SDimitry Andric const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 33430b57cec5SDimitry Andric if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 33440b57cec5SDimitry Andric return analyzeMemberExpr(ME); 33450b57cec5SDimitry Andric } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 33460b57cec5SDimitry Andric if (!hasMatchingVarInit(D)) 33470b57cec5SDimitry Andric return VarInitMismatches; 33480b57cec5SDimitry Andric } 33490b57cec5SDimitry Andric return NoMismatch; 33500b57cec5SDimitry Andric } 33510b57cec5SDimitry Andric 33520b57cec5SDimitry Andric const CXXNewExpr * 33530b57cec5SDimitry Andric MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 33540b57cec5SDimitry Andric assert(E != nullptr && "Expected a valid initializer expression"); 33550b57cec5SDimitry Andric E = E->IgnoreParenImpCasts(); 33560b57cec5SDimitry Andric if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 33570b57cec5SDimitry Andric if (ILE->getNumInits() == 1) 33580b57cec5SDimitry Andric E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 33590b57cec5SDimitry Andric } 33600b57cec5SDimitry Andric 33610b57cec5SDimitry Andric return dyn_cast_or_null<const CXXNewExpr>(E); 33620b57cec5SDimitry Andric } 33630b57cec5SDimitry Andric 33640b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 33650b57cec5SDimitry Andric const CXXCtorInitializer *CI) { 33660b57cec5SDimitry Andric const CXXNewExpr *NE = nullptr; 33670b57cec5SDimitry Andric if (Field == CI->getMember() && 33680b57cec5SDimitry Andric (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 33690b57cec5SDimitry Andric if (NE->isArray() == IsArrayForm) 33700b57cec5SDimitry Andric return true; 33710b57cec5SDimitry Andric else 33720b57cec5SDimitry Andric NewExprs.push_back(NE); 33730b57cec5SDimitry Andric } 33740b57cec5SDimitry Andric return false; 33750b57cec5SDimitry Andric } 33760b57cec5SDimitry Andric 33770b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 33780b57cec5SDimitry Andric const CXXConstructorDecl *CD) { 33790b57cec5SDimitry Andric if (CD->isImplicit()) 33800b57cec5SDimitry Andric return false; 33810b57cec5SDimitry Andric const FunctionDecl *Definition = CD; 33820b57cec5SDimitry Andric if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 33830b57cec5SDimitry Andric HasUndefinedConstructors = true; 33840b57cec5SDimitry Andric return EndOfTU; 33850b57cec5SDimitry Andric } 33860b57cec5SDimitry Andric for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 33870b57cec5SDimitry Andric if (hasMatchingNewInCtorInit(CI)) 33880b57cec5SDimitry Andric return true; 33890b57cec5SDimitry Andric } 33900b57cec5SDimitry Andric return false; 33910b57cec5SDimitry Andric } 33920b57cec5SDimitry Andric 33930b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 33940b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeInClassInitializer() { 33950b57cec5SDimitry Andric assert(Field != nullptr && "This should be called only for members"); 33960b57cec5SDimitry Andric const Expr *InitExpr = Field->getInClassInitializer(); 33970b57cec5SDimitry Andric if (!InitExpr) 33980b57cec5SDimitry Andric return EndOfTU ? NoMismatch : AnalyzeLater; 33990b57cec5SDimitry Andric if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 34000b57cec5SDimitry Andric if (NE->isArray() != IsArrayForm) { 34010b57cec5SDimitry Andric NewExprs.push_back(NE); 34020b57cec5SDimitry Andric return MemberInitMismatches; 34030b57cec5SDimitry Andric } 34040b57cec5SDimitry Andric } 34050b57cec5SDimitry Andric return NoMismatch; 34060b57cec5SDimitry Andric } 34070b57cec5SDimitry Andric 34080b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 34090b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 34100b57cec5SDimitry Andric bool DeleteWasArrayForm) { 34110b57cec5SDimitry Andric assert(Field != nullptr && "Analysis requires a valid class member."); 34120b57cec5SDimitry Andric this->Field = Field; 34130b57cec5SDimitry Andric IsArrayForm = DeleteWasArrayForm; 34140b57cec5SDimitry Andric const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 34150b57cec5SDimitry Andric for (const auto *CD : RD->ctors()) { 34160b57cec5SDimitry Andric if (hasMatchingNewInCtor(CD)) 34170b57cec5SDimitry Andric return NoMismatch; 34180b57cec5SDimitry Andric } 34190b57cec5SDimitry Andric if (HasUndefinedConstructors) 34200b57cec5SDimitry Andric return EndOfTU ? NoMismatch : AnalyzeLater; 34210b57cec5SDimitry Andric if (!NewExprs.empty()) 34220b57cec5SDimitry Andric return MemberInitMismatches; 34230b57cec5SDimitry Andric return Field->hasInClassInitializer() ? analyzeInClassInitializer() 34240b57cec5SDimitry Andric : NoMismatch; 34250b57cec5SDimitry Andric } 34260b57cec5SDimitry Andric 34270b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 34280b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 34290b57cec5SDimitry Andric assert(ME != nullptr && "Expected a member expression"); 34300b57cec5SDimitry Andric if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 34310b57cec5SDimitry Andric return analyzeField(F, IsArrayForm); 34320b57cec5SDimitry Andric return NoMismatch; 34330b57cec5SDimitry Andric } 34340b57cec5SDimitry Andric 34350b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 34360b57cec5SDimitry Andric const CXXNewExpr *NE = nullptr; 34370b57cec5SDimitry Andric if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 34380b57cec5SDimitry Andric if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 34390b57cec5SDimitry Andric NE->isArray() != IsArrayForm) { 34400b57cec5SDimitry Andric NewExprs.push_back(NE); 34410b57cec5SDimitry Andric } 34420b57cec5SDimitry Andric } 34430b57cec5SDimitry Andric return NewExprs.empty(); 34440b57cec5SDimitry Andric } 34450b57cec5SDimitry Andric 34460b57cec5SDimitry Andric static void 34470b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 34480b57cec5SDimitry Andric const MismatchingNewDeleteDetector &Detector) { 34490b57cec5SDimitry Andric SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 34500b57cec5SDimitry Andric FixItHint H; 34510b57cec5SDimitry Andric if (!Detector.IsArrayForm) 34520b57cec5SDimitry Andric H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 34530b57cec5SDimitry Andric else { 34540b57cec5SDimitry Andric SourceLocation RSquare = Lexer::findLocationAfterToken( 34550b57cec5SDimitry Andric DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 34560b57cec5SDimitry Andric SemaRef.getLangOpts(), true); 34570b57cec5SDimitry Andric if (RSquare.isValid()) 34580b57cec5SDimitry Andric H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 34590b57cec5SDimitry Andric } 34600b57cec5SDimitry Andric SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 34610b57cec5SDimitry Andric << Detector.IsArrayForm << H; 34620b57cec5SDimitry Andric 34630b57cec5SDimitry Andric for (const auto *NE : Detector.NewExprs) 34640b57cec5SDimitry Andric SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 34650b57cec5SDimitry Andric << Detector.IsArrayForm; 34660b57cec5SDimitry Andric } 34670b57cec5SDimitry Andric 34680b57cec5SDimitry Andric void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 34690b57cec5SDimitry Andric if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 34700b57cec5SDimitry Andric return; 34710b57cec5SDimitry Andric MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 34720b57cec5SDimitry Andric switch (Detector.analyzeDeleteExpr(DE)) { 34730b57cec5SDimitry Andric case MismatchingNewDeleteDetector::VarInitMismatches: 34740b57cec5SDimitry Andric case MismatchingNewDeleteDetector::MemberInitMismatches: { 34750b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); 34760b57cec5SDimitry Andric break; 34770b57cec5SDimitry Andric } 34780b57cec5SDimitry Andric case MismatchingNewDeleteDetector::AnalyzeLater: { 34790b57cec5SDimitry Andric DeleteExprs[Detector.Field].push_back( 34800b57cec5SDimitry Andric std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); 34810b57cec5SDimitry Andric break; 34820b57cec5SDimitry Andric } 34830b57cec5SDimitry Andric case MismatchingNewDeleteDetector::NoMismatch: 34840b57cec5SDimitry Andric break; 34850b57cec5SDimitry Andric } 34860b57cec5SDimitry Andric } 34870b57cec5SDimitry Andric 34880b57cec5SDimitry Andric void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 34890b57cec5SDimitry Andric bool DeleteWasArrayForm) { 34900b57cec5SDimitry Andric MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 34910b57cec5SDimitry Andric switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 34920b57cec5SDimitry Andric case MismatchingNewDeleteDetector::VarInitMismatches: 34930b57cec5SDimitry Andric llvm_unreachable("This analysis should have been done for class members."); 34940b57cec5SDimitry Andric case MismatchingNewDeleteDetector::AnalyzeLater: 34950b57cec5SDimitry Andric llvm_unreachable("Analysis cannot be postponed any point beyond end of " 34960b57cec5SDimitry Andric "translation unit."); 34970b57cec5SDimitry Andric case MismatchingNewDeleteDetector::MemberInitMismatches: 34980b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 34990b57cec5SDimitry Andric break; 35000b57cec5SDimitry Andric case MismatchingNewDeleteDetector::NoMismatch: 35010b57cec5SDimitry Andric break; 35020b57cec5SDimitry Andric } 35030b57cec5SDimitry Andric } 35040b57cec5SDimitry Andric 35050b57cec5SDimitry Andric /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 35060b57cec5SDimitry Andric /// @code ::delete ptr; @endcode 35070b57cec5SDimitry Andric /// or 35080b57cec5SDimitry Andric /// @code delete [] ptr; @endcode 35090b57cec5SDimitry Andric ExprResult 35100b57cec5SDimitry Andric Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 35110b57cec5SDimitry Andric bool ArrayForm, Expr *ExE) { 35120b57cec5SDimitry Andric // C++ [expr.delete]p1: 35130b57cec5SDimitry Andric // The operand shall have a pointer type, or a class type having a single 35140b57cec5SDimitry Andric // non-explicit conversion function to a pointer type. The result has type 35150b57cec5SDimitry Andric // void. 35160b57cec5SDimitry Andric // 35170b57cec5SDimitry Andric // DR599 amends "pointer type" to "pointer to object type" in both cases. 35180b57cec5SDimitry Andric 35190b57cec5SDimitry Andric ExprResult Ex = ExE; 35200b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 35210b57cec5SDimitry Andric bool ArrayFormAsWritten = ArrayForm; 35220b57cec5SDimitry Andric bool UsualArrayDeleteWantsSize = false; 35230b57cec5SDimitry Andric 35240b57cec5SDimitry Andric if (!Ex.get()->isTypeDependent()) { 35250b57cec5SDimitry Andric // Perform lvalue-to-rvalue cast, if needed. 35260b57cec5SDimitry Andric Ex = DefaultLvalueConversion(Ex.get()); 35270b57cec5SDimitry Andric if (Ex.isInvalid()) 35280b57cec5SDimitry Andric return ExprError(); 35290b57cec5SDimitry Andric 35300b57cec5SDimitry Andric QualType Type = Ex.get()->getType(); 35310b57cec5SDimitry Andric 35320b57cec5SDimitry Andric class DeleteConverter : public ContextualImplicitConverter { 35330b57cec5SDimitry Andric public: 35340b57cec5SDimitry Andric DeleteConverter() : ContextualImplicitConverter(false, true) {} 35350b57cec5SDimitry Andric 35360b57cec5SDimitry Andric bool match(QualType ConvType) override { 35370b57cec5SDimitry Andric // FIXME: If we have an operator T* and an operator void*, we must pick 35380b57cec5SDimitry Andric // the operator T*. 35390b57cec5SDimitry Andric if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 35400b57cec5SDimitry Andric if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 35410b57cec5SDimitry Andric return true; 35420b57cec5SDimitry Andric return false; 35430b57cec5SDimitry Andric } 35440b57cec5SDimitry Andric 35450b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 35460b57cec5SDimitry Andric QualType T) override { 35470b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_operand) << T; 35480b57cec5SDimitry Andric } 35490b57cec5SDimitry Andric 35500b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 35510b57cec5SDimitry Andric QualType T) override { 35520b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 35530b57cec5SDimitry Andric } 35540b57cec5SDimitry Andric 35550b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 35560b57cec5SDimitry Andric QualType T, 35570b57cec5SDimitry Andric QualType ConvTy) override { 35580b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 35590b57cec5SDimitry Andric } 35600b57cec5SDimitry Andric 35610b57cec5SDimitry Andric SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 35620b57cec5SDimitry Andric QualType ConvTy) override { 35630b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 35640b57cec5SDimitry Andric << ConvTy; 35650b57cec5SDimitry Andric } 35660b57cec5SDimitry Andric 35670b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 35680b57cec5SDimitry Andric QualType T) override { 35690b57cec5SDimitry Andric return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 35700b57cec5SDimitry Andric } 35710b57cec5SDimitry Andric 35720b57cec5SDimitry Andric SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 35730b57cec5SDimitry Andric QualType ConvTy) override { 35740b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 35750b57cec5SDimitry Andric << ConvTy; 35760b57cec5SDimitry Andric } 35770b57cec5SDimitry Andric 35780b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 35790b57cec5SDimitry Andric QualType T, 35800b57cec5SDimitry Andric QualType ConvTy) override { 35810b57cec5SDimitry Andric llvm_unreachable("conversion functions are permitted"); 35820b57cec5SDimitry Andric } 35830b57cec5SDimitry Andric } Converter; 35840b57cec5SDimitry Andric 35850b57cec5SDimitry Andric Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 35860b57cec5SDimitry Andric if (Ex.isInvalid()) 35870b57cec5SDimitry Andric return ExprError(); 35880b57cec5SDimitry Andric Type = Ex.get()->getType(); 35890b57cec5SDimitry Andric if (!Converter.match(Type)) 35900b57cec5SDimitry Andric // FIXME: PerformContextualImplicitConversion should return ExprError 35910b57cec5SDimitry Andric // itself in this case. 35920b57cec5SDimitry Andric return ExprError(); 35930b57cec5SDimitry Andric 3594a7dea167SDimitry Andric QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); 35950b57cec5SDimitry Andric QualType PointeeElem = Context.getBaseElementType(Pointee); 35960b57cec5SDimitry Andric 35970b57cec5SDimitry Andric if (Pointee.getAddressSpace() != LangAS::Default && 35980b57cec5SDimitry Andric !getLangOpts().OpenCLCPlusPlus) 35990b57cec5SDimitry Andric return Diag(Ex.get()->getBeginLoc(), 36000b57cec5SDimitry Andric diag::err_address_space_qualified_delete) 36010b57cec5SDimitry Andric << Pointee.getUnqualifiedType() 36020b57cec5SDimitry Andric << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); 36030b57cec5SDimitry Andric 36040b57cec5SDimitry Andric CXXRecordDecl *PointeeRD = nullptr; 36050b57cec5SDimitry Andric if (Pointee->isVoidType() && !isSFINAEContext()) { 36060b57cec5SDimitry Andric // The C++ standard bans deleting a pointer to a non-object type, which 36070b57cec5SDimitry Andric // effectively bans deletion of "void*". However, most compilers support 36080b57cec5SDimitry Andric // this, so we treat it as a warning unless we're in a SFINAE context. 36090b57cec5SDimitry Andric Diag(StartLoc, diag::ext_delete_void_ptr_operand) 36100b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange(); 36115ffd83dbSDimitry Andric } else if (Pointee->isFunctionType() || Pointee->isVoidType() || 36125ffd83dbSDimitry Andric Pointee->isSizelessType()) { 36130b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_delete_operand) 36140b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange()); 36150b57cec5SDimitry Andric } else if (!Pointee->isDependentType()) { 36160b57cec5SDimitry Andric // FIXME: This can result in errors if the definition was imported from a 36170b57cec5SDimitry Andric // module but is hidden. 36180b57cec5SDimitry Andric if (!RequireCompleteType(StartLoc, Pointee, 36190b57cec5SDimitry Andric diag::warn_delete_incomplete, Ex.get())) { 36200b57cec5SDimitry Andric if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 36210b57cec5SDimitry Andric PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 36220b57cec5SDimitry Andric } 36230b57cec5SDimitry Andric } 36240b57cec5SDimitry Andric 36250b57cec5SDimitry Andric if (Pointee->isArrayType() && !ArrayForm) { 36260b57cec5SDimitry Andric Diag(StartLoc, diag::warn_delete_array_type) 36270b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange() 36280b57cec5SDimitry Andric << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 36290b57cec5SDimitry Andric ArrayForm = true; 36300b57cec5SDimitry Andric } 36310b57cec5SDimitry Andric 36320b57cec5SDimitry Andric DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 36330b57cec5SDimitry Andric ArrayForm ? OO_Array_Delete : OO_Delete); 36340b57cec5SDimitry Andric 36350b57cec5SDimitry Andric if (PointeeRD) { 36360b57cec5SDimitry Andric if (!UseGlobal && 36370b57cec5SDimitry Andric FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 36380b57cec5SDimitry Andric OperatorDelete)) 36390b57cec5SDimitry Andric return ExprError(); 36400b57cec5SDimitry Andric 36410b57cec5SDimitry Andric // If we're allocating an array of records, check whether the 36420b57cec5SDimitry Andric // usual operator delete[] has a size_t parameter. 36430b57cec5SDimitry Andric if (ArrayForm) { 36440b57cec5SDimitry Andric // If the user specifically asked to use the global allocator, 36450b57cec5SDimitry Andric // we'll need to do the lookup into the class. 36460b57cec5SDimitry Andric if (UseGlobal) 36470b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 36480b57cec5SDimitry Andric doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 36490b57cec5SDimitry Andric 36500b57cec5SDimitry Andric // Otherwise, the usual operator delete[] should be the 36510b57cec5SDimitry Andric // function we just found. 36520b57cec5SDimitry Andric else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 36530b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 36540b57cec5SDimitry Andric UsualDeallocFnInfo(*this, 36550b57cec5SDimitry Andric DeclAccessPair::make(OperatorDelete, AS_public)) 36560b57cec5SDimitry Andric .HasSizeT; 36570b57cec5SDimitry Andric } 36580b57cec5SDimitry Andric 36590b57cec5SDimitry Andric if (!PointeeRD->hasIrrelevantDestructor()) 36600b57cec5SDimitry Andric if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 36610b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, 36620b57cec5SDimitry Andric const_cast<CXXDestructorDecl*>(Dtor)); 36630b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Dtor, StartLoc)) 36640b57cec5SDimitry Andric return ExprError(); 36650b57cec5SDimitry Andric } 36660b57cec5SDimitry Andric 36670b57cec5SDimitry Andric CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 36680b57cec5SDimitry Andric /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 36690b57cec5SDimitry Andric /*WarnOnNonAbstractTypes=*/!ArrayForm, 36700b57cec5SDimitry Andric SourceLocation()); 36710b57cec5SDimitry Andric } 36720b57cec5SDimitry Andric 36730b57cec5SDimitry Andric if (!OperatorDelete) { 36740b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) { 36750b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; 36760b57cec5SDimitry Andric return ExprError(); 36770b57cec5SDimitry Andric } 36780b57cec5SDimitry Andric 36790b57cec5SDimitry Andric bool IsComplete = isCompleteType(StartLoc, Pointee); 36800b57cec5SDimitry Andric bool CanProvideSize = 36810b57cec5SDimitry Andric IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 36820b57cec5SDimitry Andric Pointee.isDestructedType()); 36830b57cec5SDimitry Andric bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 36840b57cec5SDimitry Andric 36850b57cec5SDimitry Andric // Look for a global declaration. 36860b57cec5SDimitry Andric OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 36870b57cec5SDimitry Andric Overaligned, DeleteName); 36880b57cec5SDimitry Andric } 36890b57cec5SDimitry Andric 36900b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorDelete); 36910b57cec5SDimitry Andric 36920b57cec5SDimitry Andric // Check access and ambiguity of destructor if we're going to call it. 36930b57cec5SDimitry Andric // Note that this is required even for a virtual delete. 36940b57cec5SDimitry Andric bool IsVirtualDelete = false; 36950b57cec5SDimitry Andric if (PointeeRD) { 36960b57cec5SDimitry Andric if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 36970b57cec5SDimitry Andric CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 36980b57cec5SDimitry Andric PDiag(diag::err_access_dtor) << PointeeElem); 36990b57cec5SDimitry Andric IsVirtualDelete = Dtor->isVirtual(); 37000b57cec5SDimitry Andric } 37010b57cec5SDimitry Andric } 37020b57cec5SDimitry Andric 37030b57cec5SDimitry Andric DiagnoseUseOfDecl(OperatorDelete, StartLoc); 37040b57cec5SDimitry Andric 37050b57cec5SDimitry Andric // Convert the operand to the type of the first parameter of operator 37060b57cec5SDimitry Andric // delete. This is only necessary if we selected a destroying operator 37070b57cec5SDimitry Andric // delete that we are going to call (non-virtually); converting to void* 37080b57cec5SDimitry Andric // is trivial and left to AST consumers to handle. 37090b57cec5SDimitry Andric QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 37100b57cec5SDimitry Andric if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { 37110b57cec5SDimitry Andric Qualifiers Qs = Pointee.getQualifiers(); 37120b57cec5SDimitry Andric if (Qs.hasCVRQualifiers()) { 37130b57cec5SDimitry Andric // Qualifiers are irrelevant to this conversion; we're only looking 37140b57cec5SDimitry Andric // for access and ambiguity. 37150b57cec5SDimitry Andric Qs.removeCVRQualifiers(); 37160b57cec5SDimitry Andric QualType Unqual = Context.getPointerType( 37170b57cec5SDimitry Andric Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); 37180b57cec5SDimitry Andric Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); 37190b57cec5SDimitry Andric } 37200b57cec5SDimitry Andric Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); 37210b57cec5SDimitry Andric if (Ex.isInvalid()) 37220b57cec5SDimitry Andric return ExprError(); 37230b57cec5SDimitry Andric } 37240b57cec5SDimitry Andric } 37250b57cec5SDimitry Andric 37260b57cec5SDimitry Andric CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 37270b57cec5SDimitry Andric Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 37280b57cec5SDimitry Andric UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 37290b57cec5SDimitry Andric AnalyzeDeleteExprMismatch(Result); 37300b57cec5SDimitry Andric return Result; 37310b57cec5SDimitry Andric } 37320b57cec5SDimitry Andric 37330b57cec5SDimitry Andric static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, 37340b57cec5SDimitry Andric bool IsDelete, 37350b57cec5SDimitry Andric FunctionDecl *&Operator) { 37360b57cec5SDimitry Andric 37370b57cec5SDimitry Andric DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( 37380b57cec5SDimitry Andric IsDelete ? OO_Delete : OO_New); 37390b57cec5SDimitry Andric 37400b57cec5SDimitry Andric LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); 37410b57cec5SDimitry Andric S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 37420b57cec5SDimitry Andric assert(!R.empty() && "implicitly declared allocation functions not found"); 37430b57cec5SDimitry Andric assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 37440b57cec5SDimitry Andric 37450b57cec5SDimitry Andric // We do our own custom access checks below. 37460b57cec5SDimitry Andric R.suppressDiagnostics(); 37470b57cec5SDimitry Andric 374881ad6265SDimitry Andric SmallVector<Expr *, 8> Args(TheCall->arguments()); 37490b57cec5SDimitry Andric OverloadCandidateSet Candidates(R.getNameLoc(), 37500b57cec5SDimitry Andric OverloadCandidateSet::CSK_Normal); 37510b57cec5SDimitry Andric for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); 37520b57cec5SDimitry Andric FnOvl != FnOvlEnd; ++FnOvl) { 37530b57cec5SDimitry Andric // Even member operator new/delete are implicitly treated as 37540b57cec5SDimitry Andric // static, so don't use AddMemberCandidate. 37550b57cec5SDimitry Andric NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); 37560b57cec5SDimitry Andric 37570b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 37580b57cec5SDimitry Andric S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), 37590b57cec5SDimitry Andric /*ExplicitTemplateArgs=*/nullptr, Args, 37600b57cec5SDimitry Andric Candidates, 37610b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 37620b57cec5SDimitry Andric continue; 37630b57cec5SDimitry Andric } 37640b57cec5SDimitry Andric 37650b57cec5SDimitry Andric FunctionDecl *Fn = cast<FunctionDecl>(D); 37660b57cec5SDimitry Andric S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, 37670b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 37680b57cec5SDimitry Andric } 37690b57cec5SDimitry Andric 37700b57cec5SDimitry Andric SourceRange Range = TheCall->getSourceRange(); 37710b57cec5SDimitry Andric 37720b57cec5SDimitry Andric // Do the resolution. 37730b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 37740b57cec5SDimitry Andric switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 37750b57cec5SDimitry Andric case OR_Success: { 37760b57cec5SDimitry Andric // Got one! 37770b57cec5SDimitry Andric FunctionDecl *FnDecl = Best->Function; 37780b57cec5SDimitry Andric assert(R.getNamingClass() == nullptr && 37790b57cec5SDimitry Andric "class members should not be considered"); 37800b57cec5SDimitry Andric 37810b57cec5SDimitry Andric if (!FnDecl->isReplaceableGlobalAllocationFunction()) { 37820b57cec5SDimitry Andric S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) 37830b57cec5SDimitry Andric << (IsDelete ? 1 : 0) << Range; 37840b57cec5SDimitry Andric S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) 37850b57cec5SDimitry Andric << R.getLookupName() << FnDecl->getSourceRange(); 37860b57cec5SDimitry Andric return true; 37870b57cec5SDimitry Andric } 37880b57cec5SDimitry Andric 37890b57cec5SDimitry Andric Operator = FnDecl; 37900b57cec5SDimitry Andric return false; 37910b57cec5SDimitry Andric } 37920b57cec5SDimitry Andric 37930b57cec5SDimitry Andric case OR_No_Viable_Function: 37940b57cec5SDimitry Andric Candidates.NoteCandidates( 37950b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 37960b57cec5SDimitry Andric S.PDiag(diag::err_ovl_no_viable_function_in_call) 37970b57cec5SDimitry Andric << R.getLookupName() << Range), 37980b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 37990b57cec5SDimitry Andric return true; 38000b57cec5SDimitry Andric 38010b57cec5SDimitry Andric case OR_Ambiguous: 38020b57cec5SDimitry Andric Candidates.NoteCandidates( 38030b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 38040b57cec5SDimitry Andric S.PDiag(diag::err_ovl_ambiguous_call) 38050b57cec5SDimitry Andric << R.getLookupName() << Range), 3806480093f4SDimitry Andric S, OCD_AmbiguousCandidates, Args); 38070b57cec5SDimitry Andric return true; 38080b57cec5SDimitry Andric 38090b57cec5SDimitry Andric case OR_Deleted: { 38100b57cec5SDimitry Andric Candidates.NoteCandidates( 38110b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) 38120b57cec5SDimitry Andric << R.getLookupName() << Range), 38130b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 38140b57cec5SDimitry Andric return true; 38150b57cec5SDimitry Andric } 38160b57cec5SDimitry Andric } 38170b57cec5SDimitry Andric llvm_unreachable("Unreachable, bad result from BestViableFunction"); 38180b57cec5SDimitry Andric } 38190b57cec5SDimitry Andric 38200b57cec5SDimitry Andric ExprResult 38210b57cec5SDimitry Andric Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 38220b57cec5SDimitry Andric bool IsDelete) { 38230b57cec5SDimitry Andric CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 38240b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) { 38250b57cec5SDimitry Andric Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 38260b57cec5SDimitry Andric << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") 38270b57cec5SDimitry Andric << "C++"; 38280b57cec5SDimitry Andric return ExprError(); 38290b57cec5SDimitry Andric } 38300b57cec5SDimitry Andric // CodeGen assumes it can find the global new and delete to call, 38310b57cec5SDimitry Andric // so ensure that they are declared. 38320b57cec5SDimitry Andric DeclareGlobalNewDelete(); 38330b57cec5SDimitry Andric 38340b57cec5SDimitry Andric FunctionDecl *OperatorNewOrDelete = nullptr; 38350b57cec5SDimitry Andric if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, 38360b57cec5SDimitry Andric OperatorNewOrDelete)) 38370b57cec5SDimitry Andric return ExprError(); 38380b57cec5SDimitry Andric assert(OperatorNewOrDelete && "should be found"); 38390b57cec5SDimitry Andric 38400b57cec5SDimitry Andric DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); 38410b57cec5SDimitry Andric MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); 38420b57cec5SDimitry Andric 38430b57cec5SDimitry Andric TheCall->setType(OperatorNewOrDelete->getReturnType()); 38440b57cec5SDimitry Andric for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 38450b57cec5SDimitry Andric QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); 38460b57cec5SDimitry Andric InitializedEntity Entity = 38470b57cec5SDimitry Andric InitializedEntity::InitializeParameter(Context, ParamTy, false); 38480b57cec5SDimitry Andric ExprResult Arg = PerformCopyInitialization( 38490b57cec5SDimitry Andric Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); 38500b57cec5SDimitry Andric if (Arg.isInvalid()) 38510b57cec5SDimitry Andric return ExprError(); 38520b57cec5SDimitry Andric TheCall->setArg(i, Arg.get()); 38530b57cec5SDimitry Andric } 38540b57cec5SDimitry Andric auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); 38550b57cec5SDimitry Andric assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && 38560b57cec5SDimitry Andric "Callee expected to be implicit cast to a builtin function pointer"); 38570b57cec5SDimitry Andric Callee->setType(OperatorNewOrDelete->getType()); 38580b57cec5SDimitry Andric 38590b57cec5SDimitry Andric return TheCallResult; 38600b57cec5SDimitry Andric } 38610b57cec5SDimitry Andric 38620b57cec5SDimitry Andric void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 38630b57cec5SDimitry Andric bool IsDelete, bool CallCanBeVirtual, 38640b57cec5SDimitry Andric bool WarnOnNonAbstractTypes, 38650b57cec5SDimitry Andric SourceLocation DtorLoc) { 38660b57cec5SDimitry Andric if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) 38670b57cec5SDimitry Andric return; 38680b57cec5SDimitry Andric 38690b57cec5SDimitry Andric // C++ [expr.delete]p3: 38700b57cec5SDimitry Andric // In the first alternative (delete object), if the static type of the 38710b57cec5SDimitry Andric // object to be deleted is different from its dynamic type, the static 38720b57cec5SDimitry Andric // type shall be a base class of the dynamic type of the object to be 38730b57cec5SDimitry Andric // deleted and the static type shall have a virtual destructor or the 38740b57cec5SDimitry Andric // behavior is undefined. 38750b57cec5SDimitry Andric // 38760b57cec5SDimitry Andric const CXXRecordDecl *PointeeRD = dtor->getParent(); 38770b57cec5SDimitry Andric // Note: a final class cannot be derived from, no issue there 38780b57cec5SDimitry Andric if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 38790b57cec5SDimitry Andric return; 38800b57cec5SDimitry Andric 38810b57cec5SDimitry Andric // If the superclass is in a system header, there's nothing that can be done. 38820b57cec5SDimitry Andric // The `delete` (where we emit the warning) can be in a system header, 38830b57cec5SDimitry Andric // what matters for this warning is where the deleted type is defined. 38840b57cec5SDimitry Andric if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) 38850b57cec5SDimitry Andric return; 38860b57cec5SDimitry Andric 38870b57cec5SDimitry Andric QualType ClassType = dtor->getThisType()->getPointeeType(); 38880b57cec5SDimitry Andric if (PointeeRD->isAbstract()) { 38890b57cec5SDimitry Andric // If the class is abstract, we warn by default, because we're 38900b57cec5SDimitry Andric // sure the code has undefined behavior. 38910b57cec5SDimitry Andric Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 38920b57cec5SDimitry Andric << ClassType; 38930b57cec5SDimitry Andric } else if (WarnOnNonAbstractTypes) { 38940b57cec5SDimitry Andric // Otherwise, if this is not an array delete, it's a bit suspect, 38950b57cec5SDimitry Andric // but not necessarily wrong. 38960b57cec5SDimitry Andric Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 38970b57cec5SDimitry Andric << ClassType; 38980b57cec5SDimitry Andric } 38990b57cec5SDimitry Andric if (!IsDelete) { 39000b57cec5SDimitry Andric std::string TypeStr; 39010b57cec5SDimitry Andric ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 39020b57cec5SDimitry Andric Diag(DtorLoc, diag::note_delete_non_virtual) 39030b57cec5SDimitry Andric << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 39040b57cec5SDimitry Andric } 39050b57cec5SDimitry Andric } 39060b57cec5SDimitry Andric 39070b57cec5SDimitry Andric Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 39080b57cec5SDimitry Andric SourceLocation StmtLoc, 39090b57cec5SDimitry Andric ConditionKind CK) { 39100b57cec5SDimitry Andric ExprResult E = 39110b57cec5SDimitry Andric CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 39120b57cec5SDimitry Andric if (E.isInvalid()) 39130b57cec5SDimitry Andric return ConditionError(); 39140b57cec5SDimitry Andric return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 39150b57cec5SDimitry Andric CK == ConditionKind::ConstexprIf); 39160b57cec5SDimitry Andric } 39170b57cec5SDimitry Andric 39180b57cec5SDimitry Andric /// Check the use of the given variable as a C++ condition in an if, 39190b57cec5SDimitry Andric /// while, do-while, or switch statement. 39200b57cec5SDimitry Andric ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 39210b57cec5SDimitry Andric SourceLocation StmtLoc, 39220b57cec5SDimitry Andric ConditionKind CK) { 39230b57cec5SDimitry Andric if (ConditionVar->isInvalidDecl()) 39240b57cec5SDimitry Andric return ExprError(); 39250b57cec5SDimitry Andric 39260b57cec5SDimitry Andric QualType T = ConditionVar->getType(); 39270b57cec5SDimitry Andric 39280b57cec5SDimitry Andric // C++ [stmt.select]p2: 39290b57cec5SDimitry Andric // The declarator shall not specify a function or an array. 39300b57cec5SDimitry Andric if (T->isFunctionType()) 39310b57cec5SDimitry Andric return ExprError(Diag(ConditionVar->getLocation(), 39320b57cec5SDimitry Andric diag::err_invalid_use_of_function_type) 39330b57cec5SDimitry Andric << ConditionVar->getSourceRange()); 39340b57cec5SDimitry Andric else if (T->isArrayType()) 39350b57cec5SDimitry Andric return ExprError(Diag(ConditionVar->getLocation(), 39360b57cec5SDimitry Andric diag::err_invalid_use_of_array_type) 39370b57cec5SDimitry Andric << ConditionVar->getSourceRange()); 39380b57cec5SDimitry Andric 39390b57cec5SDimitry Andric ExprResult Condition = BuildDeclRefExpr( 39400b57cec5SDimitry Andric ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, 39410b57cec5SDimitry Andric ConditionVar->getLocation()); 39420b57cec5SDimitry Andric 39430b57cec5SDimitry Andric switch (CK) { 39440b57cec5SDimitry Andric case ConditionKind::Boolean: 39450b57cec5SDimitry Andric return CheckBooleanCondition(StmtLoc, Condition.get()); 39460b57cec5SDimitry Andric 39470b57cec5SDimitry Andric case ConditionKind::ConstexprIf: 39480b57cec5SDimitry Andric return CheckBooleanCondition(StmtLoc, Condition.get(), true); 39490b57cec5SDimitry Andric 39500b57cec5SDimitry Andric case ConditionKind::Switch: 39510b57cec5SDimitry Andric return CheckSwitchCondition(StmtLoc, Condition.get()); 39520b57cec5SDimitry Andric } 39530b57cec5SDimitry Andric 39540b57cec5SDimitry Andric llvm_unreachable("unexpected condition kind"); 39550b57cec5SDimitry Andric } 39560b57cec5SDimitry Andric 39570b57cec5SDimitry Andric /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 39580b57cec5SDimitry Andric ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 3959fe6060f1SDimitry Andric // C++11 6.4p4: 39600b57cec5SDimitry Andric // The value of a condition that is an initialized declaration in a statement 39610b57cec5SDimitry Andric // other than a switch statement is the value of the declared variable 39620b57cec5SDimitry Andric // implicitly converted to type bool. If that conversion is ill-formed, the 39630b57cec5SDimitry Andric // program is ill-formed. 39640b57cec5SDimitry Andric // The value of a condition that is an expression is the value of the 39650b57cec5SDimitry Andric // expression, implicitly converted to bool. 39660b57cec5SDimitry Andric // 3967fe6060f1SDimitry Andric // C++2b 8.5.2p2 3968fe6060f1SDimitry Andric // If the if statement is of the form if constexpr, the value of the condition 3969fe6060f1SDimitry Andric // is contextually converted to bool and the converted expression shall be 3970fe6060f1SDimitry Andric // a constant expression. 3971fe6060f1SDimitry Andric // 3972fe6060f1SDimitry Andric 3973fe6060f1SDimitry Andric ExprResult E = PerformContextuallyConvertToBool(CondExpr); 3974fe6060f1SDimitry Andric if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent()) 3975fe6060f1SDimitry Andric return E; 3976fe6060f1SDimitry Andric 39770b57cec5SDimitry Andric // FIXME: Return this value to the caller so they don't need to recompute it. 3978fe6060f1SDimitry Andric llvm::APSInt Cond; 3979fe6060f1SDimitry Andric E = VerifyIntegerConstantExpression( 3980fe6060f1SDimitry Andric E.get(), &Cond, 3981fe6060f1SDimitry Andric diag::err_constexpr_if_condition_expression_is_not_constant); 3982fe6060f1SDimitry Andric return E; 39830b57cec5SDimitry Andric } 39840b57cec5SDimitry Andric 39850b57cec5SDimitry Andric /// Helper function to determine whether this is the (deprecated) C++ 39860b57cec5SDimitry Andric /// conversion from a string literal to a pointer to non-const char or 39870b57cec5SDimitry Andric /// non-const wchar_t (for narrow and wide string literals, 39880b57cec5SDimitry Andric /// respectively). 39890b57cec5SDimitry Andric bool 39900b57cec5SDimitry Andric Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 39910b57cec5SDimitry Andric // Look inside the implicit cast, if it exists. 39920b57cec5SDimitry Andric if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 39930b57cec5SDimitry Andric From = Cast->getSubExpr(); 39940b57cec5SDimitry Andric 39950b57cec5SDimitry Andric // A string literal (2.13.4) that is not a wide string literal can 39960b57cec5SDimitry Andric // be converted to an rvalue of type "pointer to char"; a wide 39970b57cec5SDimitry Andric // string literal can be converted to an rvalue of type "pointer 39980b57cec5SDimitry Andric // to wchar_t" (C++ 4.2p2). 39990b57cec5SDimitry Andric if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 40000b57cec5SDimitry Andric if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 40010b57cec5SDimitry Andric if (const BuiltinType *ToPointeeType 40020b57cec5SDimitry Andric = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 40030b57cec5SDimitry Andric // This conversion is considered only when there is an 40040b57cec5SDimitry Andric // explicit appropriate pointer target type (C++ 4.2p2). 40050b57cec5SDimitry Andric if (!ToPtrType->getPointeeType().hasQualifiers()) { 40060b57cec5SDimitry Andric switch (StrLit->getKind()) { 40070b57cec5SDimitry Andric case StringLiteral::UTF8: 40080b57cec5SDimitry Andric case StringLiteral::UTF16: 40090b57cec5SDimitry Andric case StringLiteral::UTF32: 40100b57cec5SDimitry Andric // We don't allow UTF literals to be implicitly converted 40110b57cec5SDimitry Andric break; 401281ad6265SDimitry Andric case StringLiteral::Ordinary: 40130b57cec5SDimitry Andric return (ToPointeeType->getKind() == BuiltinType::Char_U || 40140b57cec5SDimitry Andric ToPointeeType->getKind() == BuiltinType::Char_S); 40150b57cec5SDimitry Andric case StringLiteral::Wide: 40160b57cec5SDimitry Andric return Context.typesAreCompatible(Context.getWideCharType(), 40170b57cec5SDimitry Andric QualType(ToPointeeType, 0)); 40180b57cec5SDimitry Andric } 40190b57cec5SDimitry Andric } 40200b57cec5SDimitry Andric } 40210b57cec5SDimitry Andric 40220b57cec5SDimitry Andric return false; 40230b57cec5SDimitry Andric } 40240b57cec5SDimitry Andric 40250b57cec5SDimitry Andric static ExprResult BuildCXXCastArgument(Sema &S, 40260b57cec5SDimitry Andric SourceLocation CastLoc, 40270b57cec5SDimitry Andric QualType Ty, 40280b57cec5SDimitry Andric CastKind Kind, 40290b57cec5SDimitry Andric CXXMethodDecl *Method, 40300b57cec5SDimitry Andric DeclAccessPair FoundDecl, 40310b57cec5SDimitry Andric bool HadMultipleCandidates, 40320b57cec5SDimitry Andric Expr *From) { 40330b57cec5SDimitry Andric switch (Kind) { 40340b57cec5SDimitry Andric default: llvm_unreachable("Unhandled cast kind!"); 40350b57cec5SDimitry Andric case CK_ConstructorConversion: { 40360b57cec5SDimitry Andric CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 40370b57cec5SDimitry Andric SmallVector<Expr*, 8> ConstructorArgs; 40380b57cec5SDimitry Andric 40390b57cec5SDimitry Andric if (S.RequireNonAbstractType(CastLoc, Ty, 40400b57cec5SDimitry Andric diag::err_allocation_of_abstract_type)) 40410b57cec5SDimitry Andric return ExprError(); 40420b57cec5SDimitry Andric 4043fe6060f1SDimitry Andric if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc, 4044fe6060f1SDimitry Andric ConstructorArgs)) 40450b57cec5SDimitry Andric return ExprError(); 40460b57cec5SDimitry Andric 40470b57cec5SDimitry Andric S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 40480b57cec5SDimitry Andric InitializedEntity::InitializeTemporary(Ty)); 40490b57cec5SDimitry Andric if (S.DiagnoseUseOfDecl(Method, CastLoc)) 40500b57cec5SDimitry Andric return ExprError(); 40510b57cec5SDimitry Andric 40520b57cec5SDimitry Andric ExprResult Result = S.BuildCXXConstructExpr( 40530b57cec5SDimitry Andric CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 40540b57cec5SDimitry Andric ConstructorArgs, HadMultipleCandidates, 40550b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 40560b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 40570b57cec5SDimitry Andric if (Result.isInvalid()) 40580b57cec5SDimitry Andric return ExprError(); 40590b57cec5SDimitry Andric 40600b57cec5SDimitry Andric return S.MaybeBindToTemporary(Result.getAs<Expr>()); 40610b57cec5SDimitry Andric } 40620b57cec5SDimitry Andric 40630b57cec5SDimitry Andric case CK_UserDefinedConversion: { 40640b57cec5SDimitry Andric assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 40650b57cec5SDimitry Andric 40660b57cec5SDimitry Andric S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 40670b57cec5SDimitry Andric if (S.DiagnoseUseOfDecl(Method, CastLoc)) 40680b57cec5SDimitry Andric return ExprError(); 40690b57cec5SDimitry Andric 40700b57cec5SDimitry Andric // Create an implicit call expr that calls it. 40710b57cec5SDimitry Andric CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 40720b57cec5SDimitry Andric ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 40730b57cec5SDimitry Andric HadMultipleCandidates); 40740b57cec5SDimitry Andric if (Result.isInvalid()) 40750b57cec5SDimitry Andric return ExprError(); 40760b57cec5SDimitry Andric // Record usage of conversion in an implicit cast. 40770b57cec5SDimitry Andric Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 40780b57cec5SDimitry Andric CK_UserDefinedConversion, Result.get(), 4079e8d8bef9SDimitry Andric nullptr, Result.get()->getValueKind(), 4080e8d8bef9SDimitry Andric S.CurFPFeatureOverrides()); 40810b57cec5SDimitry Andric 40820b57cec5SDimitry Andric return S.MaybeBindToTemporary(Result.get()); 40830b57cec5SDimitry Andric } 40840b57cec5SDimitry Andric } 40850b57cec5SDimitry Andric } 40860b57cec5SDimitry Andric 40870b57cec5SDimitry Andric /// PerformImplicitConversion - Perform an implicit conversion of the 40880b57cec5SDimitry Andric /// expression From to the type ToType using the pre-computed implicit 40890b57cec5SDimitry Andric /// conversion sequence ICS. Returns the converted 40900b57cec5SDimitry Andric /// expression. Action is the kind of conversion we're performing, 40910b57cec5SDimitry Andric /// used in the error message. 40920b57cec5SDimitry Andric ExprResult 40930b57cec5SDimitry Andric Sema::PerformImplicitConversion(Expr *From, QualType ToType, 40940b57cec5SDimitry Andric const ImplicitConversionSequence &ICS, 40950b57cec5SDimitry Andric AssignmentAction Action, 40960b57cec5SDimitry Andric CheckedConversionKind CCK) { 40970b57cec5SDimitry Andric // C++ [over.match.oper]p7: [...] operands of class type are converted [...] 40980b57cec5SDimitry Andric if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) 40990b57cec5SDimitry Andric return From; 41000b57cec5SDimitry Andric 41010b57cec5SDimitry Andric switch (ICS.getKind()) { 41020b57cec5SDimitry Andric case ImplicitConversionSequence::StandardConversion: { 41030b57cec5SDimitry Andric ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 41040b57cec5SDimitry Andric Action, CCK); 41050b57cec5SDimitry Andric if (Res.isInvalid()) 41060b57cec5SDimitry Andric return ExprError(); 41070b57cec5SDimitry Andric From = Res.get(); 41080b57cec5SDimitry Andric break; 41090b57cec5SDimitry Andric } 41100b57cec5SDimitry Andric 41110b57cec5SDimitry Andric case ImplicitConversionSequence::UserDefinedConversion: { 41120b57cec5SDimitry Andric 41130b57cec5SDimitry Andric FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 41140b57cec5SDimitry Andric CastKind CastKind; 41150b57cec5SDimitry Andric QualType BeforeToType; 41160b57cec5SDimitry Andric assert(FD && "no conversion function for user-defined conversion seq"); 41170b57cec5SDimitry Andric if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 41180b57cec5SDimitry Andric CastKind = CK_UserDefinedConversion; 41190b57cec5SDimitry Andric 41200b57cec5SDimitry Andric // If the user-defined conversion is specified by a conversion function, 41210b57cec5SDimitry Andric // the initial standard conversion sequence converts the source type to 41220b57cec5SDimitry Andric // the implicit object parameter of the conversion function. 41230b57cec5SDimitry Andric BeforeToType = Context.getTagDeclType(Conv->getParent()); 41240b57cec5SDimitry Andric } else { 41250b57cec5SDimitry Andric const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 41260b57cec5SDimitry Andric CastKind = CK_ConstructorConversion; 41270b57cec5SDimitry Andric // Do no conversion if dealing with ... for the first conversion. 41280b57cec5SDimitry Andric if (!ICS.UserDefined.EllipsisConversion) { 41290b57cec5SDimitry Andric // If the user-defined conversion is specified by a constructor, the 41300b57cec5SDimitry Andric // initial standard conversion sequence converts the source type to 41310b57cec5SDimitry Andric // the type required by the argument of the constructor 41320b57cec5SDimitry Andric BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 41330b57cec5SDimitry Andric } 41340b57cec5SDimitry Andric } 41350b57cec5SDimitry Andric // Watch out for ellipsis conversion. 41360b57cec5SDimitry Andric if (!ICS.UserDefined.EllipsisConversion) { 41370b57cec5SDimitry Andric ExprResult Res = 41380b57cec5SDimitry Andric PerformImplicitConversion(From, BeforeToType, 41390b57cec5SDimitry Andric ICS.UserDefined.Before, AA_Converting, 41400b57cec5SDimitry Andric CCK); 41410b57cec5SDimitry Andric if (Res.isInvalid()) 41420b57cec5SDimitry Andric return ExprError(); 41430b57cec5SDimitry Andric From = Res.get(); 41440b57cec5SDimitry Andric } 41450b57cec5SDimitry Andric 41460b57cec5SDimitry Andric ExprResult CastArg = BuildCXXCastArgument( 41470b57cec5SDimitry Andric *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, 41480b57cec5SDimitry Andric cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, 41490b57cec5SDimitry Andric ICS.UserDefined.HadMultipleCandidates, From); 41500b57cec5SDimitry Andric 41510b57cec5SDimitry Andric if (CastArg.isInvalid()) 41520b57cec5SDimitry Andric return ExprError(); 41530b57cec5SDimitry Andric 41540b57cec5SDimitry Andric From = CastArg.get(); 41550b57cec5SDimitry Andric 41560b57cec5SDimitry Andric // C++ [over.match.oper]p7: 41570b57cec5SDimitry Andric // [...] the second standard conversion sequence of a user-defined 41580b57cec5SDimitry Andric // conversion sequence is not applied. 41590b57cec5SDimitry Andric if (CCK == CCK_ForBuiltinOverloadedOp) 41600b57cec5SDimitry Andric return From; 41610b57cec5SDimitry Andric 41620b57cec5SDimitry Andric return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 41630b57cec5SDimitry Andric AA_Converting, CCK); 41640b57cec5SDimitry Andric } 41650b57cec5SDimitry Andric 41660b57cec5SDimitry Andric case ImplicitConversionSequence::AmbiguousConversion: 41670b57cec5SDimitry Andric ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 41680b57cec5SDimitry Andric PDiag(diag::err_typecheck_ambiguous_condition) 41690b57cec5SDimitry Andric << From->getSourceRange()); 41700b57cec5SDimitry Andric return ExprError(); 41710b57cec5SDimitry Andric 41720b57cec5SDimitry Andric case ImplicitConversionSequence::EllipsisConversion: 41730b57cec5SDimitry Andric llvm_unreachable("Cannot perform an ellipsis conversion"); 41740b57cec5SDimitry Andric 41750b57cec5SDimitry Andric case ImplicitConversionSequence::BadConversion: 41765ffd83dbSDimitry Andric Sema::AssignConvertType ConvTy = 41775ffd83dbSDimitry Andric CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); 41785ffd83dbSDimitry Andric bool Diagnosed = DiagnoseAssignmentResult( 41795ffd83dbSDimitry Andric ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(), 41805ffd83dbSDimitry Andric ToType, From->getType(), From, Action); 41810b57cec5SDimitry Andric assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; 41820b57cec5SDimitry Andric return ExprError(); 41830b57cec5SDimitry Andric } 41840b57cec5SDimitry Andric 41850b57cec5SDimitry Andric // Everything went well. 41860b57cec5SDimitry Andric return From; 41870b57cec5SDimitry Andric } 41880b57cec5SDimitry Andric 41890b57cec5SDimitry Andric /// PerformImplicitConversion - Perform an implicit conversion of the 41900b57cec5SDimitry Andric /// expression From to the type ToType by following the standard 41910b57cec5SDimitry Andric /// conversion sequence SCS. Returns the converted 41920b57cec5SDimitry Andric /// expression. Flavor is the context in which we're performing this 41930b57cec5SDimitry Andric /// conversion, for use in error messages. 41940b57cec5SDimitry Andric ExprResult 41950b57cec5SDimitry Andric Sema::PerformImplicitConversion(Expr *From, QualType ToType, 41960b57cec5SDimitry Andric const StandardConversionSequence& SCS, 41970b57cec5SDimitry Andric AssignmentAction Action, 41980b57cec5SDimitry Andric CheckedConversionKind CCK) { 41990b57cec5SDimitry Andric bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 42000b57cec5SDimitry Andric 42010b57cec5SDimitry Andric // Overall FIXME: we are recomputing too many types here and doing far too 42020b57cec5SDimitry Andric // much extra work. What this means is that we need to keep track of more 42030b57cec5SDimitry Andric // information that is computed when we try the implicit conversion initially, 42040b57cec5SDimitry Andric // so that we don't need to recompute anything here. 42050b57cec5SDimitry Andric QualType FromType = From->getType(); 42060b57cec5SDimitry Andric 42070b57cec5SDimitry Andric if (SCS.CopyConstructor) { 42080b57cec5SDimitry Andric // FIXME: When can ToType be a reference type? 42090b57cec5SDimitry Andric assert(!ToType->isReferenceType()); 42100b57cec5SDimitry Andric if (SCS.Second == ICK_Derived_To_Base) { 42110b57cec5SDimitry Andric SmallVector<Expr*, 8> ConstructorArgs; 4212fe6060f1SDimitry Andric if (CompleteConstructorCall( 4213fe6060f1SDimitry Andric cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, 4214fe6060f1SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs)) 42150b57cec5SDimitry Andric return ExprError(); 42160b57cec5SDimitry Andric return BuildCXXConstructExpr( 42170b57cec5SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 42180b57cec5SDimitry Andric SCS.FoundCopyConstructor, SCS.CopyConstructor, 42190b57cec5SDimitry Andric ConstructorArgs, /*HadMultipleCandidates*/ false, 42200b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 42210b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 42220b57cec5SDimitry Andric } 42230b57cec5SDimitry Andric return BuildCXXConstructExpr( 42240b57cec5SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 42250b57cec5SDimitry Andric SCS.FoundCopyConstructor, SCS.CopyConstructor, 42260b57cec5SDimitry Andric From, /*HadMultipleCandidates*/ false, 42270b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 42280b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 42290b57cec5SDimitry Andric } 42300b57cec5SDimitry Andric 42310b57cec5SDimitry Andric // Resolve overloaded function references. 42320b57cec5SDimitry Andric if (Context.hasSameType(FromType, Context.OverloadTy)) { 42330b57cec5SDimitry Andric DeclAccessPair Found; 42340b57cec5SDimitry Andric FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 42350b57cec5SDimitry Andric true, Found); 42360b57cec5SDimitry Andric if (!Fn) 42370b57cec5SDimitry Andric return ExprError(); 42380b57cec5SDimitry Andric 42390b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) 42400b57cec5SDimitry Andric return ExprError(); 42410b57cec5SDimitry Andric 42420b57cec5SDimitry Andric From = FixOverloadedFunctionReference(From, Found, Fn); 424381ad6265SDimitry Andric 424481ad6265SDimitry Andric // We might get back another placeholder expression if we resolved to a 424581ad6265SDimitry Andric // builtin. 424681ad6265SDimitry Andric ExprResult Checked = CheckPlaceholderExpr(From); 424781ad6265SDimitry Andric if (Checked.isInvalid()) 424881ad6265SDimitry Andric return ExprError(); 424981ad6265SDimitry Andric 425081ad6265SDimitry Andric From = Checked.get(); 42510b57cec5SDimitry Andric FromType = From->getType(); 42520b57cec5SDimitry Andric } 42530b57cec5SDimitry Andric 42540b57cec5SDimitry Andric // If we're converting to an atomic type, first convert to the corresponding 42550b57cec5SDimitry Andric // non-atomic type. 42560b57cec5SDimitry Andric QualType ToAtomicType; 42570b57cec5SDimitry Andric if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 42580b57cec5SDimitry Andric ToAtomicType = ToType; 42590b57cec5SDimitry Andric ToType = ToAtomic->getValueType(); 42600b57cec5SDimitry Andric } 42610b57cec5SDimitry Andric 42620b57cec5SDimitry Andric QualType InitialFromType = FromType; 42630b57cec5SDimitry Andric // Perform the first implicit conversion. 42640b57cec5SDimitry Andric switch (SCS.First) { 42650b57cec5SDimitry Andric case ICK_Identity: 42660b57cec5SDimitry Andric if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 42670b57cec5SDimitry Andric FromType = FromAtomic->getValueType().getUnqualifiedType(); 42680b57cec5SDimitry Andric From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 4269fe6060f1SDimitry Andric From, /*BasePath=*/nullptr, VK_PRValue, 4270e8d8bef9SDimitry Andric FPOptionsOverride()); 42710b57cec5SDimitry Andric } 42720b57cec5SDimitry Andric break; 42730b57cec5SDimitry Andric 42740b57cec5SDimitry Andric case ICK_Lvalue_To_Rvalue: { 42750b57cec5SDimitry Andric assert(From->getObjectKind() != OK_ObjCProperty); 42760b57cec5SDimitry Andric ExprResult FromRes = DefaultLvalueConversion(From); 4277fe6060f1SDimitry Andric if (FromRes.isInvalid()) 4278fe6060f1SDimitry Andric return ExprError(); 4279fe6060f1SDimitry Andric 42800b57cec5SDimitry Andric From = FromRes.get(); 42810b57cec5SDimitry Andric FromType = From->getType(); 42820b57cec5SDimitry Andric break; 42830b57cec5SDimitry Andric } 42840b57cec5SDimitry Andric 42850b57cec5SDimitry Andric case ICK_Array_To_Pointer: 42860b57cec5SDimitry Andric FromType = Context.getArrayDecayedType(FromType); 4287fe6060f1SDimitry Andric From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue, 4288fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4289fe6060f1SDimitry Andric .get(); 42900b57cec5SDimitry Andric break; 42910b57cec5SDimitry Andric 42920b57cec5SDimitry Andric case ICK_Function_To_Pointer: 42930b57cec5SDimitry Andric FromType = Context.getPointerType(FromType); 42940b57cec5SDimitry Andric From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 4295fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4296fe6060f1SDimitry Andric .get(); 42970b57cec5SDimitry Andric break; 42980b57cec5SDimitry Andric 42990b57cec5SDimitry Andric default: 43000b57cec5SDimitry Andric llvm_unreachable("Improper first standard conversion"); 43010b57cec5SDimitry Andric } 43020b57cec5SDimitry Andric 43030b57cec5SDimitry Andric // Perform the second implicit conversion 43040b57cec5SDimitry Andric switch (SCS.Second) { 43050b57cec5SDimitry Andric case ICK_Identity: 43060b57cec5SDimitry Andric // C++ [except.spec]p5: 43070b57cec5SDimitry Andric // [For] assignment to and initialization of pointers to functions, 43080b57cec5SDimitry Andric // pointers to member functions, and references to functions: the 43090b57cec5SDimitry Andric // target entity shall allow at least the exceptions allowed by the 43100b57cec5SDimitry Andric // source value in the assignment or initialization. 43110b57cec5SDimitry Andric switch (Action) { 43120b57cec5SDimitry Andric case AA_Assigning: 43130b57cec5SDimitry Andric case AA_Initializing: 43140b57cec5SDimitry Andric // Note, function argument passing and returning are initialization. 43150b57cec5SDimitry Andric case AA_Passing: 43160b57cec5SDimitry Andric case AA_Returning: 43170b57cec5SDimitry Andric case AA_Sending: 43180b57cec5SDimitry Andric case AA_Passing_CFAudited: 43190b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 43200b57cec5SDimitry Andric return ExprError(); 43210b57cec5SDimitry Andric break; 43220b57cec5SDimitry Andric 43230b57cec5SDimitry Andric case AA_Casting: 43240b57cec5SDimitry Andric case AA_Converting: 43250b57cec5SDimitry Andric // Casts and implicit conversions are not initialization, so are not 43260b57cec5SDimitry Andric // checked for exception specification mismatches. 43270b57cec5SDimitry Andric break; 43280b57cec5SDimitry Andric } 43290b57cec5SDimitry Andric // Nothing else to do. 43300b57cec5SDimitry Andric break; 43310b57cec5SDimitry Andric 43320b57cec5SDimitry Andric case ICK_Integral_Promotion: 43330b57cec5SDimitry Andric case ICK_Integral_Conversion: 43340b57cec5SDimitry Andric if (ToType->isBooleanType()) { 43350b57cec5SDimitry Andric assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 43360b57cec5SDimitry Andric SCS.Second == ICK_Integral_Promotion && 43370b57cec5SDimitry Andric "only enums with fixed underlying type can promote to bool"); 4338fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue, 4339fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4340fe6060f1SDimitry Andric .get(); 43410b57cec5SDimitry Andric } else { 4342fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue, 4343fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4344fe6060f1SDimitry Andric .get(); 43450b57cec5SDimitry Andric } 43460b57cec5SDimitry Andric break; 43470b57cec5SDimitry Andric 43480b57cec5SDimitry Andric case ICK_Floating_Promotion: 43490b57cec5SDimitry Andric case ICK_Floating_Conversion: 4350fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue, 4351fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4352fe6060f1SDimitry Andric .get(); 43530b57cec5SDimitry Andric break; 43540b57cec5SDimitry Andric 43550b57cec5SDimitry Andric case ICK_Complex_Promotion: 43560b57cec5SDimitry Andric case ICK_Complex_Conversion: { 4357a7dea167SDimitry Andric QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); 4358a7dea167SDimitry Andric QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); 43590b57cec5SDimitry Andric CastKind CK; 43600b57cec5SDimitry Andric if (FromEl->isRealFloatingType()) { 43610b57cec5SDimitry Andric if (ToEl->isRealFloatingType()) 43620b57cec5SDimitry Andric CK = CK_FloatingComplexCast; 43630b57cec5SDimitry Andric else 43640b57cec5SDimitry Andric CK = CK_FloatingComplexToIntegralComplex; 43650b57cec5SDimitry Andric } else if (ToEl->isRealFloatingType()) { 43660b57cec5SDimitry Andric CK = CK_IntegralComplexToFloatingComplex; 43670b57cec5SDimitry Andric } else { 43680b57cec5SDimitry Andric CK = CK_IntegralComplexCast; 43690b57cec5SDimitry Andric } 4370fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr, 4371fe6060f1SDimitry Andric CCK) 4372fe6060f1SDimitry Andric .get(); 43730b57cec5SDimitry Andric break; 43740b57cec5SDimitry Andric } 43750b57cec5SDimitry Andric 43760b57cec5SDimitry Andric case ICK_Floating_Integral: 43770b57cec5SDimitry Andric if (ToType->isRealFloatingType()) 4378fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue, 4379fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4380fe6060f1SDimitry Andric .get(); 43810b57cec5SDimitry Andric else 4382fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue, 4383fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4384fe6060f1SDimitry Andric .get(); 43850b57cec5SDimitry Andric break; 43860b57cec5SDimitry Andric 43870b57cec5SDimitry Andric case ICK_Compatible_Conversion: 4388f13e6193SDimitry Andric From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), 4389f13e6193SDimitry Andric /*BasePath=*/nullptr, CCK).get(); 43900b57cec5SDimitry Andric break; 43910b57cec5SDimitry Andric 43920b57cec5SDimitry Andric case ICK_Writeback_Conversion: 43930b57cec5SDimitry Andric case ICK_Pointer_Conversion: { 43940b57cec5SDimitry Andric if (SCS.IncompatibleObjC && Action != AA_Casting) { 43950b57cec5SDimitry Andric // Diagnose incompatible Objective-C conversions 43960b57cec5SDimitry Andric if (Action == AA_Initializing || Action == AA_Assigning) 43970b57cec5SDimitry Andric Diag(From->getBeginLoc(), 43980b57cec5SDimitry Andric diag::ext_typecheck_convert_incompatible_pointer) 43990b57cec5SDimitry Andric << ToType << From->getType() << Action << From->getSourceRange() 44000b57cec5SDimitry Andric << 0; 44010b57cec5SDimitry Andric else 44020b57cec5SDimitry Andric Diag(From->getBeginLoc(), 44030b57cec5SDimitry Andric diag::ext_typecheck_convert_incompatible_pointer) 44040b57cec5SDimitry Andric << From->getType() << ToType << Action << From->getSourceRange() 44050b57cec5SDimitry Andric << 0; 44060b57cec5SDimitry Andric 44070b57cec5SDimitry Andric if (From->getType()->isObjCObjectPointerType() && 44080b57cec5SDimitry Andric ToType->isObjCObjectPointerType()) 44090b57cec5SDimitry Andric EmitRelatedResultTypeNote(From); 44100b57cec5SDimitry Andric } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 44110b57cec5SDimitry Andric !CheckObjCARCUnavailableWeakConversion(ToType, 44120b57cec5SDimitry Andric From->getType())) { 44130b57cec5SDimitry Andric if (Action == AA_Initializing) 44140b57cec5SDimitry Andric Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); 44150b57cec5SDimitry Andric else 44160b57cec5SDimitry Andric Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) 44170b57cec5SDimitry Andric << (Action == AA_Casting) << From->getType() << ToType 44180b57cec5SDimitry Andric << From->getSourceRange(); 44190b57cec5SDimitry Andric } 44200b57cec5SDimitry Andric 4421480093f4SDimitry Andric // Defer address space conversion to the third conversion. 4422480093f4SDimitry Andric QualType FromPteeType = From->getType()->getPointeeType(); 4423480093f4SDimitry Andric QualType ToPteeType = ToType->getPointeeType(); 4424480093f4SDimitry Andric QualType NewToType = ToType; 4425480093f4SDimitry Andric if (!FromPteeType.isNull() && !ToPteeType.isNull() && 4426480093f4SDimitry Andric FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { 4427480093f4SDimitry Andric NewToType = Context.removeAddrSpaceQualType(ToPteeType); 4428480093f4SDimitry Andric NewToType = Context.getAddrSpaceQualType(NewToType, 4429480093f4SDimitry Andric FromPteeType.getAddressSpace()); 4430480093f4SDimitry Andric if (ToType->isObjCObjectPointerType()) 4431480093f4SDimitry Andric NewToType = Context.getObjCObjectPointerType(NewToType); 4432480093f4SDimitry Andric else if (ToType->isBlockPointerType()) 4433480093f4SDimitry Andric NewToType = Context.getBlockPointerType(NewToType); 4434480093f4SDimitry Andric else 4435480093f4SDimitry Andric NewToType = Context.getPointerType(NewToType); 4436480093f4SDimitry Andric } 4437480093f4SDimitry Andric 44380b57cec5SDimitry Andric CastKind Kind; 44390b57cec5SDimitry Andric CXXCastPath BasePath; 4440480093f4SDimitry Andric if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) 44410b57cec5SDimitry Andric return ExprError(); 44420b57cec5SDimitry Andric 44430b57cec5SDimitry Andric // Make sure we extend blocks if necessary. 44440b57cec5SDimitry Andric // FIXME: doing this here is really ugly. 44450b57cec5SDimitry Andric if (Kind == CK_BlockPointerToObjCPointerCast) { 44460b57cec5SDimitry Andric ExprResult E = From; 44470b57cec5SDimitry Andric (void) PrepareCastToObjCObjectPointer(E); 44480b57cec5SDimitry Andric From = E.get(); 44490b57cec5SDimitry Andric } 44500b57cec5SDimitry Andric if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 4451480093f4SDimitry Andric CheckObjCConversion(SourceRange(), NewToType, From, CCK); 4452fe6060f1SDimitry Andric From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK) 44530b57cec5SDimitry Andric .get(); 44540b57cec5SDimitry Andric break; 44550b57cec5SDimitry Andric } 44560b57cec5SDimitry Andric 44570b57cec5SDimitry Andric case ICK_Pointer_Member: { 44580b57cec5SDimitry Andric CastKind Kind; 44590b57cec5SDimitry Andric CXXCastPath BasePath; 44600b57cec5SDimitry Andric if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 44610b57cec5SDimitry Andric return ExprError(); 44620b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 44630b57cec5SDimitry Andric return ExprError(); 44640b57cec5SDimitry Andric 44650b57cec5SDimitry Andric // We may not have been able to figure out what this member pointer resolved 44660b57cec5SDimitry Andric // to up until this exact point. Attempt to lock-in it's inheritance model. 44670b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 44680b57cec5SDimitry Andric (void)isCompleteType(From->getExprLoc(), From->getType()); 44690b57cec5SDimitry Andric (void)isCompleteType(From->getExprLoc(), ToType); 44700b57cec5SDimitry Andric } 44710b57cec5SDimitry Andric 4472fe6060f1SDimitry Andric From = 4473fe6060f1SDimitry Andric ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get(); 44740b57cec5SDimitry Andric break; 44750b57cec5SDimitry Andric } 44760b57cec5SDimitry Andric 44770b57cec5SDimitry Andric case ICK_Boolean_Conversion: 44780b57cec5SDimitry Andric // Perform half-to-boolean conversion via float. 44790b57cec5SDimitry Andric if (From->getType()->isHalfType()) { 44800b57cec5SDimitry Andric From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 44810b57cec5SDimitry Andric FromType = Context.FloatTy; 44820b57cec5SDimitry Andric } 44830b57cec5SDimitry Andric 44840b57cec5SDimitry Andric From = ImpCastExprToType(From, Context.BoolTy, 4485fe6060f1SDimitry Andric ScalarTypeToBooleanCastKind(FromType), VK_PRValue, 4486fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4487fe6060f1SDimitry Andric .get(); 44880b57cec5SDimitry Andric break; 44890b57cec5SDimitry Andric 44900b57cec5SDimitry Andric case ICK_Derived_To_Base: { 44910b57cec5SDimitry Andric CXXCastPath BasePath; 44920b57cec5SDimitry Andric if (CheckDerivedToBaseConversion( 44930b57cec5SDimitry Andric From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), 44940b57cec5SDimitry Andric From->getSourceRange(), &BasePath, CStyle)) 44950b57cec5SDimitry Andric return ExprError(); 44960b57cec5SDimitry Andric 44970b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getNonReferenceType(), 44980b57cec5SDimitry Andric CK_DerivedToBase, From->getValueKind(), 44990b57cec5SDimitry Andric &BasePath, CCK).get(); 45000b57cec5SDimitry Andric break; 45010b57cec5SDimitry Andric } 45020b57cec5SDimitry Andric 45030b57cec5SDimitry Andric case ICK_Vector_Conversion: 4504fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, 4505fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4506fe6060f1SDimitry Andric .get(); 45070b57cec5SDimitry Andric break; 45080b57cec5SDimitry Andric 4509e8d8bef9SDimitry Andric case ICK_SVE_Vector_Conversion: 4510fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, 4511e8d8bef9SDimitry Andric /*BasePath=*/nullptr, CCK) 4512e8d8bef9SDimitry Andric .get(); 4513e8d8bef9SDimitry Andric break; 4514e8d8bef9SDimitry Andric 45150b57cec5SDimitry Andric case ICK_Vector_Splat: { 45160b57cec5SDimitry Andric // Vector splat from any arithmetic type to a vector. 45170b57cec5SDimitry Andric Expr *Elem = prepareVectorSplat(ToType, From).get(); 4518fe6060f1SDimitry Andric From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, 4519fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4520fe6060f1SDimitry Andric .get(); 45210b57cec5SDimitry Andric break; 45220b57cec5SDimitry Andric } 45230b57cec5SDimitry Andric 45240b57cec5SDimitry Andric case ICK_Complex_Real: 45250b57cec5SDimitry Andric // Case 1. x -> _Complex y 45260b57cec5SDimitry Andric if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 45270b57cec5SDimitry Andric QualType ElType = ToComplex->getElementType(); 45280b57cec5SDimitry Andric bool isFloatingComplex = ElType->isRealFloatingType(); 45290b57cec5SDimitry Andric 45300b57cec5SDimitry Andric // x -> y 45310b57cec5SDimitry Andric if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 45320b57cec5SDimitry Andric // do nothing 45330b57cec5SDimitry Andric } else if (From->getType()->isRealFloatingType()) { 45340b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 45350b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 45360b57cec5SDimitry Andric } else { 45370b57cec5SDimitry Andric assert(From->getType()->isIntegerType()); 45380b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 45390b57cec5SDimitry Andric isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 45400b57cec5SDimitry Andric } 45410b57cec5SDimitry Andric // y -> _Complex y 45420b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 45430b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingRealToComplex 45440b57cec5SDimitry Andric : CK_IntegralRealToComplex).get(); 45450b57cec5SDimitry Andric 45460b57cec5SDimitry Andric // Case 2. _Complex x -> y 45470b57cec5SDimitry Andric } else { 45485ffd83dbSDimitry Andric auto *FromComplex = From->getType()->castAs<ComplexType>(); 45490b57cec5SDimitry Andric QualType ElType = FromComplex->getElementType(); 45500b57cec5SDimitry Andric bool isFloatingComplex = ElType->isRealFloatingType(); 45510b57cec5SDimitry Andric 45520b57cec5SDimitry Andric // _Complex x -> x 45530b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 45540b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingComplexToReal 45550b57cec5SDimitry Andric : CK_IntegralComplexToReal, 4556fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4557fe6060f1SDimitry Andric .get(); 45580b57cec5SDimitry Andric 45590b57cec5SDimitry Andric // x -> y 45600b57cec5SDimitry Andric if (Context.hasSameUnqualifiedType(ElType, ToType)) { 45610b57cec5SDimitry Andric // do nothing 45620b57cec5SDimitry Andric } else if (ToType->isRealFloatingType()) { 45630b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 4564fe6060f1SDimitry Andric isFloatingComplex ? CK_FloatingCast 4565fe6060f1SDimitry Andric : CK_IntegralToFloating, 4566fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4567fe6060f1SDimitry Andric .get(); 45680b57cec5SDimitry Andric } else { 45690b57cec5SDimitry Andric assert(ToType->isIntegerType()); 45700b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 4571fe6060f1SDimitry Andric isFloatingComplex ? CK_FloatingToIntegral 4572fe6060f1SDimitry Andric : CK_IntegralCast, 4573fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4574fe6060f1SDimitry Andric .get(); 45750b57cec5SDimitry Andric } 45760b57cec5SDimitry Andric } 45770b57cec5SDimitry Andric break; 45780b57cec5SDimitry Andric 45790b57cec5SDimitry Andric case ICK_Block_Pointer_Conversion: { 45800b57cec5SDimitry Andric LangAS AddrSpaceL = 45810b57cec5SDimitry Andric ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 45820b57cec5SDimitry Andric LangAS AddrSpaceR = 45830b57cec5SDimitry Andric FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 45840b57cec5SDimitry Andric assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && 45850b57cec5SDimitry Andric "Invalid cast"); 45860b57cec5SDimitry Andric CastKind Kind = 45870b57cec5SDimitry Andric AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 45880b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, 4589fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4590fe6060f1SDimitry Andric .get(); 45910b57cec5SDimitry Andric break; 45920b57cec5SDimitry Andric } 45930b57cec5SDimitry Andric 45940b57cec5SDimitry Andric case ICK_TransparentUnionConversion: { 45950b57cec5SDimitry Andric ExprResult FromRes = From; 45960b57cec5SDimitry Andric Sema::AssignConvertType ConvTy = 45970b57cec5SDimitry Andric CheckTransparentUnionArgumentConstraints(ToType, FromRes); 45980b57cec5SDimitry Andric if (FromRes.isInvalid()) 45990b57cec5SDimitry Andric return ExprError(); 46000b57cec5SDimitry Andric From = FromRes.get(); 46010b57cec5SDimitry Andric assert ((ConvTy == Sema::Compatible) && 46020b57cec5SDimitry Andric "Improper transparent union conversion"); 46030b57cec5SDimitry Andric (void)ConvTy; 46040b57cec5SDimitry Andric break; 46050b57cec5SDimitry Andric } 46060b57cec5SDimitry Andric 46070b57cec5SDimitry Andric case ICK_Zero_Event_Conversion: 46080b57cec5SDimitry Andric case ICK_Zero_Queue_Conversion: 46090b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 46100b57cec5SDimitry Andric CK_ZeroToOCLOpaqueType, 46110b57cec5SDimitry Andric From->getValueKind()).get(); 46120b57cec5SDimitry Andric break; 46130b57cec5SDimitry Andric 46140b57cec5SDimitry Andric case ICK_Lvalue_To_Rvalue: 46150b57cec5SDimitry Andric case ICK_Array_To_Pointer: 46160b57cec5SDimitry Andric case ICK_Function_To_Pointer: 46170b57cec5SDimitry Andric case ICK_Function_Conversion: 46180b57cec5SDimitry Andric case ICK_Qualification: 46190b57cec5SDimitry Andric case ICK_Num_Conversion_Kinds: 46200b57cec5SDimitry Andric case ICK_C_Only_Conversion: 46210b57cec5SDimitry Andric case ICK_Incompatible_Pointer_Conversion: 46220b57cec5SDimitry Andric llvm_unreachable("Improper second standard conversion"); 46230b57cec5SDimitry Andric } 46240b57cec5SDimitry Andric 46250b57cec5SDimitry Andric switch (SCS.Third) { 46260b57cec5SDimitry Andric case ICK_Identity: 46270b57cec5SDimitry Andric // Nothing to do. 46280b57cec5SDimitry Andric break; 46290b57cec5SDimitry Andric 46300b57cec5SDimitry Andric case ICK_Function_Conversion: 46310b57cec5SDimitry Andric // If both sides are functions (or pointers/references to them), there could 46320b57cec5SDimitry Andric // be incompatible exception declarations. 46330b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 46340b57cec5SDimitry Andric return ExprError(); 46350b57cec5SDimitry Andric 4636fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue, 4637fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4638fe6060f1SDimitry Andric .get(); 46390b57cec5SDimitry Andric break; 46400b57cec5SDimitry Andric 46410b57cec5SDimitry Andric case ICK_Qualification: { 4642f13e6193SDimitry Andric ExprValueKind VK = From->getValueKind(); 46430b57cec5SDimitry Andric CastKind CK = CK_NoOp; 46440b57cec5SDimitry Andric 46450b57cec5SDimitry Andric if (ToType->isReferenceType() && 46460b57cec5SDimitry Andric ToType->getPointeeType().getAddressSpace() != 46470b57cec5SDimitry Andric From->getType().getAddressSpace()) 46480b57cec5SDimitry Andric CK = CK_AddressSpaceConversion; 46490b57cec5SDimitry Andric 46500b57cec5SDimitry Andric if (ToType->isPointerType() && 46510b57cec5SDimitry Andric ToType->getPointeeType().getAddressSpace() != 46520b57cec5SDimitry Andric From->getType()->getPointeeType().getAddressSpace()) 46530b57cec5SDimitry Andric CK = CK_AddressSpaceConversion; 46540b57cec5SDimitry Andric 465581ad6265SDimitry Andric if (!isCast(CCK) && 465681ad6265SDimitry Andric !ToType->getPointeeType().getQualifiers().hasUnaligned() && 465781ad6265SDimitry Andric From->getType()->getPointeeType().getQualifiers().hasUnaligned()) { 465881ad6265SDimitry Andric Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned) 465981ad6265SDimitry Andric << InitialFromType << ToType; 466081ad6265SDimitry Andric } 466181ad6265SDimitry Andric 46620b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, 46630b57cec5SDimitry Andric /*BasePath=*/nullptr, CCK) 46640b57cec5SDimitry Andric .get(); 46650b57cec5SDimitry Andric 46660b57cec5SDimitry Andric if (SCS.DeprecatedStringLiteralToCharPtr && 46670b57cec5SDimitry Andric !getLangOpts().WritableStrings) { 46680b57cec5SDimitry Andric Diag(From->getBeginLoc(), 46690b57cec5SDimitry Andric getLangOpts().CPlusPlus11 46700b57cec5SDimitry Andric ? diag::ext_deprecated_string_literal_conversion 46710b57cec5SDimitry Andric : diag::warn_deprecated_string_literal_conversion) 46720b57cec5SDimitry Andric << ToType.getNonReferenceType(); 46730b57cec5SDimitry Andric } 46740b57cec5SDimitry Andric 46750b57cec5SDimitry Andric break; 46760b57cec5SDimitry Andric } 46770b57cec5SDimitry Andric 46780b57cec5SDimitry Andric default: 46790b57cec5SDimitry Andric llvm_unreachable("Improper third standard conversion"); 46800b57cec5SDimitry Andric } 46810b57cec5SDimitry Andric 46820b57cec5SDimitry Andric // If this conversion sequence involved a scalar -> atomic conversion, perform 46830b57cec5SDimitry Andric // that conversion now. 46840b57cec5SDimitry Andric if (!ToAtomicType.isNull()) { 46850b57cec5SDimitry Andric assert(Context.hasSameType( 46860b57cec5SDimitry Andric ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); 46870b57cec5SDimitry Andric From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 4688fe6060f1SDimitry Andric VK_PRValue, nullptr, CCK) 4689fe6060f1SDimitry Andric .get(); 46900b57cec5SDimitry Andric } 46910b57cec5SDimitry Andric 46925ffd83dbSDimitry Andric // Materialize a temporary if we're implicitly converting to a reference 46935ffd83dbSDimitry Andric // type. This is not required by the C++ rules but is necessary to maintain 46945ffd83dbSDimitry Andric // AST invariants. 4695fe6060f1SDimitry Andric if (ToType->isReferenceType() && From->isPRValue()) { 46965ffd83dbSDimitry Andric ExprResult Res = TemporaryMaterializationConversion(From); 46975ffd83dbSDimitry Andric if (Res.isInvalid()) 46985ffd83dbSDimitry Andric return ExprError(); 46995ffd83dbSDimitry Andric From = Res.get(); 47005ffd83dbSDimitry Andric } 47015ffd83dbSDimitry Andric 47020b57cec5SDimitry Andric // If this conversion sequence succeeded and involved implicitly converting a 47030b57cec5SDimitry Andric // _Nullable type to a _Nonnull one, complain. 47040b57cec5SDimitry Andric if (!isCast(CCK)) 47050b57cec5SDimitry Andric diagnoseNullableToNonnullConversion(ToType, InitialFromType, 47060b57cec5SDimitry Andric From->getBeginLoc()); 47070b57cec5SDimitry Andric 47080b57cec5SDimitry Andric return From; 47090b57cec5SDimitry Andric } 47100b57cec5SDimitry Andric 47110b57cec5SDimitry Andric /// Check the completeness of a type in a unary type trait. 47120b57cec5SDimitry Andric /// 47130b57cec5SDimitry Andric /// If the particular type trait requires a complete type, tries to complete 47140b57cec5SDimitry Andric /// it. If completing the type fails, a diagnostic is emitted and false 47150b57cec5SDimitry Andric /// returned. If completing the type succeeds or no completion was required, 47160b57cec5SDimitry Andric /// returns true. 47170b57cec5SDimitry Andric static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 47180b57cec5SDimitry Andric SourceLocation Loc, 47190b57cec5SDimitry Andric QualType ArgTy) { 47200b57cec5SDimitry Andric // C++0x [meta.unary.prop]p3: 47210b57cec5SDimitry Andric // For all of the class templates X declared in this Clause, instantiating 47220b57cec5SDimitry Andric // that template with a template argument that is a class template 47230b57cec5SDimitry Andric // specialization may result in the implicit instantiation of the template 47240b57cec5SDimitry Andric // argument if and only if the semantics of X require that the argument 47250b57cec5SDimitry Andric // must be a complete type. 47260b57cec5SDimitry Andric // We apply this rule to all the type trait expressions used to implement 47270b57cec5SDimitry Andric // these class templates. We also try to follow any GCC documented behavior 47280b57cec5SDimitry Andric // in these expressions to ensure portability of standard libraries. 47290b57cec5SDimitry Andric switch (UTT) { 47300b57cec5SDimitry Andric default: llvm_unreachable("not a UTT"); 47310b57cec5SDimitry Andric // is_complete_type somewhat obviously cannot require a complete type. 47320b57cec5SDimitry Andric case UTT_IsCompleteType: 47330b57cec5SDimitry Andric // Fall-through 47340b57cec5SDimitry Andric 47350b57cec5SDimitry Andric // These traits are modeled on the type predicates in C++0x 47360b57cec5SDimitry Andric // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 47370b57cec5SDimitry Andric // requiring a complete type, as whether or not they return true cannot be 47380b57cec5SDimitry Andric // impacted by the completeness of the type. 47390b57cec5SDimitry Andric case UTT_IsVoid: 47400b57cec5SDimitry Andric case UTT_IsIntegral: 47410b57cec5SDimitry Andric case UTT_IsFloatingPoint: 47420b57cec5SDimitry Andric case UTT_IsArray: 47430b57cec5SDimitry Andric case UTT_IsPointer: 47440b57cec5SDimitry Andric case UTT_IsLvalueReference: 47450b57cec5SDimitry Andric case UTT_IsRvalueReference: 47460b57cec5SDimitry Andric case UTT_IsMemberFunctionPointer: 47470b57cec5SDimitry Andric case UTT_IsMemberObjectPointer: 47480b57cec5SDimitry Andric case UTT_IsEnum: 47490b57cec5SDimitry Andric case UTT_IsUnion: 47500b57cec5SDimitry Andric case UTT_IsClass: 47510b57cec5SDimitry Andric case UTT_IsFunction: 47520b57cec5SDimitry Andric case UTT_IsReference: 47530b57cec5SDimitry Andric case UTT_IsArithmetic: 47540b57cec5SDimitry Andric case UTT_IsFundamental: 47550b57cec5SDimitry Andric case UTT_IsObject: 47560b57cec5SDimitry Andric case UTT_IsScalar: 47570b57cec5SDimitry Andric case UTT_IsCompound: 47580b57cec5SDimitry Andric case UTT_IsMemberPointer: 47590b57cec5SDimitry Andric // Fall-through 47600b57cec5SDimitry Andric 47610b57cec5SDimitry Andric // These traits are modeled on type predicates in C++0x [meta.unary.prop] 47620b57cec5SDimitry Andric // which requires some of its traits to have the complete type. However, 47630b57cec5SDimitry Andric // the completeness of the type cannot impact these traits' semantics, and 47640b57cec5SDimitry Andric // so they don't require it. This matches the comments on these traits in 47650b57cec5SDimitry Andric // Table 49. 47660b57cec5SDimitry Andric case UTT_IsConst: 47670b57cec5SDimitry Andric case UTT_IsVolatile: 47680b57cec5SDimitry Andric case UTT_IsSigned: 47690b57cec5SDimitry Andric case UTT_IsUnsigned: 47700b57cec5SDimitry Andric 47710b57cec5SDimitry Andric // This type trait always returns false, checking the type is moot. 47720b57cec5SDimitry Andric case UTT_IsInterfaceClass: 47730b57cec5SDimitry Andric return true; 47740b57cec5SDimitry Andric 47750b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 47760b57cec5SDimitry Andric // If T is a non-union class type, T shall be a complete type. 47770b57cec5SDimitry Andric case UTT_IsEmpty: 47780b57cec5SDimitry Andric case UTT_IsPolymorphic: 47790b57cec5SDimitry Andric case UTT_IsAbstract: 47800b57cec5SDimitry Andric if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 47810b57cec5SDimitry Andric if (!RD->isUnion()) 47820b57cec5SDimitry Andric return !S.RequireCompleteType( 47830b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 47840b57cec5SDimitry Andric return true; 47850b57cec5SDimitry Andric 47860b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 47870b57cec5SDimitry Andric // If T is a class type, T shall be a complete type. 47880b57cec5SDimitry Andric case UTT_IsFinal: 47890b57cec5SDimitry Andric case UTT_IsSealed: 47900b57cec5SDimitry Andric if (ArgTy->getAsCXXRecordDecl()) 47910b57cec5SDimitry Andric return !S.RequireCompleteType( 47920b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 47930b57cec5SDimitry Andric return true; 47940b57cec5SDimitry Andric 47950b57cec5SDimitry Andric // C++1z [meta.unary.prop]: 47960b57cec5SDimitry Andric // remove_all_extents_t<T> shall be a complete type or cv void. 47970b57cec5SDimitry Andric case UTT_IsAggregate: 47980b57cec5SDimitry Andric case UTT_IsTrivial: 47990b57cec5SDimitry Andric case UTT_IsTriviallyCopyable: 48000b57cec5SDimitry Andric case UTT_IsStandardLayout: 48010b57cec5SDimitry Andric case UTT_IsPOD: 48020b57cec5SDimitry Andric case UTT_IsLiteral: 480381ad6265SDimitry Andric // By analogy, is_trivially_relocatable imposes the same constraints. 480481ad6265SDimitry Andric case UTT_IsTriviallyRelocatable: 48050b57cec5SDimitry Andric // Per the GCC type traits documentation, T shall be a complete type, cv void, 48060b57cec5SDimitry Andric // or an array of unknown bound. But GCC actually imposes the same constraints 48070b57cec5SDimitry Andric // as above. 48080b57cec5SDimitry Andric case UTT_HasNothrowAssign: 48090b57cec5SDimitry Andric case UTT_HasNothrowMoveAssign: 48100b57cec5SDimitry Andric case UTT_HasNothrowConstructor: 48110b57cec5SDimitry Andric case UTT_HasNothrowCopy: 48120b57cec5SDimitry Andric case UTT_HasTrivialAssign: 48130b57cec5SDimitry Andric case UTT_HasTrivialMoveAssign: 48140b57cec5SDimitry Andric case UTT_HasTrivialDefaultConstructor: 48150b57cec5SDimitry Andric case UTT_HasTrivialMoveConstructor: 48160b57cec5SDimitry Andric case UTT_HasTrivialCopy: 48170b57cec5SDimitry Andric case UTT_HasTrivialDestructor: 48180b57cec5SDimitry Andric case UTT_HasVirtualDestructor: 48190b57cec5SDimitry Andric ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); 48200b57cec5SDimitry Andric LLVM_FALLTHROUGH; 48210b57cec5SDimitry Andric 48220b57cec5SDimitry Andric // C++1z [meta.unary.prop]: 48230b57cec5SDimitry Andric // T shall be a complete type, cv void, or an array of unknown bound. 48240b57cec5SDimitry Andric case UTT_IsDestructible: 48250b57cec5SDimitry Andric case UTT_IsNothrowDestructible: 48260b57cec5SDimitry Andric case UTT_IsTriviallyDestructible: 48270b57cec5SDimitry Andric case UTT_HasUniqueObjectRepresentations: 48280b57cec5SDimitry Andric if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) 48290b57cec5SDimitry Andric return true; 48300b57cec5SDimitry Andric 48310b57cec5SDimitry Andric return !S.RequireCompleteType( 48320b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 48330b57cec5SDimitry Andric } 48340b57cec5SDimitry Andric } 48350b57cec5SDimitry Andric 48360b57cec5SDimitry Andric static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 48370b57cec5SDimitry Andric Sema &Self, SourceLocation KeyLoc, ASTContext &C, 48380b57cec5SDimitry Andric bool (CXXRecordDecl::*HasTrivial)() const, 48390b57cec5SDimitry Andric bool (CXXRecordDecl::*HasNonTrivial)() const, 48400b57cec5SDimitry Andric bool (CXXMethodDecl::*IsDesiredOp)() const) 48410b57cec5SDimitry Andric { 48420b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 48430b57cec5SDimitry Andric if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 48440b57cec5SDimitry Andric return true; 48450b57cec5SDimitry Andric 48460b57cec5SDimitry Andric DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 48470b57cec5SDimitry Andric DeclarationNameInfo NameInfo(Name, KeyLoc); 48480b57cec5SDimitry Andric LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 48490b57cec5SDimitry Andric if (Self.LookupQualifiedName(Res, RD)) { 48500b57cec5SDimitry Andric bool FoundOperator = false; 48510b57cec5SDimitry Andric Res.suppressDiagnostics(); 48520b57cec5SDimitry Andric for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 48530b57cec5SDimitry Andric Op != OpEnd; ++Op) { 48540b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(*Op)) 48550b57cec5SDimitry Andric continue; 48560b57cec5SDimitry Andric 48570b57cec5SDimitry Andric CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 48580b57cec5SDimitry Andric if((Operator->*IsDesiredOp)()) { 48590b57cec5SDimitry Andric FoundOperator = true; 48605ffd83dbSDimitry Andric auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); 48610b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 48620b57cec5SDimitry Andric if (!CPT || !CPT->isNothrow()) 48630b57cec5SDimitry Andric return false; 48640b57cec5SDimitry Andric } 48650b57cec5SDimitry Andric } 48660b57cec5SDimitry Andric return FoundOperator; 48670b57cec5SDimitry Andric } 48680b57cec5SDimitry Andric return false; 48690b57cec5SDimitry Andric } 48700b57cec5SDimitry Andric 48710b57cec5SDimitry Andric static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 48720b57cec5SDimitry Andric SourceLocation KeyLoc, QualType T) { 48730b57cec5SDimitry Andric assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 48740b57cec5SDimitry Andric 48750b57cec5SDimitry Andric ASTContext &C = Self.Context; 48760b57cec5SDimitry Andric switch(UTT) { 48770b57cec5SDimitry Andric default: llvm_unreachable("not a UTT"); 48780b57cec5SDimitry Andric // Type trait expressions corresponding to the primary type category 48790b57cec5SDimitry Andric // predicates in C++0x [meta.unary.cat]. 48800b57cec5SDimitry Andric case UTT_IsVoid: 48810b57cec5SDimitry Andric return T->isVoidType(); 48820b57cec5SDimitry Andric case UTT_IsIntegral: 48830b57cec5SDimitry Andric return T->isIntegralType(C); 48840b57cec5SDimitry Andric case UTT_IsFloatingPoint: 48850b57cec5SDimitry Andric return T->isFloatingType(); 48860b57cec5SDimitry Andric case UTT_IsArray: 48870b57cec5SDimitry Andric return T->isArrayType(); 48880b57cec5SDimitry Andric case UTT_IsPointer: 48895ffd83dbSDimitry Andric return T->isAnyPointerType(); 48900b57cec5SDimitry Andric case UTT_IsLvalueReference: 48910b57cec5SDimitry Andric return T->isLValueReferenceType(); 48920b57cec5SDimitry Andric case UTT_IsRvalueReference: 48930b57cec5SDimitry Andric return T->isRValueReferenceType(); 48940b57cec5SDimitry Andric case UTT_IsMemberFunctionPointer: 48950b57cec5SDimitry Andric return T->isMemberFunctionPointerType(); 48960b57cec5SDimitry Andric case UTT_IsMemberObjectPointer: 48970b57cec5SDimitry Andric return T->isMemberDataPointerType(); 48980b57cec5SDimitry Andric case UTT_IsEnum: 48990b57cec5SDimitry Andric return T->isEnumeralType(); 49000b57cec5SDimitry Andric case UTT_IsUnion: 49010b57cec5SDimitry Andric return T->isUnionType(); 49020b57cec5SDimitry Andric case UTT_IsClass: 49030b57cec5SDimitry Andric return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 49040b57cec5SDimitry Andric case UTT_IsFunction: 49050b57cec5SDimitry Andric return T->isFunctionType(); 49060b57cec5SDimitry Andric 49070b57cec5SDimitry Andric // Type trait expressions which correspond to the convenient composition 49080b57cec5SDimitry Andric // predicates in C++0x [meta.unary.comp]. 49090b57cec5SDimitry Andric case UTT_IsReference: 49100b57cec5SDimitry Andric return T->isReferenceType(); 49110b57cec5SDimitry Andric case UTT_IsArithmetic: 49120b57cec5SDimitry Andric return T->isArithmeticType() && !T->isEnumeralType(); 49130b57cec5SDimitry Andric case UTT_IsFundamental: 49140b57cec5SDimitry Andric return T->isFundamentalType(); 49150b57cec5SDimitry Andric case UTT_IsObject: 49160b57cec5SDimitry Andric return T->isObjectType(); 49170b57cec5SDimitry Andric case UTT_IsScalar: 49180b57cec5SDimitry Andric // Note: semantic analysis depends on Objective-C lifetime types to be 49190b57cec5SDimitry Andric // considered scalar types. However, such types do not actually behave 49200b57cec5SDimitry Andric // like scalar types at run time (since they may require retain/release 49210b57cec5SDimitry Andric // operations), so we report them as non-scalar. 49220b57cec5SDimitry Andric if (T->isObjCLifetimeType()) { 49230b57cec5SDimitry Andric switch (T.getObjCLifetime()) { 49240b57cec5SDimitry Andric case Qualifiers::OCL_None: 49250b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone: 49260b57cec5SDimitry Andric return true; 49270b57cec5SDimitry Andric 49280b57cec5SDimitry Andric case Qualifiers::OCL_Strong: 49290b57cec5SDimitry Andric case Qualifiers::OCL_Weak: 49300b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing: 49310b57cec5SDimitry Andric return false; 49320b57cec5SDimitry Andric } 49330b57cec5SDimitry Andric } 49340b57cec5SDimitry Andric 49350b57cec5SDimitry Andric return T->isScalarType(); 49360b57cec5SDimitry Andric case UTT_IsCompound: 49370b57cec5SDimitry Andric return T->isCompoundType(); 49380b57cec5SDimitry Andric case UTT_IsMemberPointer: 49390b57cec5SDimitry Andric return T->isMemberPointerType(); 49400b57cec5SDimitry Andric 49410b57cec5SDimitry Andric // Type trait expressions which correspond to the type property predicates 49420b57cec5SDimitry Andric // in C++0x [meta.unary.prop]. 49430b57cec5SDimitry Andric case UTT_IsConst: 49440b57cec5SDimitry Andric return T.isConstQualified(); 49450b57cec5SDimitry Andric case UTT_IsVolatile: 49460b57cec5SDimitry Andric return T.isVolatileQualified(); 49470b57cec5SDimitry Andric case UTT_IsTrivial: 49480b57cec5SDimitry Andric return T.isTrivialType(C); 49490b57cec5SDimitry Andric case UTT_IsTriviallyCopyable: 49500b57cec5SDimitry Andric return T.isTriviallyCopyableType(C); 49510b57cec5SDimitry Andric case UTT_IsStandardLayout: 49520b57cec5SDimitry Andric return T->isStandardLayoutType(); 49530b57cec5SDimitry Andric case UTT_IsPOD: 49540b57cec5SDimitry Andric return T.isPODType(C); 49550b57cec5SDimitry Andric case UTT_IsLiteral: 49560b57cec5SDimitry Andric return T->isLiteralType(C); 49570b57cec5SDimitry Andric case UTT_IsEmpty: 49580b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49590b57cec5SDimitry Andric return !RD->isUnion() && RD->isEmpty(); 49600b57cec5SDimitry Andric return false; 49610b57cec5SDimitry Andric case UTT_IsPolymorphic: 49620b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49630b57cec5SDimitry Andric return !RD->isUnion() && RD->isPolymorphic(); 49640b57cec5SDimitry Andric return false; 49650b57cec5SDimitry Andric case UTT_IsAbstract: 49660b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49670b57cec5SDimitry Andric return !RD->isUnion() && RD->isAbstract(); 49680b57cec5SDimitry Andric return false; 49690b57cec5SDimitry Andric case UTT_IsAggregate: 49700b57cec5SDimitry Andric // Report vector extensions and complex types as aggregates because they 49710b57cec5SDimitry Andric // support aggregate initialization. GCC mirrors this behavior for vectors 49720b57cec5SDimitry Andric // but not _Complex. 49730b57cec5SDimitry Andric return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || 49740b57cec5SDimitry Andric T->isAnyComplexType(); 49750b57cec5SDimitry Andric // __is_interface_class only returns true when CL is invoked in /CLR mode and 49760b57cec5SDimitry Andric // even then only when it is used with the 'interface struct ...' syntax 49770b57cec5SDimitry Andric // Clang doesn't support /CLR which makes this type trait moot. 49780b57cec5SDimitry Andric case UTT_IsInterfaceClass: 49790b57cec5SDimitry Andric return false; 49800b57cec5SDimitry Andric case UTT_IsFinal: 49810b57cec5SDimitry Andric case UTT_IsSealed: 49820b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49830b57cec5SDimitry Andric return RD->hasAttr<FinalAttr>(); 49840b57cec5SDimitry Andric return false; 49850b57cec5SDimitry Andric case UTT_IsSigned: 4986a7dea167SDimitry Andric // Enum types should always return false. 4987a7dea167SDimitry Andric // Floating points should always return true. 4988fe6060f1SDimitry Andric return T->isFloatingType() || 4989fe6060f1SDimitry Andric (T->isSignedIntegerType() && !T->isEnumeralType()); 49900b57cec5SDimitry Andric case UTT_IsUnsigned: 4991fe6060f1SDimitry Andric // Enum types should always return false. 4992fe6060f1SDimitry Andric return T->isUnsignedIntegerType() && !T->isEnumeralType(); 49930b57cec5SDimitry Andric 49940b57cec5SDimitry Andric // Type trait expressions which query classes regarding their construction, 49950b57cec5SDimitry Andric // destruction, and copying. Rather than being based directly on the 49960b57cec5SDimitry Andric // related type predicates in the standard, they are specified by both 49970b57cec5SDimitry Andric // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 49980b57cec5SDimitry Andric // specifications. 49990b57cec5SDimitry Andric // 50000b57cec5SDimitry Andric // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 50010b57cec5SDimitry Andric // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 50020b57cec5SDimitry Andric // 50030b57cec5SDimitry Andric // Note that these builtins do not behave as documented in g++: if a class 50040b57cec5SDimitry Andric // has both a trivial and a non-trivial special member of a particular kind, 50050b57cec5SDimitry Andric // they return false! For now, we emulate this behavior. 50060b57cec5SDimitry Andric // FIXME: This appears to be a g++ bug: more complex cases reveal that it 50070b57cec5SDimitry Andric // does not correctly compute triviality in the presence of multiple special 50080b57cec5SDimitry Andric // members of the same kind. Revisit this once the g++ bug is fixed. 50090b57cec5SDimitry Andric case UTT_HasTrivialDefaultConstructor: 50100b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 50110b57cec5SDimitry Andric // If __is_pod (type) is true then the trait is true, else if type is 50120b57cec5SDimitry Andric // a cv class or union type (or array thereof) with a trivial default 50130b57cec5SDimitry Andric // constructor ([class.ctor]) then the trait is true, else it is false. 50140b57cec5SDimitry Andric if (T.isPODType(C)) 50150b57cec5SDimitry Andric return true; 50160b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 50170b57cec5SDimitry Andric return RD->hasTrivialDefaultConstructor() && 50180b57cec5SDimitry Andric !RD->hasNonTrivialDefaultConstructor(); 50190b57cec5SDimitry Andric return false; 50200b57cec5SDimitry Andric case UTT_HasTrivialMoveConstructor: 50210b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 50220b57cec5SDimitry Andric // standard library headers. Specifically this is used as the logic 50230b57cec5SDimitry Andric // behind std::is_trivially_move_constructible (20.9.4.3). 50240b57cec5SDimitry Andric if (T.isPODType(C)) 50250b57cec5SDimitry Andric return true; 50260b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 50270b57cec5SDimitry Andric return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 50280b57cec5SDimitry Andric return false; 50290b57cec5SDimitry Andric case UTT_HasTrivialCopy: 50300b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 50310b57cec5SDimitry Andric // If __is_pod (type) is true or type is a reference type then 50320b57cec5SDimitry Andric // the trait is true, else if type is a cv class or union type 50330b57cec5SDimitry Andric // with a trivial copy constructor ([class.copy]) then the trait 50340b57cec5SDimitry Andric // is true, else it is false. 50350b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType()) 50360b57cec5SDimitry Andric return true; 50370b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 50380b57cec5SDimitry Andric return RD->hasTrivialCopyConstructor() && 50390b57cec5SDimitry Andric !RD->hasNonTrivialCopyConstructor(); 50400b57cec5SDimitry Andric return false; 50410b57cec5SDimitry Andric case UTT_HasTrivialMoveAssign: 50420b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 50430b57cec5SDimitry Andric // standard library headers. Specifically it is used as the logic 50440b57cec5SDimitry Andric // behind std::is_trivially_move_assignable (20.9.4.3) 50450b57cec5SDimitry Andric if (T.isPODType(C)) 50460b57cec5SDimitry Andric return true; 50470b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 50480b57cec5SDimitry Andric return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 50490b57cec5SDimitry Andric return false; 50500b57cec5SDimitry Andric case UTT_HasTrivialAssign: 50510b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 50520b57cec5SDimitry Andric // If type is const qualified or is a reference type then the 50530b57cec5SDimitry Andric // trait is false. Otherwise if __is_pod (type) is true then the 50540b57cec5SDimitry Andric // trait is true, else if type is a cv class or union type with 50550b57cec5SDimitry Andric // a trivial copy assignment ([class.copy]) then the trait is 50560b57cec5SDimitry Andric // true, else it is false. 50570b57cec5SDimitry Andric // Note: the const and reference restrictions are interesting, 50580b57cec5SDimitry Andric // given that const and reference members don't prevent a class 50590b57cec5SDimitry Andric // from having a trivial copy assignment operator (but do cause 50600b57cec5SDimitry Andric // errors if the copy assignment operator is actually used, q.v. 50610b57cec5SDimitry Andric // [class.copy]p12). 50620b57cec5SDimitry Andric 50630b57cec5SDimitry Andric if (T.isConstQualified()) 50640b57cec5SDimitry Andric return false; 50650b57cec5SDimitry Andric if (T.isPODType(C)) 50660b57cec5SDimitry Andric return true; 50670b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 50680b57cec5SDimitry Andric return RD->hasTrivialCopyAssignment() && 50690b57cec5SDimitry Andric !RD->hasNonTrivialCopyAssignment(); 50700b57cec5SDimitry Andric return false; 50710b57cec5SDimitry Andric case UTT_IsDestructible: 50720b57cec5SDimitry Andric case UTT_IsTriviallyDestructible: 50730b57cec5SDimitry Andric case UTT_IsNothrowDestructible: 50740b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 50750b57cec5SDimitry Andric // For reference types, is_destructible<T>::value is true. 50760b57cec5SDimitry Andric if (T->isReferenceType()) 50770b57cec5SDimitry Andric return true; 50780b57cec5SDimitry Andric 50790b57cec5SDimitry Andric // Objective-C++ ARC: autorelease types don't require destruction. 50800b57cec5SDimitry Andric if (T->isObjCLifetimeType() && 50810b57cec5SDimitry Andric T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 50820b57cec5SDimitry Andric return true; 50830b57cec5SDimitry Andric 50840b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 50850b57cec5SDimitry Andric // For incomplete types and function types, is_destructible<T>::value is 50860b57cec5SDimitry Andric // false. 50870b57cec5SDimitry Andric if (T->isIncompleteType() || T->isFunctionType()) 50880b57cec5SDimitry Andric return false; 50890b57cec5SDimitry Andric 50900b57cec5SDimitry Andric // A type that requires destruction (via a non-trivial destructor or ARC 50910b57cec5SDimitry Andric // lifetime semantics) is not trivially-destructible. 50920b57cec5SDimitry Andric if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) 50930b57cec5SDimitry Andric return false; 50940b57cec5SDimitry Andric 50950b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 50960b57cec5SDimitry Andric // For object types and given U equal to remove_all_extents_t<T>, if the 50970b57cec5SDimitry Andric // expression std::declval<U&>().~U() is well-formed when treated as an 50980b57cec5SDimitry Andric // unevaluated operand (Clause 5), then is_destructible<T>::value is true 50990b57cec5SDimitry Andric if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 51000b57cec5SDimitry Andric CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 51010b57cec5SDimitry Andric if (!Destructor) 51020b57cec5SDimitry Andric return false; 51030b57cec5SDimitry Andric // C++14 [dcl.fct.def.delete]p2: 51040b57cec5SDimitry Andric // A program that refers to a deleted function implicitly or 51050b57cec5SDimitry Andric // explicitly, other than to declare it, is ill-formed. 51060b57cec5SDimitry Andric if (Destructor->isDeleted()) 51070b57cec5SDimitry Andric return false; 51080b57cec5SDimitry Andric if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 51090b57cec5SDimitry Andric return false; 51100b57cec5SDimitry Andric if (UTT == UTT_IsNothrowDestructible) { 51115ffd83dbSDimitry Andric auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); 51120b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 51130b57cec5SDimitry Andric if (!CPT || !CPT->isNothrow()) 51140b57cec5SDimitry Andric return false; 51150b57cec5SDimitry Andric } 51160b57cec5SDimitry Andric } 51170b57cec5SDimitry Andric return true; 51180b57cec5SDimitry Andric 51190b57cec5SDimitry Andric case UTT_HasTrivialDestructor: 51200b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 51210b57cec5SDimitry Andric // If __is_pod (type) is true or type is a reference type 51220b57cec5SDimitry Andric // then the trait is true, else if type is a cv class or union 51230b57cec5SDimitry Andric // type (or array thereof) with a trivial destructor 51240b57cec5SDimitry Andric // ([class.dtor]) then the trait is true, else it is 51250b57cec5SDimitry Andric // false. 51260b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType()) 51270b57cec5SDimitry Andric return true; 51280b57cec5SDimitry Andric 51290b57cec5SDimitry Andric // Objective-C++ ARC: autorelease types don't require destruction. 51300b57cec5SDimitry Andric if (T->isObjCLifetimeType() && 51310b57cec5SDimitry Andric T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 51320b57cec5SDimitry Andric return true; 51330b57cec5SDimitry Andric 51340b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 51350b57cec5SDimitry Andric return RD->hasTrivialDestructor(); 51360b57cec5SDimitry Andric return false; 51370b57cec5SDimitry Andric // TODO: Propagate nothrowness for implicitly declared special members. 51380b57cec5SDimitry Andric case UTT_HasNothrowAssign: 51390b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 51400b57cec5SDimitry Andric // If type is const qualified or is a reference type then the 51410b57cec5SDimitry Andric // trait is false. Otherwise if __has_trivial_assign (type) 51420b57cec5SDimitry Andric // is true then the trait is true, else if type is a cv class 51430b57cec5SDimitry Andric // or union type with copy assignment operators that are known 51440b57cec5SDimitry Andric // not to throw an exception then the trait is true, else it is 51450b57cec5SDimitry Andric // false. 51460b57cec5SDimitry Andric if (C.getBaseElementType(T).isConstQualified()) 51470b57cec5SDimitry Andric return false; 51480b57cec5SDimitry Andric if (T->isReferenceType()) 51490b57cec5SDimitry Andric return false; 51500b57cec5SDimitry Andric if (T.isPODType(C) || T->isObjCLifetimeType()) 51510b57cec5SDimitry Andric return true; 51520b57cec5SDimitry Andric 51530b57cec5SDimitry Andric if (const RecordType *RT = T->getAs<RecordType>()) 51540b57cec5SDimitry Andric return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 51550b57cec5SDimitry Andric &CXXRecordDecl::hasTrivialCopyAssignment, 51560b57cec5SDimitry Andric &CXXRecordDecl::hasNonTrivialCopyAssignment, 51570b57cec5SDimitry Andric &CXXMethodDecl::isCopyAssignmentOperator); 51580b57cec5SDimitry Andric return false; 51590b57cec5SDimitry Andric case UTT_HasNothrowMoveAssign: 51600b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 51610b57cec5SDimitry Andric // standard library headers. Specifically this is used as the logic 51620b57cec5SDimitry Andric // behind std::is_nothrow_move_assignable (20.9.4.3). 51630b57cec5SDimitry Andric if (T.isPODType(C)) 51640b57cec5SDimitry Andric return true; 51650b57cec5SDimitry Andric 51660b57cec5SDimitry Andric if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 51670b57cec5SDimitry Andric return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 51680b57cec5SDimitry Andric &CXXRecordDecl::hasTrivialMoveAssignment, 51690b57cec5SDimitry Andric &CXXRecordDecl::hasNonTrivialMoveAssignment, 51700b57cec5SDimitry Andric &CXXMethodDecl::isMoveAssignmentOperator); 51710b57cec5SDimitry Andric return false; 51720b57cec5SDimitry Andric case UTT_HasNothrowCopy: 51730b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 51740b57cec5SDimitry Andric // If __has_trivial_copy (type) is true then the trait is true, else 51750b57cec5SDimitry Andric // if type is a cv class or union type with copy constructors that are 51760b57cec5SDimitry Andric // known not to throw an exception then the trait is true, else it is 51770b57cec5SDimitry Andric // false. 51780b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 51790b57cec5SDimitry Andric return true; 51800b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 51810b57cec5SDimitry Andric if (RD->hasTrivialCopyConstructor() && 51820b57cec5SDimitry Andric !RD->hasNonTrivialCopyConstructor()) 51830b57cec5SDimitry Andric return true; 51840b57cec5SDimitry Andric 51850b57cec5SDimitry Andric bool FoundConstructor = false; 51860b57cec5SDimitry Andric unsigned FoundTQs; 51870b57cec5SDimitry Andric for (const auto *ND : Self.LookupConstructors(RD)) { 51880b57cec5SDimitry Andric // A template constructor is never a copy constructor. 51890b57cec5SDimitry Andric // FIXME: However, it may actually be selected at the actual overload 51900b57cec5SDimitry Andric // resolution point. 51910b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 51920b57cec5SDimitry Andric continue; 51930b57cec5SDimitry Andric // UsingDecl itself is not a constructor 51940b57cec5SDimitry Andric if (isa<UsingDecl>(ND)) 51950b57cec5SDimitry Andric continue; 51960b57cec5SDimitry Andric auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 51970b57cec5SDimitry Andric if (Constructor->isCopyConstructor(FoundTQs)) { 51980b57cec5SDimitry Andric FoundConstructor = true; 51995ffd83dbSDimitry Andric auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 52000b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 52010b57cec5SDimitry Andric if (!CPT) 52020b57cec5SDimitry Andric return false; 52030b57cec5SDimitry Andric // TODO: check whether evaluating default arguments can throw. 52040b57cec5SDimitry Andric // For now, we'll be conservative and assume that they can throw. 52050b57cec5SDimitry Andric if (!CPT->isNothrow() || CPT->getNumParams() > 1) 52060b57cec5SDimitry Andric return false; 52070b57cec5SDimitry Andric } 52080b57cec5SDimitry Andric } 52090b57cec5SDimitry Andric 52100b57cec5SDimitry Andric return FoundConstructor; 52110b57cec5SDimitry Andric } 52120b57cec5SDimitry Andric return false; 52130b57cec5SDimitry Andric case UTT_HasNothrowConstructor: 52140b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 52150b57cec5SDimitry Andric // If __has_trivial_constructor (type) is true then the trait is 52160b57cec5SDimitry Andric // true, else if type is a cv class or union type (or array 52170b57cec5SDimitry Andric // thereof) with a default constructor that is known not to 52180b57cec5SDimitry Andric // throw an exception then the trait is true, else it is false. 52190b57cec5SDimitry Andric if (T.isPODType(C) || T->isObjCLifetimeType()) 52200b57cec5SDimitry Andric return true; 52210b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 52220b57cec5SDimitry Andric if (RD->hasTrivialDefaultConstructor() && 52230b57cec5SDimitry Andric !RD->hasNonTrivialDefaultConstructor()) 52240b57cec5SDimitry Andric return true; 52250b57cec5SDimitry Andric 52260b57cec5SDimitry Andric bool FoundConstructor = false; 52270b57cec5SDimitry Andric for (const auto *ND : Self.LookupConstructors(RD)) { 52280b57cec5SDimitry Andric // FIXME: In C++0x, a constructor template can be a default constructor. 52290b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 52300b57cec5SDimitry Andric continue; 52310b57cec5SDimitry Andric // UsingDecl itself is not a constructor 52320b57cec5SDimitry Andric if (isa<UsingDecl>(ND)) 52330b57cec5SDimitry Andric continue; 52340b57cec5SDimitry Andric auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 52350b57cec5SDimitry Andric if (Constructor->isDefaultConstructor()) { 52360b57cec5SDimitry Andric FoundConstructor = true; 52375ffd83dbSDimitry Andric auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 52380b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 52390b57cec5SDimitry Andric if (!CPT) 52400b57cec5SDimitry Andric return false; 52410b57cec5SDimitry Andric // FIXME: check whether evaluating default arguments can throw. 52420b57cec5SDimitry Andric // For now, we'll be conservative and assume that they can throw. 52430b57cec5SDimitry Andric if (!CPT->isNothrow() || CPT->getNumParams() > 0) 52440b57cec5SDimitry Andric return false; 52450b57cec5SDimitry Andric } 52460b57cec5SDimitry Andric } 52470b57cec5SDimitry Andric return FoundConstructor; 52480b57cec5SDimitry Andric } 52490b57cec5SDimitry Andric return false; 52500b57cec5SDimitry Andric case UTT_HasVirtualDestructor: 52510b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 52520b57cec5SDimitry Andric // If type is a class type with a virtual destructor ([class.dtor]) 52530b57cec5SDimitry Andric // then the trait is true, else it is false. 52540b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 52550b57cec5SDimitry Andric if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 52560b57cec5SDimitry Andric return Destructor->isVirtual(); 52570b57cec5SDimitry Andric return false; 52580b57cec5SDimitry Andric 52590b57cec5SDimitry Andric // These type trait expressions are modeled on the specifications for the 52600b57cec5SDimitry Andric // Embarcadero C++0x type trait functions: 52610b57cec5SDimitry Andric // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 52620b57cec5SDimitry Andric case UTT_IsCompleteType: 52630b57cec5SDimitry Andric // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 52640b57cec5SDimitry Andric // Returns True if and only if T is a complete type at the point of the 52650b57cec5SDimitry Andric // function call. 52660b57cec5SDimitry Andric return !T->isIncompleteType(); 52670b57cec5SDimitry Andric case UTT_HasUniqueObjectRepresentations: 52680b57cec5SDimitry Andric return C.hasUniqueObjectRepresentations(T); 526981ad6265SDimitry Andric case UTT_IsTriviallyRelocatable: 527081ad6265SDimitry Andric return T.isTriviallyRelocatableType(C); 52710b57cec5SDimitry Andric } 52720b57cec5SDimitry Andric } 52730b57cec5SDimitry Andric 52740b57cec5SDimitry Andric static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 52750b57cec5SDimitry Andric QualType RhsT, SourceLocation KeyLoc); 52760b57cec5SDimitry Andric 52770b57cec5SDimitry Andric static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 52780b57cec5SDimitry Andric ArrayRef<TypeSourceInfo *> Args, 52790b57cec5SDimitry Andric SourceLocation RParenLoc) { 52800b57cec5SDimitry Andric if (Kind <= UTT_Last) 52810b57cec5SDimitry Andric return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); 52820b57cec5SDimitry Andric 52830b57cec5SDimitry Andric // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible 52840b57cec5SDimitry Andric // traits to avoid duplication. 52850b57cec5SDimitry Andric if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) 52860b57cec5SDimitry Andric return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), 52870b57cec5SDimitry Andric Args[1]->getType(), RParenLoc); 52880b57cec5SDimitry Andric 52890b57cec5SDimitry Andric switch (Kind) { 52900b57cec5SDimitry Andric case clang::BTT_ReferenceBindsToTemporary: 52910b57cec5SDimitry Andric case clang::TT_IsConstructible: 52920b57cec5SDimitry Andric case clang::TT_IsNothrowConstructible: 52930b57cec5SDimitry Andric case clang::TT_IsTriviallyConstructible: { 52940b57cec5SDimitry Andric // C++11 [meta.unary.prop]: 52950b57cec5SDimitry Andric // is_trivially_constructible is defined as: 52960b57cec5SDimitry Andric // 52970b57cec5SDimitry Andric // is_constructible<T, Args...>::value is true and the variable 52980b57cec5SDimitry Andric // definition for is_constructible, as defined below, is known to call 52990b57cec5SDimitry Andric // no operation that is not trivial. 53000b57cec5SDimitry Andric // 53010b57cec5SDimitry Andric // The predicate condition for a template specialization 53020b57cec5SDimitry Andric // is_constructible<T, Args...> shall be satisfied if and only if the 53030b57cec5SDimitry Andric // following variable definition would be well-formed for some invented 53040b57cec5SDimitry Andric // variable t: 53050b57cec5SDimitry Andric // 53060b57cec5SDimitry Andric // T t(create<Args>()...); 53070b57cec5SDimitry Andric assert(!Args.empty()); 53080b57cec5SDimitry Andric 53090b57cec5SDimitry Andric // Precondition: T and all types in the parameter pack Args shall be 53100b57cec5SDimitry Andric // complete types, (possibly cv-qualified) void, or arrays of 53110b57cec5SDimitry Andric // unknown bound. 53120b57cec5SDimitry Andric for (const auto *TSI : Args) { 53130b57cec5SDimitry Andric QualType ArgTy = TSI->getType(); 53140b57cec5SDimitry Andric if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 53150b57cec5SDimitry Andric continue; 53160b57cec5SDimitry Andric 53170b57cec5SDimitry Andric if (S.RequireCompleteType(KWLoc, ArgTy, 53180b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 53190b57cec5SDimitry Andric return false; 53200b57cec5SDimitry Andric } 53210b57cec5SDimitry Andric 53220b57cec5SDimitry Andric // Make sure the first argument is not incomplete nor a function type. 53230b57cec5SDimitry Andric QualType T = Args[0]->getType(); 53240b57cec5SDimitry Andric if (T->isIncompleteType() || T->isFunctionType()) 53250b57cec5SDimitry Andric return false; 53260b57cec5SDimitry Andric 53270b57cec5SDimitry Andric // Make sure the first argument is not an abstract type. 53280b57cec5SDimitry Andric CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 53290b57cec5SDimitry Andric if (RD && RD->isAbstract()) 53300b57cec5SDimitry Andric return false; 53310b57cec5SDimitry Andric 53325ffd83dbSDimitry Andric llvm::BumpPtrAllocator OpaqueExprAllocator; 53330b57cec5SDimitry Andric SmallVector<Expr *, 2> ArgExprs; 53340b57cec5SDimitry Andric ArgExprs.reserve(Args.size() - 1); 53350b57cec5SDimitry Andric for (unsigned I = 1, N = Args.size(); I != N; ++I) { 53360b57cec5SDimitry Andric QualType ArgTy = Args[I]->getType(); 53370b57cec5SDimitry Andric if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 53380b57cec5SDimitry Andric ArgTy = S.Context.getRValueReferenceType(ArgTy); 53395ffd83dbSDimitry Andric ArgExprs.push_back( 53405ffd83dbSDimitry Andric new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) 53410b57cec5SDimitry Andric OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), 53420b57cec5SDimitry Andric ArgTy.getNonLValueExprType(S.Context), 53430b57cec5SDimitry Andric Expr::getValueKindForType(ArgTy))); 53440b57cec5SDimitry Andric } 53450b57cec5SDimitry Andric 53460b57cec5SDimitry Andric // Perform the initialization in an unevaluated context within a SFINAE 53470b57cec5SDimitry Andric // trap at translation unit scope. 53480b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 53490b57cec5SDimitry Andric S, Sema::ExpressionEvaluationContext::Unevaluated); 53500b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 53510b57cec5SDimitry Andric Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 5352349cc55cSDimitry Andric InitializedEntity To( 5353349cc55cSDimitry Andric InitializedEntity::InitializeTemporary(S.Context, Args[0])); 53540b57cec5SDimitry Andric InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 53550b57cec5SDimitry Andric RParenLoc)); 53560b57cec5SDimitry Andric InitializationSequence Init(S, To, InitKind, ArgExprs); 53570b57cec5SDimitry Andric if (Init.Failed()) 53580b57cec5SDimitry Andric return false; 53590b57cec5SDimitry Andric 53600b57cec5SDimitry Andric ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 53610b57cec5SDimitry Andric if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 53620b57cec5SDimitry Andric return false; 53630b57cec5SDimitry Andric 53640b57cec5SDimitry Andric if (Kind == clang::TT_IsConstructible) 53650b57cec5SDimitry Andric return true; 53660b57cec5SDimitry Andric 53670b57cec5SDimitry Andric if (Kind == clang::BTT_ReferenceBindsToTemporary) { 53680b57cec5SDimitry Andric if (!T->isReferenceType()) 53690b57cec5SDimitry Andric return false; 53700b57cec5SDimitry Andric 53710b57cec5SDimitry Andric return !Init.isDirectReferenceBinding(); 53720b57cec5SDimitry Andric } 53730b57cec5SDimitry Andric 53740b57cec5SDimitry Andric if (Kind == clang::TT_IsNothrowConstructible) 53750b57cec5SDimitry Andric return S.canThrow(Result.get()) == CT_Cannot; 53760b57cec5SDimitry Andric 53770b57cec5SDimitry Andric if (Kind == clang::TT_IsTriviallyConstructible) { 53780b57cec5SDimitry Andric // Under Objective-C ARC and Weak, if the destination has non-trivial 53790b57cec5SDimitry Andric // Objective-C lifetime, this is a non-trivial construction. 53800b57cec5SDimitry Andric if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) 53810b57cec5SDimitry Andric return false; 53820b57cec5SDimitry Andric 53830b57cec5SDimitry Andric // The initialization succeeded; now make sure there are no non-trivial 53840b57cec5SDimitry Andric // calls. 53850b57cec5SDimitry Andric return !Result.get()->hasNonTrivialCall(S.Context); 53860b57cec5SDimitry Andric } 53870b57cec5SDimitry Andric 53880b57cec5SDimitry Andric llvm_unreachable("unhandled type trait"); 53890b57cec5SDimitry Andric return false; 53900b57cec5SDimitry Andric } 53910b57cec5SDimitry Andric default: llvm_unreachable("not a TT"); 53920b57cec5SDimitry Andric } 53930b57cec5SDimitry Andric 53940b57cec5SDimitry Andric return false; 53950b57cec5SDimitry Andric } 53960b57cec5SDimitry Andric 5397753f127fSDimitry Andric namespace { 5398753f127fSDimitry Andric void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind, 5399753f127fSDimitry Andric SourceLocation KWLoc) { 5400753f127fSDimitry Andric TypeTrait Replacement; 5401753f127fSDimitry Andric switch (Kind) { 5402753f127fSDimitry Andric case UTT_HasNothrowAssign: 5403753f127fSDimitry Andric case UTT_HasNothrowMoveAssign: 5404753f127fSDimitry Andric Replacement = BTT_IsNothrowAssignable; 5405753f127fSDimitry Andric break; 5406753f127fSDimitry Andric case UTT_HasNothrowCopy: 5407753f127fSDimitry Andric case UTT_HasNothrowConstructor: 5408753f127fSDimitry Andric Replacement = TT_IsNothrowConstructible; 5409753f127fSDimitry Andric break; 5410753f127fSDimitry Andric case UTT_HasTrivialAssign: 5411753f127fSDimitry Andric case UTT_HasTrivialMoveAssign: 5412753f127fSDimitry Andric Replacement = BTT_IsTriviallyAssignable; 5413753f127fSDimitry Andric break; 5414753f127fSDimitry Andric case UTT_HasTrivialCopy: 5415753f127fSDimitry Andric case UTT_HasTrivialDefaultConstructor: 5416753f127fSDimitry Andric case UTT_HasTrivialMoveConstructor: 5417753f127fSDimitry Andric Replacement = TT_IsTriviallyConstructible; 5418753f127fSDimitry Andric break; 5419753f127fSDimitry Andric case UTT_HasTrivialDestructor: 5420753f127fSDimitry Andric Replacement = UTT_IsTriviallyDestructible; 5421753f127fSDimitry Andric break; 5422753f127fSDimitry Andric default: 5423753f127fSDimitry Andric return; 5424753f127fSDimitry Andric } 5425753f127fSDimitry Andric S.Diag(KWLoc, diag::warn_deprecated_builtin) 5426753f127fSDimitry Andric << getTraitSpelling(Kind) << getTraitSpelling(Replacement); 5427753f127fSDimitry Andric } 5428753f127fSDimitry Andric } 5429753f127fSDimitry Andric 54300b57cec5SDimitry Andric ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 54310b57cec5SDimitry Andric ArrayRef<TypeSourceInfo *> Args, 54320b57cec5SDimitry Andric SourceLocation RParenLoc) { 54330b57cec5SDimitry Andric QualType ResultType = Context.getLogicalOperationType(); 54340b57cec5SDimitry Andric 54350b57cec5SDimitry Andric if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 54360b57cec5SDimitry Andric *this, Kind, KWLoc, Args[0]->getType())) 54370b57cec5SDimitry Andric return ExprError(); 54380b57cec5SDimitry Andric 5439753f127fSDimitry Andric DiagnoseBuiltinDeprecation(*this, Kind, KWLoc); 5440753f127fSDimitry Andric 54410b57cec5SDimitry Andric bool Dependent = false; 54420b57cec5SDimitry Andric for (unsigned I = 0, N = Args.size(); I != N; ++I) { 54430b57cec5SDimitry Andric if (Args[I]->getType()->isDependentType()) { 54440b57cec5SDimitry Andric Dependent = true; 54450b57cec5SDimitry Andric break; 54460b57cec5SDimitry Andric } 54470b57cec5SDimitry Andric } 54480b57cec5SDimitry Andric 54490b57cec5SDimitry Andric bool Result = false; 54500b57cec5SDimitry Andric if (!Dependent) 54510b57cec5SDimitry Andric Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 54520b57cec5SDimitry Andric 54530b57cec5SDimitry Andric return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, 54540b57cec5SDimitry Andric RParenLoc, Result); 54550b57cec5SDimitry Andric } 54560b57cec5SDimitry Andric 54570b57cec5SDimitry Andric ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 54580b57cec5SDimitry Andric ArrayRef<ParsedType> Args, 54590b57cec5SDimitry Andric SourceLocation RParenLoc) { 54600b57cec5SDimitry Andric SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 54610b57cec5SDimitry Andric ConvertedArgs.reserve(Args.size()); 54620b57cec5SDimitry Andric 54630b57cec5SDimitry Andric for (unsigned I = 0, N = Args.size(); I != N; ++I) { 54640b57cec5SDimitry Andric TypeSourceInfo *TInfo; 54650b57cec5SDimitry Andric QualType T = GetTypeFromParser(Args[I], &TInfo); 54660b57cec5SDimitry Andric if (!TInfo) 54670b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 54680b57cec5SDimitry Andric 54690b57cec5SDimitry Andric ConvertedArgs.push_back(TInfo); 54700b57cec5SDimitry Andric } 54710b57cec5SDimitry Andric 54720b57cec5SDimitry Andric return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 54730b57cec5SDimitry Andric } 54740b57cec5SDimitry Andric 54750b57cec5SDimitry Andric static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 54760b57cec5SDimitry Andric QualType RhsT, SourceLocation KeyLoc) { 54770b57cec5SDimitry Andric assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 54780b57cec5SDimitry Andric "Cannot evaluate traits of dependent types"); 54790b57cec5SDimitry Andric 54800b57cec5SDimitry Andric switch(BTT) { 54810b57cec5SDimitry Andric case BTT_IsBaseOf: { 54820b57cec5SDimitry Andric // C++0x [meta.rel]p2 54830b57cec5SDimitry Andric // Base is a base class of Derived without regard to cv-qualifiers or 54840b57cec5SDimitry Andric // Base and Derived are not unions and name the same class type without 54850b57cec5SDimitry Andric // regard to cv-qualifiers. 54860b57cec5SDimitry Andric 54870b57cec5SDimitry Andric const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 54880b57cec5SDimitry Andric const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 54890b57cec5SDimitry Andric if (!rhsRecord || !lhsRecord) { 54900b57cec5SDimitry Andric const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); 54910b57cec5SDimitry Andric const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); 54920b57cec5SDimitry Andric if (!LHSObjTy || !RHSObjTy) 54930b57cec5SDimitry Andric return false; 54940b57cec5SDimitry Andric 54950b57cec5SDimitry Andric ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); 54960b57cec5SDimitry Andric ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); 54970b57cec5SDimitry Andric if (!BaseInterface || !DerivedInterface) 54980b57cec5SDimitry Andric return false; 54990b57cec5SDimitry Andric 55000b57cec5SDimitry Andric if (Self.RequireCompleteType( 55010b57cec5SDimitry Andric KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) 55020b57cec5SDimitry Andric return false; 55030b57cec5SDimitry Andric 55040b57cec5SDimitry Andric return BaseInterface->isSuperClassOf(DerivedInterface); 55050b57cec5SDimitry Andric } 55060b57cec5SDimitry Andric 55070b57cec5SDimitry Andric assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 55080b57cec5SDimitry Andric == (lhsRecord == rhsRecord)); 55090b57cec5SDimitry Andric 55100b57cec5SDimitry Andric // Unions are never base classes, and never have base classes. 55110b57cec5SDimitry Andric // It doesn't matter if they are complete or not. See PR#41843 55120b57cec5SDimitry Andric if (lhsRecord && lhsRecord->getDecl()->isUnion()) 55130b57cec5SDimitry Andric return false; 55140b57cec5SDimitry Andric if (rhsRecord && rhsRecord->getDecl()->isUnion()) 55150b57cec5SDimitry Andric return false; 55160b57cec5SDimitry Andric 55170b57cec5SDimitry Andric if (lhsRecord == rhsRecord) 55180b57cec5SDimitry Andric return true; 55190b57cec5SDimitry Andric 55200b57cec5SDimitry Andric // C++0x [meta.rel]p2: 55210b57cec5SDimitry Andric // If Base and Derived are class types and are different types 55220b57cec5SDimitry Andric // (ignoring possible cv-qualifiers) then Derived shall be a 55230b57cec5SDimitry Andric // complete type. 55240b57cec5SDimitry Andric if (Self.RequireCompleteType(KeyLoc, RhsT, 55250b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 55260b57cec5SDimitry Andric return false; 55270b57cec5SDimitry Andric 55280b57cec5SDimitry Andric return cast<CXXRecordDecl>(rhsRecord->getDecl()) 55290b57cec5SDimitry Andric ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 55300b57cec5SDimitry Andric } 55310b57cec5SDimitry Andric case BTT_IsSame: 55320b57cec5SDimitry Andric return Self.Context.hasSameType(LhsT, RhsT); 55330b57cec5SDimitry Andric case BTT_TypeCompatible: { 55340b57cec5SDimitry Andric // GCC ignores cv-qualifiers on arrays for this builtin. 55350b57cec5SDimitry Andric Qualifiers LhsQuals, RhsQuals; 55360b57cec5SDimitry Andric QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); 55370b57cec5SDimitry Andric QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); 55380b57cec5SDimitry Andric return Self.Context.typesAreCompatible(Lhs, Rhs); 55390b57cec5SDimitry Andric } 55400b57cec5SDimitry Andric case BTT_IsConvertible: 55410b57cec5SDimitry Andric case BTT_IsConvertibleTo: { 55420b57cec5SDimitry Andric // C++0x [meta.rel]p4: 55430b57cec5SDimitry Andric // Given the following function prototype: 55440b57cec5SDimitry Andric // 55450b57cec5SDimitry Andric // template <class T> 55460b57cec5SDimitry Andric // typename add_rvalue_reference<T>::type create(); 55470b57cec5SDimitry Andric // 55480b57cec5SDimitry Andric // the predicate condition for a template specialization 55490b57cec5SDimitry Andric // is_convertible<From, To> shall be satisfied if and only if 55500b57cec5SDimitry Andric // the return expression in the following code would be 55510b57cec5SDimitry Andric // well-formed, including any implicit conversions to the return 55520b57cec5SDimitry Andric // type of the function: 55530b57cec5SDimitry Andric // 55540b57cec5SDimitry Andric // To test() { 55550b57cec5SDimitry Andric // return create<From>(); 55560b57cec5SDimitry Andric // } 55570b57cec5SDimitry Andric // 55580b57cec5SDimitry Andric // Access checking is performed as if in a context unrelated to To and 55590b57cec5SDimitry Andric // From. Only the validity of the immediate context of the expression 55600b57cec5SDimitry Andric // of the return-statement (including conversions to the return type) 55610b57cec5SDimitry Andric // is considered. 55620b57cec5SDimitry Andric // 55630b57cec5SDimitry Andric // We model the initialization as a copy-initialization of a temporary 55640b57cec5SDimitry Andric // of the appropriate type, which for this expression is identical to the 55650b57cec5SDimitry Andric // return statement (since NRVO doesn't apply). 55660b57cec5SDimitry Andric 55670b57cec5SDimitry Andric // Functions aren't allowed to return function or array types. 55680b57cec5SDimitry Andric if (RhsT->isFunctionType() || RhsT->isArrayType()) 55690b57cec5SDimitry Andric return false; 55700b57cec5SDimitry Andric 55710b57cec5SDimitry Andric // A return statement in a void function must have void type. 55720b57cec5SDimitry Andric if (RhsT->isVoidType()) 55730b57cec5SDimitry Andric return LhsT->isVoidType(); 55740b57cec5SDimitry Andric 55750b57cec5SDimitry Andric // A function definition requires a complete, non-abstract return type. 55760b57cec5SDimitry Andric if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) 55770b57cec5SDimitry Andric return false; 55780b57cec5SDimitry Andric 55790b57cec5SDimitry Andric // Compute the result of add_rvalue_reference. 55800b57cec5SDimitry Andric if (LhsT->isObjectType() || LhsT->isFunctionType()) 55810b57cec5SDimitry Andric LhsT = Self.Context.getRValueReferenceType(LhsT); 55820b57cec5SDimitry Andric 55830b57cec5SDimitry Andric // Build a fake source and destination for initialization. 55840b57cec5SDimitry Andric InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 55850b57cec5SDimitry Andric OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 55860b57cec5SDimitry Andric Expr::getValueKindForType(LhsT)); 55870b57cec5SDimitry Andric Expr *FromPtr = &From; 55880b57cec5SDimitry Andric InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 55890b57cec5SDimitry Andric SourceLocation())); 55900b57cec5SDimitry Andric 55910b57cec5SDimitry Andric // Perform the initialization in an unevaluated context within a SFINAE 55920b57cec5SDimitry Andric // trap at translation unit scope. 55930b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 55940b57cec5SDimitry Andric Self, Sema::ExpressionEvaluationContext::Unevaluated); 55950b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 55960b57cec5SDimitry Andric Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 55970b57cec5SDimitry Andric InitializationSequence Init(Self, To, Kind, FromPtr); 55980b57cec5SDimitry Andric if (Init.Failed()) 55990b57cec5SDimitry Andric return false; 56000b57cec5SDimitry Andric 56010b57cec5SDimitry Andric ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 56020b57cec5SDimitry Andric return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 56030b57cec5SDimitry Andric } 56040b57cec5SDimitry Andric 56050b57cec5SDimitry Andric case BTT_IsAssignable: 56060b57cec5SDimitry Andric case BTT_IsNothrowAssignable: 56070b57cec5SDimitry Andric case BTT_IsTriviallyAssignable: { 56080b57cec5SDimitry Andric // C++11 [meta.unary.prop]p3: 56090b57cec5SDimitry Andric // is_trivially_assignable is defined as: 56100b57cec5SDimitry Andric // is_assignable<T, U>::value is true and the assignment, as defined by 56110b57cec5SDimitry Andric // is_assignable, is known to call no operation that is not trivial 56120b57cec5SDimitry Andric // 56130b57cec5SDimitry Andric // is_assignable is defined as: 56140b57cec5SDimitry Andric // The expression declval<T>() = declval<U>() is well-formed when 56150b57cec5SDimitry Andric // treated as an unevaluated operand (Clause 5). 56160b57cec5SDimitry Andric // 56170b57cec5SDimitry Andric // For both, T and U shall be complete types, (possibly cv-qualified) 56180b57cec5SDimitry Andric // void, or arrays of unknown bound. 56190b57cec5SDimitry Andric if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 56200b57cec5SDimitry Andric Self.RequireCompleteType(KeyLoc, LhsT, 56210b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 56220b57cec5SDimitry Andric return false; 56230b57cec5SDimitry Andric if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 56240b57cec5SDimitry Andric Self.RequireCompleteType(KeyLoc, RhsT, 56250b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 56260b57cec5SDimitry Andric return false; 56270b57cec5SDimitry Andric 56280b57cec5SDimitry Andric // cv void is never assignable. 56290b57cec5SDimitry Andric if (LhsT->isVoidType() || RhsT->isVoidType()) 56300b57cec5SDimitry Andric return false; 56310b57cec5SDimitry Andric 56320b57cec5SDimitry Andric // Build expressions that emulate the effect of declval<T>() and 56330b57cec5SDimitry Andric // declval<U>(). 56340b57cec5SDimitry Andric if (LhsT->isObjectType() || LhsT->isFunctionType()) 56350b57cec5SDimitry Andric LhsT = Self.Context.getRValueReferenceType(LhsT); 56360b57cec5SDimitry Andric if (RhsT->isObjectType() || RhsT->isFunctionType()) 56370b57cec5SDimitry Andric RhsT = Self.Context.getRValueReferenceType(RhsT); 56380b57cec5SDimitry Andric OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 56390b57cec5SDimitry Andric Expr::getValueKindForType(LhsT)); 56400b57cec5SDimitry Andric OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 56410b57cec5SDimitry Andric Expr::getValueKindForType(RhsT)); 56420b57cec5SDimitry Andric 56430b57cec5SDimitry Andric // Attempt the assignment in an unevaluated context within a SFINAE 56440b57cec5SDimitry Andric // trap at translation unit scope. 56450b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 56460b57cec5SDimitry Andric Self, Sema::ExpressionEvaluationContext::Unevaluated); 56470b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 56480b57cec5SDimitry Andric Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 56490b57cec5SDimitry Andric ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 56500b57cec5SDimitry Andric &Rhs); 5651a7dea167SDimitry Andric if (Result.isInvalid()) 5652a7dea167SDimitry Andric return false; 5653a7dea167SDimitry Andric 5654a7dea167SDimitry Andric // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. 5655a7dea167SDimitry Andric Self.CheckUnusedVolatileAssignment(Result.get()); 5656a7dea167SDimitry Andric 5657a7dea167SDimitry Andric if (SFINAE.hasErrorOccurred()) 56580b57cec5SDimitry Andric return false; 56590b57cec5SDimitry Andric 56600b57cec5SDimitry Andric if (BTT == BTT_IsAssignable) 56610b57cec5SDimitry Andric return true; 56620b57cec5SDimitry Andric 56630b57cec5SDimitry Andric if (BTT == BTT_IsNothrowAssignable) 56640b57cec5SDimitry Andric return Self.canThrow(Result.get()) == CT_Cannot; 56650b57cec5SDimitry Andric 56660b57cec5SDimitry Andric if (BTT == BTT_IsTriviallyAssignable) { 56670b57cec5SDimitry Andric // Under Objective-C ARC and Weak, if the destination has non-trivial 56680b57cec5SDimitry Andric // Objective-C lifetime, this is a non-trivial assignment. 56690b57cec5SDimitry Andric if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) 56700b57cec5SDimitry Andric return false; 56710b57cec5SDimitry Andric 56720b57cec5SDimitry Andric return !Result.get()->hasNonTrivialCall(Self.Context); 56730b57cec5SDimitry Andric } 56740b57cec5SDimitry Andric 56750b57cec5SDimitry Andric llvm_unreachable("unhandled type trait"); 56760b57cec5SDimitry Andric return false; 56770b57cec5SDimitry Andric } 56780b57cec5SDimitry Andric default: llvm_unreachable("not a BTT"); 56790b57cec5SDimitry Andric } 56800b57cec5SDimitry Andric llvm_unreachable("Unknown type trait or not implemented"); 56810b57cec5SDimitry Andric } 56820b57cec5SDimitry Andric 56830b57cec5SDimitry Andric ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 56840b57cec5SDimitry Andric SourceLocation KWLoc, 56850b57cec5SDimitry Andric ParsedType Ty, 56860b57cec5SDimitry Andric Expr* DimExpr, 56870b57cec5SDimitry Andric SourceLocation RParen) { 56880b57cec5SDimitry Andric TypeSourceInfo *TSInfo; 56890b57cec5SDimitry Andric QualType T = GetTypeFromParser(Ty, &TSInfo); 56900b57cec5SDimitry Andric if (!TSInfo) 56910b57cec5SDimitry Andric TSInfo = Context.getTrivialTypeSourceInfo(T); 56920b57cec5SDimitry Andric 56930b57cec5SDimitry Andric return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 56940b57cec5SDimitry Andric } 56950b57cec5SDimitry Andric 56960b57cec5SDimitry Andric static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 56970b57cec5SDimitry Andric QualType T, Expr *DimExpr, 56980b57cec5SDimitry Andric SourceLocation KeyLoc) { 56990b57cec5SDimitry Andric assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 57000b57cec5SDimitry Andric 57010b57cec5SDimitry Andric switch(ATT) { 57020b57cec5SDimitry Andric case ATT_ArrayRank: 57030b57cec5SDimitry Andric if (T->isArrayType()) { 57040b57cec5SDimitry Andric unsigned Dim = 0; 57050b57cec5SDimitry Andric while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 57060b57cec5SDimitry Andric ++Dim; 57070b57cec5SDimitry Andric T = AT->getElementType(); 57080b57cec5SDimitry Andric } 57090b57cec5SDimitry Andric return Dim; 57100b57cec5SDimitry Andric } 57110b57cec5SDimitry Andric return 0; 57120b57cec5SDimitry Andric 57130b57cec5SDimitry Andric case ATT_ArrayExtent: { 57140b57cec5SDimitry Andric llvm::APSInt Value; 57150b57cec5SDimitry Andric uint64_t Dim; 5716e8d8bef9SDimitry Andric if (Self.VerifyIntegerConstantExpression( 5717e8d8bef9SDimitry Andric DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) 5718e8d8bef9SDimitry Andric .isInvalid()) 57190b57cec5SDimitry Andric return 0; 57200b57cec5SDimitry Andric if (Value.isSigned() && Value.isNegative()) { 57210b57cec5SDimitry Andric Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 57220b57cec5SDimitry Andric << DimExpr->getSourceRange(); 57230b57cec5SDimitry Andric return 0; 57240b57cec5SDimitry Andric } 57250b57cec5SDimitry Andric Dim = Value.getLimitedValue(); 57260b57cec5SDimitry Andric 57270b57cec5SDimitry Andric if (T->isArrayType()) { 57280b57cec5SDimitry Andric unsigned D = 0; 57290b57cec5SDimitry Andric bool Matched = false; 57300b57cec5SDimitry Andric while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 57310b57cec5SDimitry Andric if (Dim == D) { 57320b57cec5SDimitry Andric Matched = true; 57330b57cec5SDimitry Andric break; 57340b57cec5SDimitry Andric } 57350b57cec5SDimitry Andric ++D; 57360b57cec5SDimitry Andric T = AT->getElementType(); 57370b57cec5SDimitry Andric } 57380b57cec5SDimitry Andric 57390b57cec5SDimitry Andric if (Matched && T->isArrayType()) { 57400b57cec5SDimitry Andric if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 57410b57cec5SDimitry Andric return CAT->getSize().getLimitedValue(); 57420b57cec5SDimitry Andric } 57430b57cec5SDimitry Andric } 57440b57cec5SDimitry Andric return 0; 57450b57cec5SDimitry Andric } 57460b57cec5SDimitry Andric } 57470b57cec5SDimitry Andric llvm_unreachable("Unknown type trait or not implemented"); 57480b57cec5SDimitry Andric } 57490b57cec5SDimitry Andric 57500b57cec5SDimitry Andric ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 57510b57cec5SDimitry Andric SourceLocation KWLoc, 57520b57cec5SDimitry Andric TypeSourceInfo *TSInfo, 57530b57cec5SDimitry Andric Expr* DimExpr, 57540b57cec5SDimitry Andric SourceLocation RParen) { 57550b57cec5SDimitry Andric QualType T = TSInfo->getType(); 57560b57cec5SDimitry Andric 57570b57cec5SDimitry Andric // FIXME: This should likely be tracked as an APInt to remove any host 57580b57cec5SDimitry Andric // assumptions about the width of size_t on the target. 57590b57cec5SDimitry Andric uint64_t Value = 0; 57600b57cec5SDimitry Andric if (!T->isDependentType()) 57610b57cec5SDimitry Andric Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 57620b57cec5SDimitry Andric 57630b57cec5SDimitry Andric // While the specification for these traits from the Embarcadero C++ 57640b57cec5SDimitry Andric // compiler's documentation says the return type is 'unsigned int', Clang 57650b57cec5SDimitry Andric // returns 'size_t'. On Windows, the primary platform for the Embarcadero 57660b57cec5SDimitry Andric // compiler, there is no difference. On several other platforms this is an 57670b57cec5SDimitry Andric // important distinction. 57680b57cec5SDimitry Andric return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 57690b57cec5SDimitry Andric RParen, Context.getSizeType()); 57700b57cec5SDimitry Andric } 57710b57cec5SDimitry Andric 57720b57cec5SDimitry Andric ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 57730b57cec5SDimitry Andric SourceLocation KWLoc, 57740b57cec5SDimitry Andric Expr *Queried, 57750b57cec5SDimitry Andric SourceLocation RParen) { 57760b57cec5SDimitry Andric // If error parsing the expression, ignore. 57770b57cec5SDimitry Andric if (!Queried) 57780b57cec5SDimitry Andric return ExprError(); 57790b57cec5SDimitry Andric 57800b57cec5SDimitry Andric ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 57810b57cec5SDimitry Andric 57820b57cec5SDimitry Andric return Result; 57830b57cec5SDimitry Andric } 57840b57cec5SDimitry Andric 57850b57cec5SDimitry Andric static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 57860b57cec5SDimitry Andric switch (ET) { 57870b57cec5SDimitry Andric case ET_IsLValueExpr: return E->isLValue(); 5788fe6060f1SDimitry Andric case ET_IsRValueExpr: 5789fe6060f1SDimitry Andric return E->isPRValue(); 57900b57cec5SDimitry Andric } 57910b57cec5SDimitry Andric llvm_unreachable("Expression trait not covered by switch"); 57920b57cec5SDimitry Andric } 57930b57cec5SDimitry Andric 57940b57cec5SDimitry Andric ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 57950b57cec5SDimitry Andric SourceLocation KWLoc, 57960b57cec5SDimitry Andric Expr *Queried, 57970b57cec5SDimitry Andric SourceLocation RParen) { 57980b57cec5SDimitry Andric if (Queried->isTypeDependent()) { 57990b57cec5SDimitry Andric // Delay type-checking for type-dependent expressions. 58001fd87a68SDimitry Andric } else if (Queried->hasPlaceholderType()) { 58010b57cec5SDimitry Andric ExprResult PE = CheckPlaceholderExpr(Queried); 58020b57cec5SDimitry Andric if (PE.isInvalid()) return ExprError(); 58030b57cec5SDimitry Andric return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 58040b57cec5SDimitry Andric } 58050b57cec5SDimitry Andric 58060b57cec5SDimitry Andric bool Value = EvaluateExpressionTrait(ET, Queried); 58070b57cec5SDimitry Andric 58080b57cec5SDimitry Andric return new (Context) 58090b57cec5SDimitry Andric ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 58100b57cec5SDimitry Andric } 58110b57cec5SDimitry Andric 58120b57cec5SDimitry Andric QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 58130b57cec5SDimitry Andric ExprValueKind &VK, 58140b57cec5SDimitry Andric SourceLocation Loc, 58150b57cec5SDimitry Andric bool isIndirect) { 58161fd87a68SDimitry Andric assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && 58170b57cec5SDimitry Andric "placeholders should have been weeded out by now"); 58180b57cec5SDimitry Andric 58190b57cec5SDimitry Andric // The LHS undergoes lvalue conversions if this is ->*, and undergoes the 58200b57cec5SDimitry Andric // temporary materialization conversion otherwise. 58210b57cec5SDimitry Andric if (isIndirect) 58220b57cec5SDimitry Andric LHS = DefaultLvalueConversion(LHS.get()); 5823fe6060f1SDimitry Andric else if (LHS.get()->isPRValue()) 58240b57cec5SDimitry Andric LHS = TemporaryMaterializationConversion(LHS.get()); 58250b57cec5SDimitry Andric if (LHS.isInvalid()) 58260b57cec5SDimitry Andric return QualType(); 58270b57cec5SDimitry Andric 58280b57cec5SDimitry Andric // The RHS always undergoes lvalue conversions. 58290b57cec5SDimitry Andric RHS = DefaultLvalueConversion(RHS.get()); 58300b57cec5SDimitry Andric if (RHS.isInvalid()) return QualType(); 58310b57cec5SDimitry Andric 58320b57cec5SDimitry Andric const char *OpSpelling = isIndirect ? "->*" : ".*"; 58330b57cec5SDimitry Andric // C++ 5.5p2 58340b57cec5SDimitry Andric // The binary operator .* [p3: ->*] binds its second operand, which shall 58350b57cec5SDimitry Andric // be of type "pointer to member of T" (where T is a completely-defined 58360b57cec5SDimitry Andric // class type) [...] 58370b57cec5SDimitry Andric QualType RHSType = RHS.get()->getType(); 58380b57cec5SDimitry Andric const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 58390b57cec5SDimitry Andric if (!MemPtr) { 58400b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_rhs) 58410b57cec5SDimitry Andric << OpSpelling << RHSType << RHS.get()->getSourceRange(); 58420b57cec5SDimitry Andric return QualType(); 58430b57cec5SDimitry Andric } 58440b57cec5SDimitry Andric 58450b57cec5SDimitry Andric QualType Class(MemPtr->getClass(), 0); 58460b57cec5SDimitry Andric 58470b57cec5SDimitry Andric // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 58480b57cec5SDimitry Andric // member pointer points must be completely-defined. However, there is no 58490b57cec5SDimitry Andric // reason for this semantic distinction, and the rule is not enforced by 58500b57cec5SDimitry Andric // other compilers. Therefore, we do not check this property, as it is 58510b57cec5SDimitry Andric // likely to be considered a defect. 58520b57cec5SDimitry Andric 58530b57cec5SDimitry Andric // C++ 5.5p2 58540b57cec5SDimitry Andric // [...] to its first operand, which shall be of class T or of a class of 58550b57cec5SDimitry Andric // which T is an unambiguous and accessible base class. [p3: a pointer to 58560b57cec5SDimitry Andric // such a class] 58570b57cec5SDimitry Andric QualType LHSType = LHS.get()->getType(); 58580b57cec5SDimitry Andric if (isIndirect) { 58590b57cec5SDimitry Andric if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 58600b57cec5SDimitry Andric LHSType = Ptr->getPointeeType(); 58610b57cec5SDimitry Andric else { 58620b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_lhs) 58630b57cec5SDimitry Andric << OpSpelling << 1 << LHSType 58640b57cec5SDimitry Andric << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 58650b57cec5SDimitry Andric return QualType(); 58660b57cec5SDimitry Andric } 58670b57cec5SDimitry Andric } 58680b57cec5SDimitry Andric 58690b57cec5SDimitry Andric if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 58700b57cec5SDimitry Andric // If we want to check the hierarchy, we need a complete type. 58710b57cec5SDimitry Andric if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 58720b57cec5SDimitry Andric OpSpelling, (int)isIndirect)) { 58730b57cec5SDimitry Andric return QualType(); 58740b57cec5SDimitry Andric } 58750b57cec5SDimitry Andric 58760b57cec5SDimitry Andric if (!IsDerivedFrom(Loc, LHSType, Class)) { 58770b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 58780b57cec5SDimitry Andric << (int)isIndirect << LHS.get()->getType(); 58790b57cec5SDimitry Andric return QualType(); 58800b57cec5SDimitry Andric } 58810b57cec5SDimitry Andric 58820b57cec5SDimitry Andric CXXCastPath BasePath; 58830b57cec5SDimitry Andric if (CheckDerivedToBaseConversion( 58840b57cec5SDimitry Andric LHSType, Class, Loc, 58850b57cec5SDimitry Andric SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), 58860b57cec5SDimitry Andric &BasePath)) 58870b57cec5SDimitry Andric return QualType(); 58880b57cec5SDimitry Andric 58890b57cec5SDimitry Andric // Cast LHS to type of use. 58900b57cec5SDimitry Andric QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); 58910b57cec5SDimitry Andric if (isIndirect) 58920b57cec5SDimitry Andric UseType = Context.getPointerType(UseType); 5893fe6060f1SDimitry Andric ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind(); 58940b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 58950b57cec5SDimitry Andric &BasePath); 58960b57cec5SDimitry Andric } 58970b57cec5SDimitry Andric 58980b57cec5SDimitry Andric if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 58990b57cec5SDimitry Andric // Diagnose use of pointer-to-member type which when used as 59000b57cec5SDimitry Andric // the functional cast in a pointer-to-member expression. 59010b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 59020b57cec5SDimitry Andric return QualType(); 59030b57cec5SDimitry Andric } 59040b57cec5SDimitry Andric 59050b57cec5SDimitry Andric // C++ 5.5p2 59060b57cec5SDimitry Andric // The result is an object or a function of the type specified by the 59070b57cec5SDimitry Andric // second operand. 59080b57cec5SDimitry Andric // The cv qualifiers are the union of those in the pointer and the left side, 59090b57cec5SDimitry Andric // in accordance with 5.5p5 and 5.2.5. 59100b57cec5SDimitry Andric QualType Result = MemPtr->getPointeeType(); 59110b57cec5SDimitry Andric Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 59120b57cec5SDimitry Andric 59130b57cec5SDimitry Andric // C++0x [expr.mptr.oper]p6: 59140b57cec5SDimitry Andric // In a .* expression whose object expression is an rvalue, the program is 59150b57cec5SDimitry Andric // ill-formed if the second operand is a pointer to member function with 59160b57cec5SDimitry Andric // ref-qualifier &. In a ->* expression or in a .* expression whose object 59170b57cec5SDimitry Andric // expression is an lvalue, the program is ill-formed if the second operand 59180b57cec5SDimitry Andric // is a pointer to member function with ref-qualifier &&. 59190b57cec5SDimitry Andric if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 59200b57cec5SDimitry Andric switch (Proto->getRefQualifier()) { 59210b57cec5SDimitry Andric case RQ_None: 59220b57cec5SDimitry Andric // Do nothing 59230b57cec5SDimitry Andric break; 59240b57cec5SDimitry Andric 59250b57cec5SDimitry Andric case RQ_LValue: 59260b57cec5SDimitry Andric if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { 59270b57cec5SDimitry Andric // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq 59280b57cec5SDimitry Andric // is (exactly) 'const'. 59290b57cec5SDimitry Andric if (Proto->isConst() && !Proto->isVolatile()) 59305ffd83dbSDimitry Andric Diag(Loc, getLangOpts().CPlusPlus20 59310b57cec5SDimitry Andric ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue 59320b57cec5SDimitry Andric : diag::ext_pointer_to_const_ref_member_on_rvalue); 59330b57cec5SDimitry Andric else 59340b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 59350b57cec5SDimitry Andric << RHSType << 1 << LHS.get()->getSourceRange(); 59360b57cec5SDimitry Andric } 59370b57cec5SDimitry Andric break; 59380b57cec5SDimitry Andric 59390b57cec5SDimitry Andric case RQ_RValue: 59400b57cec5SDimitry Andric if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 59410b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 59420b57cec5SDimitry Andric << RHSType << 0 << LHS.get()->getSourceRange(); 59430b57cec5SDimitry Andric break; 59440b57cec5SDimitry Andric } 59450b57cec5SDimitry Andric } 59460b57cec5SDimitry Andric 59470b57cec5SDimitry Andric // C++ [expr.mptr.oper]p6: 59480b57cec5SDimitry Andric // The result of a .* expression whose second operand is a pointer 59490b57cec5SDimitry Andric // to a data member is of the same value category as its 59500b57cec5SDimitry Andric // first operand. The result of a .* expression whose second 59510b57cec5SDimitry Andric // operand is a pointer to a member function is a prvalue. The 59520b57cec5SDimitry Andric // result of an ->* expression is an lvalue if its second operand 59530b57cec5SDimitry Andric // is a pointer to data member and a prvalue otherwise. 59540b57cec5SDimitry Andric if (Result->isFunctionType()) { 5955fe6060f1SDimitry Andric VK = VK_PRValue; 59560b57cec5SDimitry Andric return Context.BoundMemberTy; 59570b57cec5SDimitry Andric } else if (isIndirect) { 59580b57cec5SDimitry Andric VK = VK_LValue; 59590b57cec5SDimitry Andric } else { 59600b57cec5SDimitry Andric VK = LHS.get()->getValueKind(); 59610b57cec5SDimitry Andric } 59620b57cec5SDimitry Andric 59630b57cec5SDimitry Andric return Result; 59640b57cec5SDimitry Andric } 59650b57cec5SDimitry Andric 59660b57cec5SDimitry Andric /// Try to convert a type to another according to C++11 5.16p3. 59670b57cec5SDimitry Andric /// 59680b57cec5SDimitry Andric /// This is part of the parameter validation for the ? operator. If either 59690b57cec5SDimitry Andric /// value operand is a class type, the two operands are attempted to be 59700b57cec5SDimitry Andric /// converted to each other. This function does the conversion in one direction. 59710b57cec5SDimitry Andric /// It returns true if the program is ill-formed and has already been diagnosed 59720b57cec5SDimitry Andric /// as such. 59730b57cec5SDimitry Andric static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 59740b57cec5SDimitry Andric SourceLocation QuestionLoc, 59750b57cec5SDimitry Andric bool &HaveConversion, 59760b57cec5SDimitry Andric QualType &ToType) { 59770b57cec5SDimitry Andric HaveConversion = false; 59780b57cec5SDimitry Andric ToType = To->getType(); 59790b57cec5SDimitry Andric 59800b57cec5SDimitry Andric InitializationKind Kind = 59810b57cec5SDimitry Andric InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); 59820b57cec5SDimitry Andric // C++11 5.16p3 59830b57cec5SDimitry Andric // The process for determining whether an operand expression E1 of type T1 59840b57cec5SDimitry Andric // can be converted to match an operand expression E2 of type T2 is defined 59850b57cec5SDimitry Andric // as follows: 59860b57cec5SDimitry Andric // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be 59870b57cec5SDimitry Andric // implicitly converted to type "lvalue reference to T2", subject to the 59880b57cec5SDimitry Andric // constraint that in the conversion the reference must bind directly to 59890b57cec5SDimitry Andric // an lvalue. 59900b57cec5SDimitry Andric // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be 59910b57cec5SDimitry Andric // implicitly converted to the type "rvalue reference to R2", subject to 59920b57cec5SDimitry Andric // the constraint that the reference must bind directly. 5993349cc55cSDimitry Andric if (To->isGLValue()) { 5994349cc55cSDimitry Andric QualType T = Self.Context.getReferenceQualifiedType(To); 59950b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 59960b57cec5SDimitry Andric 59970b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 59980b57cec5SDimitry Andric if (InitSeq.isDirectReferenceBinding()) { 59990b57cec5SDimitry Andric ToType = T; 60000b57cec5SDimitry Andric HaveConversion = true; 60010b57cec5SDimitry Andric return false; 60020b57cec5SDimitry Andric } 60030b57cec5SDimitry Andric 60040b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 60050b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 60060b57cec5SDimitry Andric } 60070b57cec5SDimitry Andric 60080b57cec5SDimitry Andric // -- If E2 is an rvalue, or if the conversion above cannot be done: 60090b57cec5SDimitry Andric // -- if E1 and E2 have class type, and the underlying class types are 60100b57cec5SDimitry Andric // the same or one is a base class of the other: 60110b57cec5SDimitry Andric QualType FTy = From->getType(); 60120b57cec5SDimitry Andric QualType TTy = To->getType(); 60130b57cec5SDimitry Andric const RecordType *FRec = FTy->getAs<RecordType>(); 60140b57cec5SDimitry Andric const RecordType *TRec = TTy->getAs<RecordType>(); 60150b57cec5SDimitry Andric bool FDerivedFromT = FRec && TRec && FRec != TRec && 60160b57cec5SDimitry Andric Self.IsDerivedFrom(QuestionLoc, FTy, TTy); 60170b57cec5SDimitry Andric if (FRec && TRec && (FRec == TRec || FDerivedFromT || 60180b57cec5SDimitry Andric Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { 60190b57cec5SDimitry Andric // E1 can be converted to match E2 if the class of T2 is the 60200b57cec5SDimitry Andric // same type as, or a base class of, the class of T1, and 60210b57cec5SDimitry Andric // [cv2 > cv1]. 60220b57cec5SDimitry Andric if (FRec == TRec || FDerivedFromT) { 60230b57cec5SDimitry Andric if (TTy.isAtLeastAsQualifiedAs(FTy)) { 60240b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 60250b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 60260b57cec5SDimitry Andric if (InitSeq) { 60270b57cec5SDimitry Andric HaveConversion = true; 60280b57cec5SDimitry Andric return false; 60290b57cec5SDimitry Andric } 60300b57cec5SDimitry Andric 60310b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 60320b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 60330b57cec5SDimitry Andric } 60340b57cec5SDimitry Andric } 60350b57cec5SDimitry Andric 60360b57cec5SDimitry Andric return false; 60370b57cec5SDimitry Andric } 60380b57cec5SDimitry Andric 60390b57cec5SDimitry Andric // -- Otherwise: E1 can be converted to match E2 if E1 can be 60400b57cec5SDimitry Andric // implicitly converted to the type that expression E2 would have 60410b57cec5SDimitry Andric // if E2 were converted to an rvalue (or the type it has, if E2 is 60420b57cec5SDimitry Andric // an rvalue). 60430b57cec5SDimitry Andric // 60440b57cec5SDimitry Andric // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 60450b57cec5SDimitry Andric // to the array-to-pointer or function-to-pointer conversions. 60460b57cec5SDimitry Andric TTy = TTy.getNonLValueExprType(Self.Context); 60470b57cec5SDimitry Andric 60480b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 60490b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 60500b57cec5SDimitry Andric HaveConversion = !InitSeq.Failed(); 60510b57cec5SDimitry Andric ToType = TTy; 60520b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 60530b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 60540b57cec5SDimitry Andric 60550b57cec5SDimitry Andric return false; 60560b57cec5SDimitry Andric } 60570b57cec5SDimitry Andric 60580b57cec5SDimitry Andric /// Try to find a common type for two according to C++0x 5.16p5. 60590b57cec5SDimitry Andric /// 60600b57cec5SDimitry Andric /// This is part of the parameter validation for the ? operator. If either 60610b57cec5SDimitry Andric /// value operand is a class type, overload resolution is used to find a 60620b57cec5SDimitry Andric /// conversion to a common type. 60630b57cec5SDimitry Andric static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 60640b57cec5SDimitry Andric SourceLocation QuestionLoc) { 60650b57cec5SDimitry Andric Expr *Args[2] = { LHS.get(), RHS.get() }; 60660b57cec5SDimitry Andric OverloadCandidateSet CandidateSet(QuestionLoc, 60670b57cec5SDimitry Andric OverloadCandidateSet::CSK_Operator); 60680b57cec5SDimitry Andric Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 60690b57cec5SDimitry Andric CandidateSet); 60700b57cec5SDimitry Andric 60710b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 60720b57cec5SDimitry Andric switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 60730b57cec5SDimitry Andric case OR_Success: { 60740b57cec5SDimitry Andric // We found a match. Perform the conversions on the arguments and move on. 60750b57cec5SDimitry Andric ExprResult LHSRes = Self.PerformImplicitConversion( 60760b57cec5SDimitry Andric LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], 60770b57cec5SDimitry Andric Sema::AA_Converting); 60780b57cec5SDimitry Andric if (LHSRes.isInvalid()) 60790b57cec5SDimitry Andric break; 60800b57cec5SDimitry Andric LHS = LHSRes; 60810b57cec5SDimitry Andric 60820b57cec5SDimitry Andric ExprResult RHSRes = Self.PerformImplicitConversion( 60830b57cec5SDimitry Andric RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], 60840b57cec5SDimitry Andric Sema::AA_Converting); 60850b57cec5SDimitry Andric if (RHSRes.isInvalid()) 60860b57cec5SDimitry Andric break; 60870b57cec5SDimitry Andric RHS = RHSRes; 60880b57cec5SDimitry Andric if (Best->Function) 60890b57cec5SDimitry Andric Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 60900b57cec5SDimitry Andric return false; 60910b57cec5SDimitry Andric } 60920b57cec5SDimitry Andric 60930b57cec5SDimitry Andric case OR_No_Viable_Function: 60940b57cec5SDimitry Andric 60950b57cec5SDimitry Andric // Emit a better diagnostic if one of the expressions is a null pointer 60960b57cec5SDimitry Andric // constant and the other is a pointer type. In this case, the user most 60970b57cec5SDimitry Andric // likely forgot to take the address of the other expression. 60980b57cec5SDimitry Andric if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 60990b57cec5SDimitry Andric return true; 61000b57cec5SDimitry Andric 61010b57cec5SDimitry Andric Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 61020b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 61030b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 61040b57cec5SDimitry Andric return true; 61050b57cec5SDimitry Andric 61060b57cec5SDimitry Andric case OR_Ambiguous: 61070b57cec5SDimitry Andric Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 61080b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 61090b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 61100b57cec5SDimitry Andric // FIXME: Print the possible common types by printing the return types of 61110b57cec5SDimitry Andric // the viable candidates. 61120b57cec5SDimitry Andric break; 61130b57cec5SDimitry Andric 61140b57cec5SDimitry Andric case OR_Deleted: 61150b57cec5SDimitry Andric llvm_unreachable("Conditional operator has only built-in overloads"); 61160b57cec5SDimitry Andric } 61170b57cec5SDimitry Andric return true; 61180b57cec5SDimitry Andric } 61190b57cec5SDimitry Andric 61200b57cec5SDimitry Andric /// Perform an "extended" implicit conversion as returned by 61210b57cec5SDimitry Andric /// TryClassUnification. 61220b57cec5SDimitry Andric static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 61230b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 61240b57cec5SDimitry Andric InitializationKind Kind = 61250b57cec5SDimitry Andric InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); 61260b57cec5SDimitry Andric Expr *Arg = E.get(); 61270b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, Arg); 61280b57cec5SDimitry Andric ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 61290b57cec5SDimitry Andric if (Result.isInvalid()) 61300b57cec5SDimitry Andric return true; 61310b57cec5SDimitry Andric 61320b57cec5SDimitry Andric E = Result; 61330b57cec5SDimitry Andric return false; 61340b57cec5SDimitry Andric } 61350b57cec5SDimitry Andric 6136480093f4SDimitry Andric // Check the condition operand of ?: to see if it is valid for the GCC 6137480093f4SDimitry Andric // extension. 6138480093f4SDimitry Andric static bool isValidVectorForConditionalCondition(ASTContext &Ctx, 6139480093f4SDimitry Andric QualType CondTy) { 6140fe6060f1SDimitry Andric if (!CondTy->isVectorType() && !CondTy->isExtVectorType()) 6141480093f4SDimitry Andric return false; 6142480093f4SDimitry Andric const QualType EltTy = 6143480093f4SDimitry Andric cast<VectorType>(CondTy.getCanonicalType())->getElementType(); 614481ad6265SDimitry Andric assert(!EltTy->isEnumeralType() && "Vectors cant be enum types"); 614581ad6265SDimitry Andric return EltTy->isIntegralType(Ctx); 614681ad6265SDimitry Andric } 614781ad6265SDimitry Andric 614881ad6265SDimitry Andric static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx, 614981ad6265SDimitry Andric QualType CondTy) { 615081ad6265SDimitry Andric if (!CondTy->isVLSTBuiltinType()) 615181ad6265SDimitry Andric return false; 615281ad6265SDimitry Andric const QualType EltTy = 615381ad6265SDimitry Andric cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx); 615481ad6265SDimitry Andric assert(!EltTy->isEnumeralType() && "Vectors cant be enum types"); 6155480093f4SDimitry Andric return EltTy->isIntegralType(Ctx); 6156480093f4SDimitry Andric } 6157480093f4SDimitry Andric 6158fe6060f1SDimitry Andric QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 6159480093f4SDimitry Andric ExprResult &RHS, 6160480093f4SDimitry Andric SourceLocation QuestionLoc) { 6161480093f4SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 6162480093f4SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 6163480093f4SDimitry Andric 6164480093f4SDimitry Andric QualType CondType = Cond.get()->getType(); 61655ffd83dbSDimitry Andric const auto *CondVT = CondType->castAs<VectorType>(); 6166480093f4SDimitry Andric QualType CondElementTy = CondVT->getElementType(); 6167480093f4SDimitry Andric unsigned CondElementCount = CondVT->getNumElements(); 6168480093f4SDimitry Andric QualType LHSType = LHS.get()->getType(); 6169480093f4SDimitry Andric const auto *LHSVT = LHSType->getAs<VectorType>(); 6170480093f4SDimitry Andric QualType RHSType = RHS.get()->getType(); 6171480093f4SDimitry Andric const auto *RHSVT = RHSType->getAs<VectorType>(); 6172480093f4SDimitry Andric 6173480093f4SDimitry Andric QualType ResultType; 6174480093f4SDimitry Andric 6175480093f4SDimitry Andric 6176480093f4SDimitry Andric if (LHSVT && RHSVT) { 6177fe6060f1SDimitry Andric if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) { 6178fe6060f1SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) 6179fe6060f1SDimitry Andric << /*isExtVector*/ isa<ExtVectorType>(CondVT); 6180fe6060f1SDimitry Andric return {}; 6181fe6060f1SDimitry Andric } 6182fe6060f1SDimitry Andric 6183480093f4SDimitry Andric // If both are vector types, they must be the same type. 6184480093f4SDimitry Andric if (!Context.hasSameType(LHSType, RHSType)) { 6185fe6060f1SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_mismatched) 6186480093f4SDimitry Andric << LHSType << RHSType; 6187480093f4SDimitry Andric return {}; 6188480093f4SDimitry Andric } 6189480093f4SDimitry Andric ResultType = LHSType; 6190480093f4SDimitry Andric } else if (LHSVT || RHSVT) { 6191480093f4SDimitry Andric ResultType = CheckVectorOperands( 6192480093f4SDimitry Andric LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true, 619381ad6265SDimitry Andric /*AllowBoolConversions*/ false, 619481ad6265SDimitry Andric /*AllowBoolOperation*/ true, 619581ad6265SDimitry Andric /*ReportInvalid*/ true); 6196480093f4SDimitry Andric if (ResultType.isNull()) 6197480093f4SDimitry Andric return {}; 6198480093f4SDimitry Andric } else { 6199480093f4SDimitry Andric // Both are scalar. 6200480093f4SDimitry Andric QualType ResultElementTy; 6201480093f4SDimitry Andric LHSType = LHSType.getCanonicalType().getUnqualifiedType(); 6202480093f4SDimitry Andric RHSType = RHSType.getCanonicalType().getUnqualifiedType(); 6203480093f4SDimitry Andric 6204480093f4SDimitry Andric if (Context.hasSameType(LHSType, RHSType)) 6205480093f4SDimitry Andric ResultElementTy = LHSType; 6206480093f4SDimitry Andric else 6207480093f4SDimitry Andric ResultElementTy = 6208480093f4SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 6209480093f4SDimitry Andric 6210480093f4SDimitry Andric if (ResultElementTy->isEnumeralType()) { 6211480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 6212fe6060f1SDimitry Andric << ResultElementTy; 6213480093f4SDimitry Andric return {}; 6214480093f4SDimitry Andric } 6215fe6060f1SDimitry Andric if (CondType->isExtVectorType()) 6216fe6060f1SDimitry Andric ResultType = 6217fe6060f1SDimitry Andric Context.getExtVectorType(ResultElementTy, CondVT->getNumElements()); 6218fe6060f1SDimitry Andric else 6219480093f4SDimitry Andric ResultType = Context.getVectorType( 6220fe6060f1SDimitry Andric ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector); 6221480093f4SDimitry Andric 6222480093f4SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); 6223480093f4SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); 6224480093f4SDimitry Andric } 6225480093f4SDimitry Andric 6226480093f4SDimitry Andric assert(!ResultType.isNull() && ResultType->isVectorType() && 6227fe6060f1SDimitry Andric (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && 6228480093f4SDimitry Andric "Result should have been a vector type"); 62295ffd83dbSDimitry Andric auto *ResultVectorTy = ResultType->castAs<VectorType>(); 62305ffd83dbSDimitry Andric QualType ResultElementTy = ResultVectorTy->getElementType(); 62315ffd83dbSDimitry Andric unsigned ResultElementCount = ResultVectorTy->getNumElements(); 6232480093f4SDimitry Andric 6233480093f4SDimitry Andric if (ResultElementCount != CondElementCount) { 6234480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType 6235480093f4SDimitry Andric << ResultType; 6236480093f4SDimitry Andric return {}; 6237480093f4SDimitry Andric } 6238480093f4SDimitry Andric 6239480093f4SDimitry Andric if (Context.getTypeSize(ResultElementTy) != 6240480093f4SDimitry Andric Context.getTypeSize(CondElementTy)) { 6241480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType 6242480093f4SDimitry Andric << ResultType; 6243480093f4SDimitry Andric return {}; 6244480093f4SDimitry Andric } 6245480093f4SDimitry Andric 6246480093f4SDimitry Andric return ResultType; 6247480093f4SDimitry Andric } 6248480093f4SDimitry Andric 624981ad6265SDimitry Andric QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond, 625081ad6265SDimitry Andric ExprResult &LHS, 625181ad6265SDimitry Andric ExprResult &RHS, 625281ad6265SDimitry Andric SourceLocation QuestionLoc) { 625381ad6265SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 625481ad6265SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 625581ad6265SDimitry Andric 625681ad6265SDimitry Andric QualType CondType = Cond.get()->getType(); 625781ad6265SDimitry Andric const auto *CondBT = CondType->castAs<BuiltinType>(); 625881ad6265SDimitry Andric QualType CondElementTy = CondBT->getSveEltType(Context); 625981ad6265SDimitry Andric llvm::ElementCount CondElementCount = 626081ad6265SDimitry Andric Context.getBuiltinVectorTypeInfo(CondBT).EC; 626181ad6265SDimitry Andric 626281ad6265SDimitry Andric QualType LHSType = LHS.get()->getType(); 626381ad6265SDimitry Andric const auto *LHSBT = 626481ad6265SDimitry Andric LHSType->isVLSTBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr; 626581ad6265SDimitry Andric QualType RHSType = RHS.get()->getType(); 626681ad6265SDimitry Andric const auto *RHSBT = 626781ad6265SDimitry Andric RHSType->isVLSTBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr; 626881ad6265SDimitry Andric 626981ad6265SDimitry Andric QualType ResultType; 627081ad6265SDimitry Andric 627181ad6265SDimitry Andric if (LHSBT && RHSBT) { 627281ad6265SDimitry Andric // If both are sizeless vector types, they must be the same type. 627381ad6265SDimitry Andric if (!Context.hasSameType(LHSType, RHSType)) { 627481ad6265SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_mismatched) 627581ad6265SDimitry Andric << LHSType << RHSType; 627681ad6265SDimitry Andric return QualType(); 627781ad6265SDimitry Andric } 627881ad6265SDimitry Andric ResultType = LHSType; 627981ad6265SDimitry Andric } else if (LHSBT || RHSBT) { 628081ad6265SDimitry Andric ResultType = CheckSizelessVectorOperands( 628181ad6265SDimitry Andric LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional); 628281ad6265SDimitry Andric if (ResultType.isNull()) 628381ad6265SDimitry Andric return QualType(); 628481ad6265SDimitry Andric } else { 628581ad6265SDimitry Andric // Both are scalar so splat 628681ad6265SDimitry Andric QualType ResultElementTy; 628781ad6265SDimitry Andric LHSType = LHSType.getCanonicalType().getUnqualifiedType(); 628881ad6265SDimitry Andric RHSType = RHSType.getCanonicalType().getUnqualifiedType(); 628981ad6265SDimitry Andric 629081ad6265SDimitry Andric if (Context.hasSameType(LHSType, RHSType)) 629181ad6265SDimitry Andric ResultElementTy = LHSType; 629281ad6265SDimitry Andric else 629381ad6265SDimitry Andric ResultElementTy = 629481ad6265SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 629581ad6265SDimitry Andric 629681ad6265SDimitry Andric if (ResultElementTy->isEnumeralType()) { 629781ad6265SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 629881ad6265SDimitry Andric << ResultElementTy; 629981ad6265SDimitry Andric return QualType(); 630081ad6265SDimitry Andric } 630181ad6265SDimitry Andric 630281ad6265SDimitry Andric ResultType = Context.getScalableVectorType( 630381ad6265SDimitry Andric ResultElementTy, CondElementCount.getKnownMinValue()); 630481ad6265SDimitry Andric 630581ad6265SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); 630681ad6265SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); 630781ad6265SDimitry Andric } 630881ad6265SDimitry Andric 630981ad6265SDimitry Andric assert(!ResultType.isNull() && ResultType->isVLSTBuiltinType() && 631081ad6265SDimitry Andric "Result should have been a vector type"); 631181ad6265SDimitry Andric auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>(); 631281ad6265SDimitry Andric QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context); 631381ad6265SDimitry Andric llvm::ElementCount ResultElementCount = 631481ad6265SDimitry Andric Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC; 631581ad6265SDimitry Andric 631681ad6265SDimitry Andric if (ResultElementCount != CondElementCount) { 631781ad6265SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_size) 631881ad6265SDimitry Andric << CondType << ResultType; 631981ad6265SDimitry Andric return QualType(); 632081ad6265SDimitry Andric } 632181ad6265SDimitry Andric 632281ad6265SDimitry Andric if (Context.getTypeSize(ResultElementTy) != 632381ad6265SDimitry Andric Context.getTypeSize(CondElementTy)) { 632481ad6265SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_element_size) 632581ad6265SDimitry Andric << CondType << ResultType; 632681ad6265SDimitry Andric return QualType(); 632781ad6265SDimitry Andric } 632881ad6265SDimitry Andric 632981ad6265SDimitry Andric return ResultType; 633081ad6265SDimitry Andric } 633181ad6265SDimitry Andric 63320b57cec5SDimitry Andric /// Check the operands of ?: under C++ semantics. 63330b57cec5SDimitry Andric /// 63340b57cec5SDimitry Andric /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 63350b57cec5SDimitry Andric /// extension. In this case, LHS == Cond. (But they're not aliases.) 6336480093f4SDimitry Andric /// 6337fe6060f1SDimitry Andric /// This function also implements GCC's vector extension and the 6338fe6060f1SDimitry Andric /// OpenCL/ext_vector_type extension for conditionals. The vector extensions 6339fe6060f1SDimitry Andric /// permit the use of a?b:c where the type of a is that of a integer vector with 6340fe6060f1SDimitry Andric /// the same number of elements and size as the vectors of b and c. If one of 6341fe6060f1SDimitry Andric /// either b or c is a scalar it is implicitly converted to match the type of 6342fe6060f1SDimitry Andric /// the vector. Otherwise the expression is ill-formed. If both b and c are 6343fe6060f1SDimitry Andric /// scalars, then b and c are checked and converted to the type of a if 6344fe6060f1SDimitry Andric /// possible. 6345fe6060f1SDimitry Andric /// 6346fe6060f1SDimitry Andric /// The expressions are evaluated differently for GCC's and OpenCL's extensions. 6347fe6060f1SDimitry Andric /// For the GCC extension, the ?: operator is evaluated as 6348480093f4SDimitry Andric /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). 6349fe6060f1SDimitry Andric /// For the OpenCL extensions, the ?: operator is evaluated as 6350fe6060f1SDimitry Andric /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. , 6351fe6060f1SDimitry Andric /// most-significant-bit-set(a[n]) ? b[n] : c[n]). 63520b57cec5SDimitry Andric QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 63530b57cec5SDimitry Andric ExprResult &RHS, ExprValueKind &VK, 63540b57cec5SDimitry Andric ExprObjectKind &OK, 63550b57cec5SDimitry Andric SourceLocation QuestionLoc) { 6356480093f4SDimitry Andric // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface 6357480093f4SDimitry Andric // pointers. 63580b57cec5SDimitry Andric 63590b57cec5SDimitry Andric // Assume r-value. 6360fe6060f1SDimitry Andric VK = VK_PRValue; 63610b57cec5SDimitry Andric OK = OK_Ordinary; 6362480093f4SDimitry Andric bool IsVectorConditional = 6363480093f4SDimitry Andric isValidVectorForConditionalCondition(Context, Cond.get()->getType()); 6364480093f4SDimitry Andric 636581ad6265SDimitry Andric bool IsSizelessVectorConditional = 636681ad6265SDimitry Andric isValidSizelessVectorForConditionalCondition(Context, 636781ad6265SDimitry Andric Cond.get()->getType()); 636881ad6265SDimitry Andric 6369480093f4SDimitry Andric // C++11 [expr.cond]p1 6370480093f4SDimitry Andric // The first expression is contextually converted to bool. 6371480093f4SDimitry Andric if (!Cond.get()->isTypeDependent()) { 637281ad6265SDimitry Andric ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional 6373480093f4SDimitry Andric ? DefaultFunctionArrayLvalueConversion(Cond.get()) 6374480093f4SDimitry Andric : CheckCXXBooleanCondition(Cond.get()); 6375480093f4SDimitry Andric if (CondRes.isInvalid()) 6376480093f4SDimitry Andric return QualType(); 6377480093f4SDimitry Andric Cond = CondRes; 6378480093f4SDimitry Andric } else { 6379480093f4SDimitry Andric // To implement C++, the first expression typically doesn't alter the result 6380480093f4SDimitry Andric // type of the conditional, however the GCC compatible vector extension 6381480093f4SDimitry Andric // changes the result type to be that of the conditional. Since we cannot 6382480093f4SDimitry Andric // know if this is a vector extension here, delay the conversion of the 6383480093f4SDimitry Andric // LHS/RHS below until later. 6384480093f4SDimitry Andric return Context.DependentTy; 6385480093f4SDimitry Andric } 6386480093f4SDimitry Andric 63870b57cec5SDimitry Andric 63880b57cec5SDimitry Andric // Either of the arguments dependent? 63890b57cec5SDimitry Andric if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 63900b57cec5SDimitry Andric return Context.DependentTy; 63910b57cec5SDimitry Andric 63920b57cec5SDimitry Andric // C++11 [expr.cond]p2 63930b57cec5SDimitry Andric // If either the second or the third operand has type (cv) void, ... 63940b57cec5SDimitry Andric QualType LTy = LHS.get()->getType(); 63950b57cec5SDimitry Andric QualType RTy = RHS.get()->getType(); 63960b57cec5SDimitry Andric bool LVoid = LTy->isVoidType(); 63970b57cec5SDimitry Andric bool RVoid = RTy->isVoidType(); 63980b57cec5SDimitry Andric if (LVoid || RVoid) { 63990b57cec5SDimitry Andric // ... one of the following shall hold: 64000b57cec5SDimitry Andric // -- The second or the third operand (but not both) is a (possibly 64010b57cec5SDimitry Andric // parenthesized) throw-expression; the result is of the type 64020b57cec5SDimitry Andric // and value category of the other. 64030b57cec5SDimitry Andric bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); 64040b57cec5SDimitry Andric bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); 6405480093f4SDimitry Andric 6406480093f4SDimitry Andric // Void expressions aren't legal in the vector-conditional expressions. 6407480093f4SDimitry Andric if (IsVectorConditional) { 6408480093f4SDimitry Andric SourceRange DiagLoc = 6409480093f4SDimitry Andric LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); 6410480093f4SDimitry Andric bool IsThrow = LVoid ? LThrow : RThrow; 6411480093f4SDimitry Andric Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) 6412480093f4SDimitry Andric << DiagLoc << IsThrow; 6413480093f4SDimitry Andric return QualType(); 6414480093f4SDimitry Andric } 6415480093f4SDimitry Andric 64160b57cec5SDimitry Andric if (LThrow != RThrow) { 64170b57cec5SDimitry Andric Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); 64180b57cec5SDimitry Andric VK = NonThrow->getValueKind(); 64190b57cec5SDimitry Andric // DR (no number yet): the result is a bit-field if the 64200b57cec5SDimitry Andric // non-throw-expression operand is a bit-field. 64210b57cec5SDimitry Andric OK = NonThrow->getObjectKind(); 64220b57cec5SDimitry Andric return NonThrow->getType(); 64230b57cec5SDimitry Andric } 64240b57cec5SDimitry Andric 64250b57cec5SDimitry Andric // -- Both the second and third operands have type void; the result is of 64260b57cec5SDimitry Andric // type void and is a prvalue. 64270b57cec5SDimitry Andric if (LVoid && RVoid) 64280b57cec5SDimitry Andric return Context.VoidTy; 64290b57cec5SDimitry Andric 64300b57cec5SDimitry Andric // Neither holds, error. 64310b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 64320b57cec5SDimitry Andric << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 64330b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 64340b57cec5SDimitry Andric return QualType(); 64350b57cec5SDimitry Andric } 64360b57cec5SDimitry Andric 64370b57cec5SDimitry Andric // Neither is void. 6438480093f4SDimitry Andric if (IsVectorConditional) 6439fe6060f1SDimitry Andric return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); 64400b57cec5SDimitry Andric 644181ad6265SDimitry Andric if (IsSizelessVectorConditional) 644281ad6265SDimitry Andric return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); 644381ad6265SDimitry Andric 64440b57cec5SDimitry Andric // C++11 [expr.cond]p3 64450b57cec5SDimitry Andric // Otherwise, if the second and third operand have different types, and 64460b57cec5SDimitry Andric // either has (cv) class type [...] an attempt is made to convert each of 64470b57cec5SDimitry Andric // those operands to the type of the other. 64480b57cec5SDimitry Andric if (!Context.hasSameType(LTy, RTy) && 64490b57cec5SDimitry Andric (LTy->isRecordType() || RTy->isRecordType())) { 64500b57cec5SDimitry Andric // These return true if a single direction is already ambiguous. 64510b57cec5SDimitry Andric QualType L2RType, R2LType; 64520b57cec5SDimitry Andric bool HaveL2R, HaveR2L; 64530b57cec5SDimitry Andric if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 64540b57cec5SDimitry Andric return QualType(); 64550b57cec5SDimitry Andric if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 64560b57cec5SDimitry Andric return QualType(); 64570b57cec5SDimitry Andric 64580b57cec5SDimitry Andric // If both can be converted, [...] the program is ill-formed. 64590b57cec5SDimitry Andric if (HaveL2R && HaveR2L) { 64600b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_conditional_ambiguous) 64610b57cec5SDimitry Andric << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 64620b57cec5SDimitry Andric return QualType(); 64630b57cec5SDimitry Andric } 64640b57cec5SDimitry Andric 64650b57cec5SDimitry Andric // If exactly one conversion is possible, that conversion is applied to 64660b57cec5SDimitry Andric // the chosen operand and the converted operands are used in place of the 64670b57cec5SDimitry Andric // original operands for the remainder of this section. 64680b57cec5SDimitry Andric if (HaveL2R) { 64690b57cec5SDimitry Andric if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 64700b57cec5SDimitry Andric return QualType(); 64710b57cec5SDimitry Andric LTy = LHS.get()->getType(); 64720b57cec5SDimitry Andric } else if (HaveR2L) { 64730b57cec5SDimitry Andric if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 64740b57cec5SDimitry Andric return QualType(); 64750b57cec5SDimitry Andric RTy = RHS.get()->getType(); 64760b57cec5SDimitry Andric } 64770b57cec5SDimitry Andric } 64780b57cec5SDimitry Andric 64790b57cec5SDimitry Andric // C++11 [expr.cond]p3 64800b57cec5SDimitry Andric // if both are glvalues of the same value category and the same type except 64810b57cec5SDimitry Andric // for cv-qualification, an attempt is made to convert each of those 64820b57cec5SDimitry Andric // operands to the type of the other. 64830b57cec5SDimitry Andric // FIXME: 64840b57cec5SDimitry Andric // Resolving a defect in P0012R1: we extend this to cover all cases where 64850b57cec5SDimitry Andric // one of the operands is reference-compatible with the other, in order 6486480093f4SDimitry Andric // to support conditionals between functions differing in noexcept. This 6487480093f4SDimitry Andric // will similarly cover difference in array bounds after P0388R4. 6488480093f4SDimitry Andric // FIXME: If LTy and RTy have a composite pointer type, should we convert to 6489480093f4SDimitry Andric // that instead? 64900b57cec5SDimitry Andric ExprValueKind LVK = LHS.get()->getValueKind(); 64910b57cec5SDimitry Andric ExprValueKind RVK = RHS.get()->getValueKind(); 6492fe6060f1SDimitry Andric if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) { 64930b57cec5SDimitry Andric // DerivedToBase was already handled by the class-specific case above. 64940b57cec5SDimitry Andric // FIXME: Should we allow ObjC conversions here? 6495480093f4SDimitry Andric const ReferenceConversions AllowedConversions = 6496480093f4SDimitry Andric ReferenceConversions::Qualification | 6497480093f4SDimitry Andric ReferenceConversions::NestedQualification | 6498480093f4SDimitry Andric ReferenceConversions::Function; 6499480093f4SDimitry Andric 6500480093f4SDimitry Andric ReferenceConversions RefConv; 6501480093f4SDimitry Andric if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) == 6502480093f4SDimitry Andric Ref_Compatible && 6503480093f4SDimitry Andric !(RefConv & ~AllowedConversions) && 65040b57cec5SDimitry Andric // [...] subject to the constraint that the reference must bind 65050b57cec5SDimitry Andric // directly [...] 6506a7dea167SDimitry Andric !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { 65070b57cec5SDimitry Andric RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); 65080b57cec5SDimitry Andric RTy = RHS.get()->getType(); 6509480093f4SDimitry Andric } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) == 6510480093f4SDimitry Andric Ref_Compatible && 6511480093f4SDimitry Andric !(RefConv & ~AllowedConversions) && 65120b57cec5SDimitry Andric !LHS.get()->refersToBitField() && 65130b57cec5SDimitry Andric !LHS.get()->refersToVectorElement()) { 65140b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); 65150b57cec5SDimitry Andric LTy = LHS.get()->getType(); 65160b57cec5SDimitry Andric } 65170b57cec5SDimitry Andric } 65180b57cec5SDimitry Andric 65190b57cec5SDimitry Andric // C++11 [expr.cond]p4 65200b57cec5SDimitry Andric // If the second and third operands are glvalues of the same value 65210b57cec5SDimitry Andric // category and have the same type, the result is of that type and 65220b57cec5SDimitry Andric // value category and it is a bit-field if the second or the third 65230b57cec5SDimitry Andric // operand is a bit-field, or if both are bit-fields. 65240b57cec5SDimitry Andric // We only extend this to bitfields, not to the crazy other kinds of 65250b57cec5SDimitry Andric // l-values. 65260b57cec5SDimitry Andric bool Same = Context.hasSameType(LTy, RTy); 6527fe6060f1SDimitry Andric if (Same && LVK == RVK && LVK != VK_PRValue && 65280b57cec5SDimitry Andric LHS.get()->isOrdinaryOrBitFieldObject() && 65290b57cec5SDimitry Andric RHS.get()->isOrdinaryOrBitFieldObject()) { 65300b57cec5SDimitry Andric VK = LHS.get()->getValueKind(); 65310b57cec5SDimitry Andric if (LHS.get()->getObjectKind() == OK_BitField || 65320b57cec5SDimitry Andric RHS.get()->getObjectKind() == OK_BitField) 65330b57cec5SDimitry Andric OK = OK_BitField; 65340b57cec5SDimitry Andric 65350b57cec5SDimitry Andric // If we have function pointer types, unify them anyway to unify their 65360b57cec5SDimitry Andric // exception specifications, if any. 65370b57cec5SDimitry Andric if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 65380b57cec5SDimitry Andric Qualifiers Qs = LTy.getQualifiers(); 65390b57cec5SDimitry Andric LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, 65400b57cec5SDimitry Andric /*ConvertArgs*/false); 65410b57cec5SDimitry Andric LTy = Context.getQualifiedType(LTy, Qs); 65420b57cec5SDimitry Andric 65430b57cec5SDimitry Andric assert(!LTy.isNull() && "failed to find composite pointer type for " 65440b57cec5SDimitry Andric "canonically equivalent function ptr types"); 65450b57cec5SDimitry Andric assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type"); 65460b57cec5SDimitry Andric } 65470b57cec5SDimitry Andric 65480b57cec5SDimitry Andric return LTy; 65490b57cec5SDimitry Andric } 65500b57cec5SDimitry Andric 65510b57cec5SDimitry Andric // C++11 [expr.cond]p5 65520b57cec5SDimitry Andric // Otherwise, the result is a prvalue. If the second and third operands 65530b57cec5SDimitry Andric // do not have the same type, and either has (cv) class type, ... 65540b57cec5SDimitry Andric if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 65550b57cec5SDimitry Andric // ... overload resolution is used to determine the conversions (if any) 65560b57cec5SDimitry Andric // to be applied to the operands. If the overload resolution fails, the 65570b57cec5SDimitry Andric // program is ill-formed. 65580b57cec5SDimitry Andric if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 65590b57cec5SDimitry Andric return QualType(); 65600b57cec5SDimitry Andric } 65610b57cec5SDimitry Andric 65620b57cec5SDimitry Andric // C++11 [expr.cond]p6 65630b57cec5SDimitry Andric // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 65640b57cec5SDimitry Andric // conversions are performed on the second and third operands. 65650b57cec5SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 65660b57cec5SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 65670b57cec5SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 65680b57cec5SDimitry Andric return QualType(); 65690b57cec5SDimitry Andric LTy = LHS.get()->getType(); 65700b57cec5SDimitry Andric RTy = RHS.get()->getType(); 65710b57cec5SDimitry Andric 65720b57cec5SDimitry Andric // After those conversions, one of the following shall hold: 65730b57cec5SDimitry Andric // -- The second and third operands have the same type; the result 65740b57cec5SDimitry Andric // is of that type. If the operands have class type, the result 65750b57cec5SDimitry Andric // is a prvalue temporary of the result type, which is 65760b57cec5SDimitry Andric // copy-initialized from either the second operand or the third 65770b57cec5SDimitry Andric // operand depending on the value of the first operand. 65780b57cec5SDimitry Andric if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 65790b57cec5SDimitry Andric if (LTy->isRecordType()) { 65800b57cec5SDimitry Andric // The operands have class type. Make a temporary copy. 65810b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 65820b57cec5SDimitry Andric 65830b57cec5SDimitry Andric ExprResult LHSCopy = PerformCopyInitialization(Entity, 65840b57cec5SDimitry Andric SourceLocation(), 65850b57cec5SDimitry Andric LHS); 65860b57cec5SDimitry Andric if (LHSCopy.isInvalid()) 65870b57cec5SDimitry Andric return QualType(); 65880b57cec5SDimitry Andric 65890b57cec5SDimitry Andric ExprResult RHSCopy = PerformCopyInitialization(Entity, 65900b57cec5SDimitry Andric SourceLocation(), 65910b57cec5SDimitry Andric RHS); 65920b57cec5SDimitry Andric if (RHSCopy.isInvalid()) 65930b57cec5SDimitry Andric return QualType(); 65940b57cec5SDimitry Andric 65950b57cec5SDimitry Andric LHS = LHSCopy; 65960b57cec5SDimitry Andric RHS = RHSCopy; 65970b57cec5SDimitry Andric } 65980b57cec5SDimitry Andric 65990b57cec5SDimitry Andric // If we have function pointer types, unify them anyway to unify their 66000b57cec5SDimitry Andric // exception specifications, if any. 66010b57cec5SDimitry Andric if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 66020b57cec5SDimitry Andric LTy = FindCompositePointerType(QuestionLoc, LHS, RHS); 66030b57cec5SDimitry Andric assert(!LTy.isNull() && "failed to find composite pointer type for " 66040b57cec5SDimitry Andric "canonically equivalent function ptr types"); 66050b57cec5SDimitry Andric } 66060b57cec5SDimitry Andric 66070b57cec5SDimitry Andric return LTy; 66080b57cec5SDimitry Andric } 66090b57cec5SDimitry Andric 66100b57cec5SDimitry Andric // Extension: conditional operator involving vector types. 66110b57cec5SDimitry Andric if (LTy->isVectorType() || RTy->isVectorType()) 66120b57cec5SDimitry Andric return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 66130b57cec5SDimitry Andric /*AllowBothBool*/ true, 661481ad6265SDimitry Andric /*AllowBoolConversions*/ false, 661581ad6265SDimitry Andric /*AllowBoolOperation*/ false, 661681ad6265SDimitry Andric /*ReportInvalid*/ true); 66170b57cec5SDimitry Andric 66180b57cec5SDimitry Andric // -- The second and third operands have arithmetic or enumeration type; 66190b57cec5SDimitry Andric // the usual arithmetic conversions are performed to bring them to a 66200b57cec5SDimitry Andric // common type, and the result is of that type. 66210b57cec5SDimitry Andric if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 6622480093f4SDimitry Andric QualType ResTy = 6623480093f4SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 66240b57cec5SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 66250b57cec5SDimitry Andric return QualType(); 66260b57cec5SDimitry Andric if (ResTy.isNull()) { 66270b57cec5SDimitry Andric Diag(QuestionLoc, 66280b57cec5SDimitry Andric diag::err_typecheck_cond_incompatible_operands) << LTy << RTy 66290b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 66300b57cec5SDimitry Andric return QualType(); 66310b57cec5SDimitry Andric } 66320b57cec5SDimitry Andric 66330b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 66340b57cec5SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 66350b57cec5SDimitry Andric 66360b57cec5SDimitry Andric return ResTy; 66370b57cec5SDimitry Andric } 66380b57cec5SDimitry Andric 66390b57cec5SDimitry Andric // -- The second and third operands have pointer type, or one has pointer 66400b57cec5SDimitry Andric // type and the other is a null pointer constant, or both are null 66410b57cec5SDimitry Andric // pointer constants, at least one of which is non-integral; pointer 66420b57cec5SDimitry Andric // conversions and qualification conversions are performed to bring them 66430b57cec5SDimitry Andric // to their composite pointer type. The result is of the composite 66440b57cec5SDimitry Andric // pointer type. 66450b57cec5SDimitry Andric // -- The second and third operands have pointer to member type, or one has 66460b57cec5SDimitry Andric // pointer to member type and the other is a null pointer constant; 66470b57cec5SDimitry Andric // pointer to member conversions and qualification conversions are 66480b57cec5SDimitry Andric // performed to bring them to a common type, whose cv-qualification 66490b57cec5SDimitry Andric // shall match the cv-qualification of either the second or the third 66500b57cec5SDimitry Andric // operand. The result is of the common type. 66510b57cec5SDimitry Andric QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); 66520b57cec5SDimitry Andric if (!Composite.isNull()) 66530b57cec5SDimitry Andric return Composite; 66540b57cec5SDimitry Andric 66550b57cec5SDimitry Andric // Similarly, attempt to find composite type of two objective-c pointers. 66560b57cec5SDimitry Andric Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 6657e8d8bef9SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 6658e8d8bef9SDimitry Andric return QualType(); 66590b57cec5SDimitry Andric if (!Composite.isNull()) 66600b57cec5SDimitry Andric return Composite; 66610b57cec5SDimitry Andric 66620b57cec5SDimitry Andric // Check if we are using a null with a non-pointer type. 66630b57cec5SDimitry Andric if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 66640b57cec5SDimitry Andric return QualType(); 66650b57cec5SDimitry Andric 66660b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 66670b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 66680b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 66690b57cec5SDimitry Andric return QualType(); 66700b57cec5SDimitry Andric } 66710b57cec5SDimitry Andric 66720b57cec5SDimitry Andric static FunctionProtoType::ExceptionSpecInfo 66730b57cec5SDimitry Andric mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, 66740b57cec5SDimitry Andric FunctionProtoType::ExceptionSpecInfo ESI2, 66750b57cec5SDimitry Andric SmallVectorImpl<QualType> &ExceptionTypeStorage) { 66760b57cec5SDimitry Andric ExceptionSpecificationType EST1 = ESI1.Type; 66770b57cec5SDimitry Andric ExceptionSpecificationType EST2 = ESI2.Type; 66780b57cec5SDimitry Andric 66790b57cec5SDimitry Andric // If either of them can throw anything, that is the result. 66800b57cec5SDimitry Andric if (EST1 == EST_None) return ESI1; 66810b57cec5SDimitry Andric if (EST2 == EST_None) return ESI2; 66820b57cec5SDimitry Andric if (EST1 == EST_MSAny) return ESI1; 66830b57cec5SDimitry Andric if (EST2 == EST_MSAny) return ESI2; 66840b57cec5SDimitry Andric if (EST1 == EST_NoexceptFalse) return ESI1; 66850b57cec5SDimitry Andric if (EST2 == EST_NoexceptFalse) return ESI2; 66860b57cec5SDimitry Andric 66870b57cec5SDimitry Andric // If either of them is non-throwing, the result is the other. 66880b57cec5SDimitry Andric if (EST1 == EST_NoThrow) return ESI2; 66890b57cec5SDimitry Andric if (EST2 == EST_NoThrow) return ESI1; 66900b57cec5SDimitry Andric if (EST1 == EST_DynamicNone) return ESI2; 66910b57cec5SDimitry Andric if (EST2 == EST_DynamicNone) return ESI1; 66920b57cec5SDimitry Andric if (EST1 == EST_BasicNoexcept) return ESI2; 66930b57cec5SDimitry Andric if (EST2 == EST_BasicNoexcept) return ESI1; 66940b57cec5SDimitry Andric if (EST1 == EST_NoexceptTrue) return ESI2; 66950b57cec5SDimitry Andric if (EST2 == EST_NoexceptTrue) return ESI1; 66960b57cec5SDimitry Andric 66970b57cec5SDimitry Andric // If we're left with value-dependent computed noexcept expressions, we're 66980b57cec5SDimitry Andric // stuck. Before C++17, we can just drop the exception specification entirely, 66990b57cec5SDimitry Andric // since it's not actually part of the canonical type. And this should never 67000b57cec5SDimitry Andric // happen in C++17, because it would mean we were computing the composite 67010b57cec5SDimitry Andric // pointer type of dependent types, which should never happen. 67020b57cec5SDimitry Andric if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) { 67030b57cec5SDimitry Andric assert(!S.getLangOpts().CPlusPlus17 && 67040b57cec5SDimitry Andric "computing composite pointer type of dependent types"); 67050b57cec5SDimitry Andric return FunctionProtoType::ExceptionSpecInfo(); 67060b57cec5SDimitry Andric } 67070b57cec5SDimitry Andric 67080b57cec5SDimitry Andric // Switch over the possibilities so that people adding new values know to 67090b57cec5SDimitry Andric // update this function. 67100b57cec5SDimitry Andric switch (EST1) { 67110b57cec5SDimitry Andric case EST_None: 67120b57cec5SDimitry Andric case EST_DynamicNone: 67130b57cec5SDimitry Andric case EST_MSAny: 67140b57cec5SDimitry Andric case EST_BasicNoexcept: 67150b57cec5SDimitry Andric case EST_DependentNoexcept: 67160b57cec5SDimitry Andric case EST_NoexceptFalse: 67170b57cec5SDimitry Andric case EST_NoexceptTrue: 67180b57cec5SDimitry Andric case EST_NoThrow: 67190b57cec5SDimitry Andric llvm_unreachable("handled above"); 67200b57cec5SDimitry Andric 67210b57cec5SDimitry Andric case EST_Dynamic: { 67220b57cec5SDimitry Andric // This is the fun case: both exception specifications are dynamic. Form 67230b57cec5SDimitry Andric // the union of the two lists. 67240b57cec5SDimitry Andric assert(EST2 == EST_Dynamic && "other cases should already be handled"); 67250b57cec5SDimitry Andric llvm::SmallPtrSet<QualType, 8> Found; 67260b57cec5SDimitry Andric for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions}) 67270b57cec5SDimitry Andric for (QualType E : Exceptions) 67280b57cec5SDimitry Andric if (Found.insert(S.Context.getCanonicalType(E)).second) 67290b57cec5SDimitry Andric ExceptionTypeStorage.push_back(E); 67300b57cec5SDimitry Andric 67310b57cec5SDimitry Andric FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); 67320b57cec5SDimitry Andric Result.Exceptions = ExceptionTypeStorage; 67330b57cec5SDimitry Andric return Result; 67340b57cec5SDimitry Andric } 67350b57cec5SDimitry Andric 67360b57cec5SDimitry Andric case EST_Unevaluated: 67370b57cec5SDimitry Andric case EST_Uninstantiated: 67380b57cec5SDimitry Andric case EST_Unparsed: 67390b57cec5SDimitry Andric llvm_unreachable("shouldn't see unresolved exception specifications here"); 67400b57cec5SDimitry Andric } 67410b57cec5SDimitry Andric 67420b57cec5SDimitry Andric llvm_unreachable("invalid ExceptionSpecificationType"); 67430b57cec5SDimitry Andric } 67440b57cec5SDimitry Andric 67450b57cec5SDimitry Andric /// Find a merged pointer type and convert the two expressions to it. 67460b57cec5SDimitry Andric /// 6747480093f4SDimitry Andric /// This finds the composite pointer type for \p E1 and \p E2 according to 6748480093f4SDimitry Andric /// C++2a [expr.type]p3. It converts both expressions to this type and returns 6749480093f4SDimitry Andric /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs 6750480093f4SDimitry Andric /// is \c true). 67510b57cec5SDimitry Andric /// 67520b57cec5SDimitry Andric /// \param Loc The location of the operator requiring these two expressions to 67530b57cec5SDimitry Andric /// be converted to the composite pointer type. 67540b57cec5SDimitry Andric /// 67550b57cec5SDimitry Andric /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. 67560b57cec5SDimitry Andric QualType Sema::FindCompositePointerType(SourceLocation Loc, 67570b57cec5SDimitry Andric Expr *&E1, Expr *&E2, 67580b57cec5SDimitry Andric bool ConvertArgs) { 67590b57cec5SDimitry Andric assert(getLangOpts().CPlusPlus && "This function assumes C++"); 67600b57cec5SDimitry Andric 67610b57cec5SDimitry Andric // C++1z [expr]p14: 67620b57cec5SDimitry Andric // The composite pointer type of two operands p1 and p2 having types T1 67630b57cec5SDimitry Andric // and T2 67640b57cec5SDimitry Andric QualType T1 = E1->getType(), T2 = E2->getType(); 67650b57cec5SDimitry Andric 67660b57cec5SDimitry Andric // where at least one is a pointer or pointer to member type or 67670b57cec5SDimitry Andric // std::nullptr_t is: 67680b57cec5SDimitry Andric bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || 67690b57cec5SDimitry Andric T1->isNullPtrType(); 67700b57cec5SDimitry Andric bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || 67710b57cec5SDimitry Andric T2->isNullPtrType(); 67720b57cec5SDimitry Andric if (!T1IsPointerLike && !T2IsPointerLike) 67730b57cec5SDimitry Andric return QualType(); 67740b57cec5SDimitry Andric 67750b57cec5SDimitry Andric // - if both p1 and p2 are null pointer constants, std::nullptr_t; 67760b57cec5SDimitry Andric // This can't actually happen, following the standard, but we also use this 67770b57cec5SDimitry Andric // to implement the end of [expr.conv], which hits this case. 67780b57cec5SDimitry Andric // 67790b57cec5SDimitry Andric // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; 67800b57cec5SDimitry Andric if (T1IsPointerLike && 67810b57cec5SDimitry Andric E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 67820b57cec5SDimitry Andric if (ConvertArgs) 67830b57cec5SDimitry Andric E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() 67840b57cec5SDimitry Andric ? CK_NullToMemberPointer 67850b57cec5SDimitry Andric : CK_NullToPointer).get(); 67860b57cec5SDimitry Andric return T1; 67870b57cec5SDimitry Andric } 67880b57cec5SDimitry Andric if (T2IsPointerLike && 67890b57cec5SDimitry Andric E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 67900b57cec5SDimitry Andric if (ConvertArgs) 67910b57cec5SDimitry Andric E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() 67920b57cec5SDimitry Andric ? CK_NullToMemberPointer 67930b57cec5SDimitry Andric : CK_NullToPointer).get(); 67940b57cec5SDimitry Andric return T2; 67950b57cec5SDimitry Andric } 67960b57cec5SDimitry Andric 67970b57cec5SDimitry Andric // Now both have to be pointers or member pointers. 67980b57cec5SDimitry Andric if (!T1IsPointerLike || !T2IsPointerLike) 67990b57cec5SDimitry Andric return QualType(); 68000b57cec5SDimitry Andric assert(!T1->isNullPtrType() && !T2->isNullPtrType() && 68010b57cec5SDimitry Andric "nullptr_t should be a null pointer constant"); 68020b57cec5SDimitry Andric 6803480093f4SDimitry Andric struct Step { 6804480093f4SDimitry Andric enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; 6805480093f4SDimitry Andric // Qualifiers to apply under the step kind. 6806480093f4SDimitry Andric Qualifiers Quals; 6807480093f4SDimitry Andric /// The class for a pointer-to-member; a constant array type with a bound 6808480093f4SDimitry Andric /// (if any) for an array. 6809480093f4SDimitry Andric const Type *ClassOrBound; 6810480093f4SDimitry Andric 6811480093f4SDimitry Andric Step(Kind K, const Type *ClassOrBound = nullptr) 681204eeddc0SDimitry Andric : K(K), ClassOrBound(ClassOrBound) {} 6813480093f4SDimitry Andric QualType rebuild(ASTContext &Ctx, QualType T) const { 6814480093f4SDimitry Andric T = Ctx.getQualifiedType(T, Quals); 6815480093f4SDimitry Andric switch (K) { 6816480093f4SDimitry Andric case Pointer: 6817480093f4SDimitry Andric return Ctx.getPointerType(T); 6818480093f4SDimitry Andric case MemberPointer: 6819480093f4SDimitry Andric return Ctx.getMemberPointerType(T, ClassOrBound); 6820480093f4SDimitry Andric case ObjCPointer: 6821480093f4SDimitry Andric return Ctx.getObjCObjectPointerType(T); 6822480093f4SDimitry Andric case Array: 6823480093f4SDimitry Andric if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound)) 6824480093f4SDimitry Andric return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr, 6825480093f4SDimitry Andric ArrayType::Normal, 0); 6826480093f4SDimitry Andric else 6827480093f4SDimitry Andric return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0); 6828480093f4SDimitry Andric } 6829480093f4SDimitry Andric llvm_unreachable("unknown step kind"); 6830480093f4SDimitry Andric } 6831480093f4SDimitry Andric }; 6832480093f4SDimitry Andric 6833480093f4SDimitry Andric SmallVector<Step, 8> Steps; 6834480093f4SDimitry Andric 68350b57cec5SDimitry Andric // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 68360b57cec5SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 68370b57cec5SDimitry Andric // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, 68380b57cec5SDimitry Andric // respectively; 68390b57cec5SDimitry Andric // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer 6840480093f4SDimitry Andric // to member of C2 of type cv2 U2" for some non-function type U, where 6841480093f4SDimitry Andric // C1 is reference-related to C2 or C2 is reference-related to C1, the 6842480093f4SDimitry Andric // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, 6843480093f4SDimitry Andric // respectively; 68440b57cec5SDimitry Andric // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and 68450b57cec5SDimitry Andric // T2; 68460b57cec5SDimitry Andric // 6847480093f4SDimitry Andric // Dismantle T1 and T2 to simultaneously determine whether they are similar 6848480093f4SDimitry Andric // and to prepare to form the cv-combined type if so. 68490b57cec5SDimitry Andric QualType Composite1 = T1; 68500b57cec5SDimitry Andric QualType Composite2 = T2; 68510b57cec5SDimitry Andric unsigned NeedConstBefore = 0; 68520b57cec5SDimitry Andric while (true) { 6853480093f4SDimitry Andric assert(!Composite1.isNull() && !Composite2.isNull()); 6854480093f4SDimitry Andric 6855480093f4SDimitry Andric Qualifiers Q1, Q2; 6856480093f4SDimitry Andric Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); 6857480093f4SDimitry Andric Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); 6858480093f4SDimitry Andric 6859480093f4SDimitry Andric // Top-level qualifiers are ignored. Merge at all lower levels. 6860480093f4SDimitry Andric if (!Steps.empty()) { 6861480093f4SDimitry Andric // Find the qualifier union: (approximately) the unique minimal set of 6862480093f4SDimitry Andric // qualifiers that is compatible with both types. 6863480093f4SDimitry Andric Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | 6864480093f4SDimitry Andric Q2.getCVRUQualifiers()); 6865480093f4SDimitry Andric 6866480093f4SDimitry Andric // Under one level of pointer or pointer-to-member, we can change to an 6867480093f4SDimitry Andric // unambiguous compatible address space. 6868480093f4SDimitry Andric if (Q1.getAddressSpace() == Q2.getAddressSpace()) { 6869480093f4SDimitry Andric Quals.setAddressSpace(Q1.getAddressSpace()); 6870480093f4SDimitry Andric } else if (Steps.size() == 1) { 6871480093f4SDimitry Andric bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2); 6872480093f4SDimitry Andric bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1); 6873349cc55cSDimitry Andric if (MaybeQ1 == MaybeQ2) { 6874349cc55cSDimitry Andric // Exception for ptr size address spaces. Should be able to choose 6875349cc55cSDimitry Andric // either address space during comparison. 6876349cc55cSDimitry Andric if (isPtrSizeAddressSpace(Q1.getAddressSpace()) || 6877349cc55cSDimitry Andric isPtrSizeAddressSpace(Q2.getAddressSpace())) 6878349cc55cSDimitry Andric MaybeQ1 = true; 6879349cc55cSDimitry Andric else 6880480093f4SDimitry Andric return QualType(); // No unique best address space. 6881349cc55cSDimitry Andric } 6882480093f4SDimitry Andric Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() 6883480093f4SDimitry Andric : Q2.getAddressSpace()); 6884480093f4SDimitry Andric } else { 6885480093f4SDimitry Andric return QualType(); 6886480093f4SDimitry Andric } 6887480093f4SDimitry Andric 6888480093f4SDimitry Andric // FIXME: In C, we merge __strong and none to __strong at the top level. 6889480093f4SDimitry Andric if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) 6890480093f4SDimitry Andric Quals.setObjCGCAttr(Q1.getObjCGCAttr()); 6891e8d8bef9SDimitry Andric else if (T1->isVoidPointerType() || T2->isVoidPointerType()) 6892e8d8bef9SDimitry Andric assert(Steps.size() == 1); 6893480093f4SDimitry Andric else 6894480093f4SDimitry Andric return QualType(); 6895480093f4SDimitry Andric 6896480093f4SDimitry Andric // Mismatched lifetime qualifiers never compatibly include each other. 6897480093f4SDimitry Andric if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) 6898480093f4SDimitry Andric Quals.setObjCLifetime(Q1.getObjCLifetime()); 6899e8d8bef9SDimitry Andric else if (T1->isVoidPointerType() || T2->isVoidPointerType()) 6900e8d8bef9SDimitry Andric assert(Steps.size() == 1); 6901480093f4SDimitry Andric else 6902480093f4SDimitry Andric return QualType(); 6903480093f4SDimitry Andric 6904480093f4SDimitry Andric Steps.back().Quals = Quals; 6905480093f4SDimitry Andric if (Q1 != Quals || Q2 != Quals) 6906480093f4SDimitry Andric NeedConstBefore = Steps.size() - 1; 6907480093f4SDimitry Andric } 6908480093f4SDimitry Andric 6909480093f4SDimitry Andric // FIXME: Can we unify the following with UnwrapSimilarTypes? 6910349cc55cSDimitry Andric 6911349cc55cSDimitry Andric const ArrayType *Arr1, *Arr2; 6912349cc55cSDimitry Andric if ((Arr1 = Context.getAsArrayType(Composite1)) && 6913349cc55cSDimitry Andric (Arr2 = Context.getAsArrayType(Composite2))) { 6914349cc55cSDimitry Andric auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1); 6915349cc55cSDimitry Andric auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2); 6916349cc55cSDimitry Andric if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) { 6917349cc55cSDimitry Andric Composite1 = Arr1->getElementType(); 6918349cc55cSDimitry Andric Composite2 = Arr2->getElementType(); 6919349cc55cSDimitry Andric Steps.emplace_back(Step::Array, CAT1); 6920349cc55cSDimitry Andric continue; 6921349cc55cSDimitry Andric } 6922349cc55cSDimitry Andric bool IAT1 = isa<IncompleteArrayType>(Arr1); 6923349cc55cSDimitry Andric bool IAT2 = isa<IncompleteArrayType>(Arr2); 6924349cc55cSDimitry Andric if ((IAT1 && IAT2) || 6925349cc55cSDimitry Andric (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) && 6926349cc55cSDimitry Andric ((bool)CAT1 != (bool)CAT2) && 6927349cc55cSDimitry Andric (Steps.empty() || Steps.back().K != Step::Array))) { 6928349cc55cSDimitry Andric // In C++20 onwards, we can unify an array of N T with an array of 6929349cc55cSDimitry Andric // a different or unknown bound. But we can't form an array whose 6930349cc55cSDimitry Andric // element type is an array of unknown bound by doing so. 6931349cc55cSDimitry Andric Composite1 = Arr1->getElementType(); 6932349cc55cSDimitry Andric Composite2 = Arr2->getElementType(); 6933349cc55cSDimitry Andric Steps.emplace_back(Step::Array); 6934349cc55cSDimitry Andric if (CAT1 || CAT2) 6935349cc55cSDimitry Andric NeedConstBefore = Steps.size(); 6936349cc55cSDimitry Andric continue; 6937349cc55cSDimitry Andric } 6938349cc55cSDimitry Andric } 6939349cc55cSDimitry Andric 69400b57cec5SDimitry Andric const PointerType *Ptr1, *Ptr2; 69410b57cec5SDimitry Andric if ((Ptr1 = Composite1->getAs<PointerType>()) && 69420b57cec5SDimitry Andric (Ptr2 = Composite2->getAs<PointerType>())) { 69430b57cec5SDimitry Andric Composite1 = Ptr1->getPointeeType(); 69440b57cec5SDimitry Andric Composite2 = Ptr2->getPointeeType(); 6945480093f4SDimitry Andric Steps.emplace_back(Step::Pointer); 6946480093f4SDimitry Andric continue; 6947480093f4SDimitry Andric } 69480b57cec5SDimitry Andric 6949480093f4SDimitry Andric const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; 6950480093f4SDimitry Andric if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && 6951480093f4SDimitry Andric (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { 6952480093f4SDimitry Andric Composite1 = ObjPtr1->getPointeeType(); 6953480093f4SDimitry Andric Composite2 = ObjPtr2->getPointeeType(); 6954480093f4SDimitry Andric Steps.emplace_back(Step::ObjCPointer); 69550b57cec5SDimitry Andric continue; 69560b57cec5SDimitry Andric } 69570b57cec5SDimitry Andric 69580b57cec5SDimitry Andric const MemberPointerType *MemPtr1, *MemPtr2; 69590b57cec5SDimitry Andric if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 69600b57cec5SDimitry Andric (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 69610b57cec5SDimitry Andric Composite1 = MemPtr1->getPointeeType(); 69620b57cec5SDimitry Andric Composite2 = MemPtr2->getPointeeType(); 69630b57cec5SDimitry Andric 6964480093f4SDimitry Andric // At the top level, we can perform a base-to-derived pointer-to-member 6965480093f4SDimitry Andric // conversion: 6966480093f4SDimitry Andric // 6967480093f4SDimitry Andric // - [...] where C1 is reference-related to C2 or C2 is 6968480093f4SDimitry Andric // reference-related to C1 6969480093f4SDimitry Andric // 6970480093f4SDimitry Andric // (Note that the only kinds of reference-relatedness in scope here are 6971480093f4SDimitry Andric // "same type or derived from".) At any other level, the class must 6972480093f4SDimitry Andric // exactly match. 6973480093f4SDimitry Andric const Type *Class = nullptr; 6974480093f4SDimitry Andric QualType Cls1(MemPtr1->getClass(), 0); 6975480093f4SDimitry Andric QualType Cls2(MemPtr2->getClass(), 0); 6976480093f4SDimitry Andric if (Context.hasSameType(Cls1, Cls2)) 6977480093f4SDimitry Andric Class = MemPtr1->getClass(); 6978480093f4SDimitry Andric else if (Steps.empty()) 6979480093f4SDimitry Andric Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() : 6980480093f4SDimitry Andric IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr; 6981480093f4SDimitry Andric if (!Class) 6982480093f4SDimitry Andric return QualType(); 69830b57cec5SDimitry Andric 6984480093f4SDimitry Andric Steps.emplace_back(Step::MemberPointer, Class); 69850b57cec5SDimitry Andric continue; 69860b57cec5SDimitry Andric } 69870b57cec5SDimitry Andric 6988480093f4SDimitry Andric // Special case: at the top level, we can decompose an Objective-C pointer 6989480093f4SDimitry Andric // and a 'cv void *'. Unify the qualifiers. 6990480093f4SDimitry Andric if (Steps.empty() && ((Composite1->isVoidPointerType() && 6991480093f4SDimitry Andric Composite2->isObjCObjectPointerType()) || 6992480093f4SDimitry Andric (Composite1->isObjCObjectPointerType() && 6993480093f4SDimitry Andric Composite2->isVoidPointerType()))) { 6994480093f4SDimitry Andric Composite1 = Composite1->getPointeeType(); 6995480093f4SDimitry Andric Composite2 = Composite2->getPointeeType(); 6996480093f4SDimitry Andric Steps.emplace_back(Step::Pointer); 6997480093f4SDimitry Andric continue; 6998480093f4SDimitry Andric } 6999480093f4SDimitry Andric 70000b57cec5SDimitry Andric // FIXME: block pointer types? 70010b57cec5SDimitry Andric 70020b57cec5SDimitry Andric // Cannot unwrap any more types. 70030b57cec5SDimitry Andric break; 70040b57cec5SDimitry Andric } 70050b57cec5SDimitry Andric 7006480093f4SDimitry Andric // - if T1 or T2 is "pointer to noexcept function" and the other type is 7007480093f4SDimitry Andric // "pointer to function", where the function types are otherwise the same, 7008480093f4SDimitry Andric // "pointer to function"; 7009480093f4SDimitry Andric // - if T1 or T2 is "pointer to member of C1 of type function", the other 7010480093f4SDimitry Andric // type is "pointer to member of C2 of type noexcept function", and C1 7011480093f4SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1, where 7012480093f4SDimitry Andric // the function types are otherwise the same, "pointer to member of C2 of 7013480093f4SDimitry Andric // type function" or "pointer to member of C1 of type function", 7014480093f4SDimitry Andric // respectively; 7015480093f4SDimitry Andric // 7016480093f4SDimitry Andric // We also support 'noreturn' here, so as a Clang extension we generalize the 7017480093f4SDimitry Andric // above to: 7018480093f4SDimitry Andric // 7019480093f4SDimitry Andric // - [Clang] If T1 and T2 are both of type "pointer to function" or 7020480093f4SDimitry Andric // "pointer to member function" and the pointee types can be unified 7021480093f4SDimitry Andric // by a function pointer conversion, that conversion is applied 7022480093f4SDimitry Andric // before checking the following rules. 7023480093f4SDimitry Andric // 7024480093f4SDimitry Andric // We've already unwrapped down to the function types, and we want to merge 7025480093f4SDimitry Andric // rather than just convert, so do this ourselves rather than calling 70260b57cec5SDimitry Andric // IsFunctionConversion. 70270b57cec5SDimitry Andric // 70280b57cec5SDimitry Andric // FIXME: In order to match the standard wording as closely as possible, we 70290b57cec5SDimitry Andric // currently only do this under a single level of pointers. Ideally, we would 70300b57cec5SDimitry Andric // allow this in general, and set NeedConstBefore to the relevant depth on 7031480093f4SDimitry Andric // the side(s) where we changed anything. If we permit that, we should also 7032480093f4SDimitry Andric // consider this conversion when determining type similarity and model it as 7033480093f4SDimitry Andric // a qualification conversion. 7034480093f4SDimitry Andric if (Steps.size() == 1) { 70350b57cec5SDimitry Andric if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { 70360b57cec5SDimitry Andric if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { 70370b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); 70380b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); 70390b57cec5SDimitry Andric 70400b57cec5SDimitry Andric // The result is noreturn if both operands are. 70410b57cec5SDimitry Andric bool Noreturn = 70420b57cec5SDimitry Andric EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); 70430b57cec5SDimitry Andric EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); 70440b57cec5SDimitry Andric EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); 70450b57cec5SDimitry Andric 70460b57cec5SDimitry Andric // The result is nothrow if both operands are. 70470b57cec5SDimitry Andric SmallVector<QualType, 8> ExceptionTypeStorage; 70480b57cec5SDimitry Andric EPI1.ExceptionSpec = EPI2.ExceptionSpec = 70490b57cec5SDimitry Andric mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec, 70500b57cec5SDimitry Andric ExceptionTypeStorage); 70510b57cec5SDimitry Andric 70520b57cec5SDimitry Andric Composite1 = Context.getFunctionType(FPT1->getReturnType(), 70530b57cec5SDimitry Andric FPT1->getParamTypes(), EPI1); 70540b57cec5SDimitry Andric Composite2 = Context.getFunctionType(FPT2->getReturnType(), 70550b57cec5SDimitry Andric FPT2->getParamTypes(), EPI2); 70560b57cec5SDimitry Andric } 70570b57cec5SDimitry Andric } 70580b57cec5SDimitry Andric } 70590b57cec5SDimitry Andric 7060480093f4SDimitry Andric // There are some more conversions we can perform under exactly one pointer. 7061480093f4SDimitry Andric if (Steps.size() == 1 && Steps.front().K == Step::Pointer && 7062480093f4SDimitry Andric !Context.hasSameType(Composite1, Composite2)) { 7063480093f4SDimitry Andric // - if T1 or T2 is "pointer to cv1 void" and the other type is 7064480093f4SDimitry Andric // "pointer to cv2 T", where T is an object type or void, 7065480093f4SDimitry Andric // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; 7066480093f4SDimitry Andric if (Composite1->isVoidType() && Composite2->isObjectType()) 7067480093f4SDimitry Andric Composite2 = Composite1; 7068480093f4SDimitry Andric else if (Composite2->isVoidType() && Composite1->isObjectType()) 7069480093f4SDimitry Andric Composite1 = Composite2; 7070480093f4SDimitry Andric // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 7071480093f4SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 7072480093f4SDimitry Andric // the cv-combined type of T1 and T2 or the cv-combined type of T2 and 7073480093f4SDimitry Andric // T1, respectively; 7074480093f4SDimitry Andric // 7075480093f4SDimitry Andric // The "similar type" handling covers all of this except for the "T1 is a 7076480093f4SDimitry Andric // base class of T2" case in the definition of reference-related. 7077480093f4SDimitry Andric else if (IsDerivedFrom(Loc, Composite1, Composite2)) 7078480093f4SDimitry Andric Composite1 = Composite2; 7079480093f4SDimitry Andric else if (IsDerivedFrom(Loc, Composite2, Composite1)) 7080480093f4SDimitry Andric Composite2 = Composite1; 7081480093f4SDimitry Andric } 7082480093f4SDimitry Andric 7083480093f4SDimitry Andric // At this point, either the inner types are the same or we have failed to 7084480093f4SDimitry Andric // find a composite pointer type. 7085480093f4SDimitry Andric if (!Context.hasSameType(Composite1, Composite2)) 7086480093f4SDimitry Andric return QualType(); 7087480093f4SDimitry Andric 7088480093f4SDimitry Andric // Per C++ [conv.qual]p3, add 'const' to every level before the last 7089480093f4SDimitry Andric // differing qualifier. 70900b57cec5SDimitry Andric for (unsigned I = 0; I != NeedConstBefore; ++I) 7091480093f4SDimitry Andric Steps[I].Quals.addConst(); 70920b57cec5SDimitry Andric 7093480093f4SDimitry Andric // Rebuild the composite type. 7094480093f4SDimitry Andric QualType Composite = Composite1; 7095480093f4SDimitry Andric for (auto &S : llvm::reverse(Steps)) 7096480093f4SDimitry Andric Composite = S.rebuild(Context, Composite); 70970b57cec5SDimitry Andric 7098480093f4SDimitry Andric if (ConvertArgs) { 7099480093f4SDimitry Andric // Convert the expressions to the composite pointer type. 7100480093f4SDimitry Andric InitializedEntity Entity = 7101480093f4SDimitry Andric InitializedEntity::InitializeTemporary(Composite); 7102480093f4SDimitry Andric InitializationKind Kind = 7103480093f4SDimitry Andric InitializationKind::CreateCopy(Loc, SourceLocation()); 71040b57cec5SDimitry Andric 7105480093f4SDimitry Andric InitializationSequence E1ToC(*this, Entity, Kind, E1); 7106480093f4SDimitry Andric if (!E1ToC) 7107480093f4SDimitry Andric return QualType(); 71080b57cec5SDimitry Andric 7109480093f4SDimitry Andric InitializationSequence E2ToC(*this, Entity, Kind, E2); 7110480093f4SDimitry Andric if (!E2ToC) 7111480093f4SDimitry Andric return QualType(); 7112480093f4SDimitry Andric 7113480093f4SDimitry Andric // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. 7114480093f4SDimitry Andric ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1); 71150b57cec5SDimitry Andric if (E1Result.isInvalid()) 7116480093f4SDimitry Andric return QualType(); 7117480093f4SDimitry Andric E1 = E1Result.get(); 71180b57cec5SDimitry Andric 7119480093f4SDimitry Andric ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2); 71200b57cec5SDimitry Andric if (E2Result.isInvalid()) 71210b57cec5SDimitry Andric return QualType(); 7122480093f4SDimitry Andric E2 = E2Result.get(); 71230b57cec5SDimitry Andric } 71240b57cec5SDimitry Andric 7125480093f4SDimitry Andric return Composite; 71260b57cec5SDimitry Andric } 71270b57cec5SDimitry Andric 71280b57cec5SDimitry Andric ExprResult Sema::MaybeBindToTemporary(Expr *E) { 71290b57cec5SDimitry Andric if (!E) 71300b57cec5SDimitry Andric return ExprError(); 71310b57cec5SDimitry Andric 71320b57cec5SDimitry Andric assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 71330b57cec5SDimitry Andric 71340b57cec5SDimitry Andric // If the result is a glvalue, we shouldn't bind it. 7135fe6060f1SDimitry Andric if (E->isGLValue()) 71360b57cec5SDimitry Andric return E; 71370b57cec5SDimitry Andric 71380b57cec5SDimitry Andric // In ARC, calls that return a retainable type can return retained, 71390b57cec5SDimitry Andric // in which case we have to insert a consuming cast. 71400b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 71410b57cec5SDimitry Andric E->getType()->isObjCRetainableType()) { 71420b57cec5SDimitry Andric 71430b57cec5SDimitry Andric bool ReturnsRetained; 71440b57cec5SDimitry Andric 71450b57cec5SDimitry Andric // For actual calls, we compute this by examining the type of the 71460b57cec5SDimitry Andric // called value. 71470b57cec5SDimitry Andric if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 71480b57cec5SDimitry Andric Expr *Callee = Call->getCallee()->IgnoreParens(); 71490b57cec5SDimitry Andric QualType T = Callee->getType(); 71500b57cec5SDimitry Andric 71510b57cec5SDimitry Andric if (T == Context.BoundMemberTy) { 71520b57cec5SDimitry Andric // Handle pointer-to-members. 71530b57cec5SDimitry Andric if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 71540b57cec5SDimitry Andric T = BinOp->getRHS()->getType(); 71550b57cec5SDimitry Andric else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 71560b57cec5SDimitry Andric T = Mem->getMemberDecl()->getType(); 71570b57cec5SDimitry Andric } 71580b57cec5SDimitry Andric 71590b57cec5SDimitry Andric if (const PointerType *Ptr = T->getAs<PointerType>()) 71600b57cec5SDimitry Andric T = Ptr->getPointeeType(); 71610b57cec5SDimitry Andric else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 71620b57cec5SDimitry Andric T = Ptr->getPointeeType(); 71630b57cec5SDimitry Andric else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 71640b57cec5SDimitry Andric T = MemPtr->getPointeeType(); 71650b57cec5SDimitry Andric 71665ffd83dbSDimitry Andric auto *FTy = T->castAs<FunctionType>(); 71670b57cec5SDimitry Andric ReturnsRetained = FTy->getExtInfo().getProducesResult(); 71680b57cec5SDimitry Andric 71690b57cec5SDimitry Andric // ActOnStmtExpr arranges things so that StmtExprs of retainable 71700b57cec5SDimitry Andric // type always produce a +1 object. 71710b57cec5SDimitry Andric } else if (isa<StmtExpr>(E)) { 71720b57cec5SDimitry Andric ReturnsRetained = true; 71730b57cec5SDimitry Andric 71740b57cec5SDimitry Andric // We hit this case with the lambda conversion-to-block optimization; 71750b57cec5SDimitry Andric // we don't want any extra casts here. 71760b57cec5SDimitry Andric } else if (isa<CastExpr>(E) && 71770b57cec5SDimitry Andric isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 71780b57cec5SDimitry Andric return E; 71790b57cec5SDimitry Andric 71800b57cec5SDimitry Andric // For message sends and property references, we try to find an 71810b57cec5SDimitry Andric // actual method. FIXME: we should infer retention by selector in 71820b57cec5SDimitry Andric // cases where we don't have an actual method. 71830b57cec5SDimitry Andric } else { 71840b57cec5SDimitry Andric ObjCMethodDecl *D = nullptr; 71850b57cec5SDimitry Andric if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 71860b57cec5SDimitry Andric D = Send->getMethodDecl(); 71870b57cec5SDimitry Andric } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 71880b57cec5SDimitry Andric D = BoxedExpr->getBoxingMethod(); 71890b57cec5SDimitry Andric } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 71900b57cec5SDimitry Andric // Don't do reclaims if we're using the zero-element array 71910b57cec5SDimitry Andric // constant. 71920b57cec5SDimitry Andric if (ArrayLit->getNumElements() == 0 && 71930b57cec5SDimitry Andric Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 71940b57cec5SDimitry Andric return E; 71950b57cec5SDimitry Andric 71960b57cec5SDimitry Andric D = ArrayLit->getArrayWithObjectsMethod(); 71970b57cec5SDimitry Andric } else if (ObjCDictionaryLiteral *DictLit 71980b57cec5SDimitry Andric = dyn_cast<ObjCDictionaryLiteral>(E)) { 71990b57cec5SDimitry Andric // Don't do reclaims if we're using the zero-element dictionary 72000b57cec5SDimitry Andric // constant. 72010b57cec5SDimitry Andric if (DictLit->getNumElements() == 0 && 72020b57cec5SDimitry Andric Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 72030b57cec5SDimitry Andric return E; 72040b57cec5SDimitry Andric 72050b57cec5SDimitry Andric D = DictLit->getDictWithObjectsMethod(); 72060b57cec5SDimitry Andric } 72070b57cec5SDimitry Andric 72080b57cec5SDimitry Andric ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 72090b57cec5SDimitry Andric 72100b57cec5SDimitry Andric // Don't do reclaims on performSelector calls; despite their 72110b57cec5SDimitry Andric // return type, the invoked method doesn't necessarily actually 72120b57cec5SDimitry Andric // return an object. 72130b57cec5SDimitry Andric if (!ReturnsRetained && 72140b57cec5SDimitry Andric D && D->getMethodFamily() == OMF_performSelector) 72150b57cec5SDimitry Andric return E; 72160b57cec5SDimitry Andric } 72170b57cec5SDimitry Andric 72180b57cec5SDimitry Andric // Don't reclaim an object of Class type. 72190b57cec5SDimitry Andric if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 72200b57cec5SDimitry Andric return E; 72210b57cec5SDimitry Andric 72220b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 72230b57cec5SDimitry Andric 72240b57cec5SDimitry Andric CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 72250b57cec5SDimitry Andric : CK_ARCReclaimReturnedObject); 72260b57cec5SDimitry Andric return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, 7227fe6060f1SDimitry Andric VK_PRValue, FPOptionsOverride()); 72280b57cec5SDimitry Andric } 72290b57cec5SDimitry Andric 72305ffd83dbSDimitry Andric if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 72315ffd83dbSDimitry Andric Cleanup.setExprNeedsCleanups(true); 72325ffd83dbSDimitry Andric 72330b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 72340b57cec5SDimitry Andric return E; 72350b57cec5SDimitry Andric 72360b57cec5SDimitry Andric // Search for the base element type (cf. ASTContext::getBaseElementType) with 72370b57cec5SDimitry Andric // a fast path for the common case that the type is directly a RecordType. 72380b57cec5SDimitry Andric const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 72390b57cec5SDimitry Andric const RecordType *RT = nullptr; 72400b57cec5SDimitry Andric while (!RT) { 72410b57cec5SDimitry Andric switch (T->getTypeClass()) { 72420b57cec5SDimitry Andric case Type::Record: 72430b57cec5SDimitry Andric RT = cast<RecordType>(T); 72440b57cec5SDimitry Andric break; 72450b57cec5SDimitry Andric case Type::ConstantArray: 72460b57cec5SDimitry Andric case Type::IncompleteArray: 72470b57cec5SDimitry Andric case Type::VariableArray: 72480b57cec5SDimitry Andric case Type::DependentSizedArray: 72490b57cec5SDimitry Andric T = cast<ArrayType>(T)->getElementType().getTypePtr(); 72500b57cec5SDimitry Andric break; 72510b57cec5SDimitry Andric default: 72520b57cec5SDimitry Andric return E; 72530b57cec5SDimitry Andric } 72540b57cec5SDimitry Andric } 72550b57cec5SDimitry Andric 72560b57cec5SDimitry Andric // That should be enough to guarantee that this type is complete, if we're 72570b57cec5SDimitry Andric // not processing a decltype expression. 72580b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 72590b57cec5SDimitry Andric if (RD->isInvalidDecl() || RD->isDependentContext()) 72600b57cec5SDimitry Andric return E; 72610b57cec5SDimitry Andric 72620b57cec5SDimitry Andric bool IsDecltype = ExprEvalContexts.back().ExprContext == 72630b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Decltype; 72640b57cec5SDimitry Andric CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); 72650b57cec5SDimitry Andric 72660b57cec5SDimitry Andric if (Destructor) { 72670b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), Destructor); 72680b57cec5SDimitry Andric CheckDestructorAccess(E->getExprLoc(), Destructor, 72690b57cec5SDimitry Andric PDiag(diag::err_access_dtor_temp) 72700b57cec5SDimitry Andric << E->getType()); 72710b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 72720b57cec5SDimitry Andric return ExprError(); 72730b57cec5SDimitry Andric 72740b57cec5SDimitry Andric // If destructor is trivial, we can avoid the extra copy. 72750b57cec5SDimitry Andric if (Destructor->isTrivial()) 72760b57cec5SDimitry Andric return E; 72770b57cec5SDimitry Andric 72780b57cec5SDimitry Andric // We need a cleanup, but we don't need to remember the temporary. 72790b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 72800b57cec5SDimitry Andric } 72810b57cec5SDimitry Andric 72820b57cec5SDimitry Andric CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 72830b57cec5SDimitry Andric CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 72840b57cec5SDimitry Andric 72850b57cec5SDimitry Andric if (IsDecltype) 72860b57cec5SDimitry Andric ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 72870b57cec5SDimitry Andric 72880b57cec5SDimitry Andric return Bind; 72890b57cec5SDimitry Andric } 72900b57cec5SDimitry Andric 72910b57cec5SDimitry Andric ExprResult 72920b57cec5SDimitry Andric Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 72930b57cec5SDimitry Andric if (SubExpr.isInvalid()) 72940b57cec5SDimitry Andric return ExprError(); 72950b57cec5SDimitry Andric 72960b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(SubExpr.get()); 72970b57cec5SDimitry Andric } 72980b57cec5SDimitry Andric 72990b57cec5SDimitry Andric Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 73000b57cec5SDimitry Andric assert(SubExpr && "subexpression can't be null!"); 73010b57cec5SDimitry Andric 73020b57cec5SDimitry Andric CleanupVarDeclMarking(); 73030b57cec5SDimitry Andric 73040b57cec5SDimitry Andric unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 73050b57cec5SDimitry Andric assert(ExprCleanupObjects.size() >= FirstCleanup); 73060b57cec5SDimitry Andric assert(Cleanup.exprNeedsCleanups() || 73070b57cec5SDimitry Andric ExprCleanupObjects.size() == FirstCleanup); 73080b57cec5SDimitry Andric if (!Cleanup.exprNeedsCleanups()) 73090b57cec5SDimitry Andric return SubExpr; 73100b57cec5SDimitry Andric 73110b57cec5SDimitry Andric auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 73120b57cec5SDimitry Andric ExprCleanupObjects.size() - FirstCleanup); 73130b57cec5SDimitry Andric 73140b57cec5SDimitry Andric auto *E = ExprWithCleanups::Create( 73150b57cec5SDimitry Andric Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); 73160b57cec5SDimitry Andric DiscardCleanupsInEvaluationContext(); 73170b57cec5SDimitry Andric 73180b57cec5SDimitry Andric return E; 73190b57cec5SDimitry Andric } 73200b57cec5SDimitry Andric 73210b57cec5SDimitry Andric Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 73220b57cec5SDimitry Andric assert(SubStmt && "sub-statement can't be null!"); 73230b57cec5SDimitry Andric 73240b57cec5SDimitry Andric CleanupVarDeclMarking(); 73250b57cec5SDimitry Andric 73260b57cec5SDimitry Andric if (!Cleanup.exprNeedsCleanups()) 73270b57cec5SDimitry Andric return SubStmt; 73280b57cec5SDimitry Andric 73290b57cec5SDimitry Andric // FIXME: In order to attach the temporaries, wrap the statement into 73300b57cec5SDimitry Andric // a StmtExpr; currently this is only used for asm statements. 73310b57cec5SDimitry Andric // This is hacky, either create a new CXXStmtWithTemporaries statement or 73320b57cec5SDimitry Andric // a new AsmStmtWithTemporaries. 733381ad6265SDimitry Andric CompoundStmt *CompStmt = 733481ad6265SDimitry Andric CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(), 733581ad6265SDimitry Andric SourceLocation(), SourceLocation()); 73368c27c554SDimitry Andric Expr *E = new (Context) 73378c27c554SDimitry Andric StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), 7338cd675bb6SDimitry Andric /*FIXME TemplateDepth=*/0); 73390b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(E); 73400b57cec5SDimitry Andric } 73410b57cec5SDimitry Andric 73420b57cec5SDimitry Andric /// Process the expression contained within a decltype. For such expressions, 73430b57cec5SDimitry Andric /// certain semantic checks on temporaries are delayed until this point, and 73440b57cec5SDimitry Andric /// are omitted for the 'topmost' call in the decltype expression. If the 73450b57cec5SDimitry Andric /// topmost call bound a temporary, strip that temporary off the expression. 73460b57cec5SDimitry Andric ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 73470b57cec5SDimitry Andric assert(ExprEvalContexts.back().ExprContext == 73480b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Decltype && 73490b57cec5SDimitry Andric "not in a decltype expression"); 73500b57cec5SDimitry Andric 73510b57cec5SDimitry Andric ExprResult Result = CheckPlaceholderExpr(E); 73520b57cec5SDimitry Andric if (Result.isInvalid()) 73530b57cec5SDimitry Andric return ExprError(); 73540b57cec5SDimitry Andric E = Result.get(); 73550b57cec5SDimitry Andric 73560b57cec5SDimitry Andric // C++11 [expr.call]p11: 73570b57cec5SDimitry Andric // If a function call is a prvalue of object type, 73580b57cec5SDimitry Andric // -- if the function call is either 73590b57cec5SDimitry Andric // -- the operand of a decltype-specifier, or 73600b57cec5SDimitry Andric // -- the right operand of a comma operator that is the operand of a 73610b57cec5SDimitry Andric // decltype-specifier, 73620b57cec5SDimitry Andric // a temporary object is not introduced for the prvalue. 73630b57cec5SDimitry Andric 73640b57cec5SDimitry Andric // Recursively rebuild ParenExprs and comma expressions to strip out the 73650b57cec5SDimitry Andric // outermost CXXBindTemporaryExpr, if any. 73660b57cec5SDimitry Andric if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 73670b57cec5SDimitry Andric ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 73680b57cec5SDimitry Andric if (SubExpr.isInvalid()) 73690b57cec5SDimitry Andric return ExprError(); 73700b57cec5SDimitry Andric if (SubExpr.get() == PE->getSubExpr()) 73710b57cec5SDimitry Andric return E; 73720b57cec5SDimitry Andric return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 73730b57cec5SDimitry Andric } 73740b57cec5SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 73750b57cec5SDimitry Andric if (BO->getOpcode() == BO_Comma) { 73760b57cec5SDimitry Andric ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 73770b57cec5SDimitry Andric if (RHS.isInvalid()) 73780b57cec5SDimitry Andric return ExprError(); 73790b57cec5SDimitry Andric if (RHS.get() == BO->getRHS()) 73800b57cec5SDimitry Andric return E; 73815ffd83dbSDimitry Andric return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma, 73825ffd83dbSDimitry Andric BO->getType(), BO->getValueKind(), 73835ffd83dbSDimitry Andric BO->getObjectKind(), BO->getOperatorLoc(), 73845ffd83dbSDimitry Andric BO->getFPFeatures(getLangOpts())); 73850b57cec5SDimitry Andric } 73860b57cec5SDimitry Andric } 73870b57cec5SDimitry Andric 73880b57cec5SDimitry Andric CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 73890b57cec5SDimitry Andric CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) 73900b57cec5SDimitry Andric : nullptr; 73910b57cec5SDimitry Andric if (TopCall) 73920b57cec5SDimitry Andric E = TopCall; 73930b57cec5SDimitry Andric else 73940b57cec5SDimitry Andric TopBind = nullptr; 73950b57cec5SDimitry Andric 73960b57cec5SDimitry Andric // Disable the special decltype handling now. 73970b57cec5SDimitry Andric ExprEvalContexts.back().ExprContext = 73980b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Other; 73990b57cec5SDimitry Andric 7400a7dea167SDimitry Andric Result = CheckUnevaluatedOperand(E); 7401a7dea167SDimitry Andric if (Result.isInvalid()) 7402a7dea167SDimitry Andric return ExprError(); 7403a7dea167SDimitry Andric E = Result.get(); 7404a7dea167SDimitry Andric 74050b57cec5SDimitry Andric // In MS mode, don't perform any extra checking of call return types within a 74060b57cec5SDimitry Andric // decltype expression. 74070b57cec5SDimitry Andric if (getLangOpts().MSVCCompat) 74080b57cec5SDimitry Andric return E; 74090b57cec5SDimitry Andric 74100b57cec5SDimitry Andric // Perform the semantic checks we delayed until this point. 74110b57cec5SDimitry Andric for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); 74120b57cec5SDimitry Andric I != N; ++I) { 74130b57cec5SDimitry Andric CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; 74140b57cec5SDimitry Andric if (Call == TopCall) 74150b57cec5SDimitry Andric continue; 74160b57cec5SDimitry Andric 74170b57cec5SDimitry Andric if (CheckCallReturnType(Call->getCallReturnType(Context), 74180b57cec5SDimitry Andric Call->getBeginLoc(), Call, Call->getDirectCallee())) 74190b57cec5SDimitry Andric return ExprError(); 74200b57cec5SDimitry Andric } 74210b57cec5SDimitry Andric 74220b57cec5SDimitry Andric // Now all relevant types are complete, check the destructors are accessible 74230b57cec5SDimitry Andric // and non-deleted, and annotate them on the temporaries. 74240b57cec5SDimitry Andric for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); 74250b57cec5SDimitry Andric I != N; ++I) { 74260b57cec5SDimitry Andric CXXBindTemporaryExpr *Bind = 74270b57cec5SDimitry Andric ExprEvalContexts.back().DelayedDecltypeBinds[I]; 74280b57cec5SDimitry Andric if (Bind == TopBind) 74290b57cec5SDimitry Andric continue; 74300b57cec5SDimitry Andric 74310b57cec5SDimitry Andric CXXTemporary *Temp = Bind->getTemporary(); 74320b57cec5SDimitry Andric 74330b57cec5SDimitry Andric CXXRecordDecl *RD = 74340b57cec5SDimitry Andric Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 74350b57cec5SDimitry Andric CXXDestructorDecl *Destructor = LookupDestructor(RD); 74360b57cec5SDimitry Andric Temp->setDestructor(Destructor); 74370b57cec5SDimitry Andric 74380b57cec5SDimitry Andric MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 74390b57cec5SDimitry Andric CheckDestructorAccess(Bind->getExprLoc(), Destructor, 74400b57cec5SDimitry Andric PDiag(diag::err_access_dtor_temp) 74410b57cec5SDimitry Andric << Bind->getType()); 74420b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) 74430b57cec5SDimitry Andric return ExprError(); 74440b57cec5SDimitry Andric 74450b57cec5SDimitry Andric // We need a cleanup, but we don't need to remember the temporary. 74460b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 74470b57cec5SDimitry Andric } 74480b57cec5SDimitry Andric 74490b57cec5SDimitry Andric // Possibly strip off the top CXXBindTemporaryExpr. 74500b57cec5SDimitry Andric return E; 74510b57cec5SDimitry Andric } 74520b57cec5SDimitry Andric 74530b57cec5SDimitry Andric /// Note a set of 'operator->' functions that were used for a member access. 74540b57cec5SDimitry Andric static void noteOperatorArrows(Sema &S, 74550b57cec5SDimitry Andric ArrayRef<FunctionDecl *> OperatorArrows) { 74560b57cec5SDimitry Andric unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; 74570b57cec5SDimitry Andric // FIXME: Make this configurable? 74580b57cec5SDimitry Andric unsigned Limit = 9; 74590b57cec5SDimitry Andric if (OperatorArrows.size() > Limit) { 74600b57cec5SDimitry Andric // Produce Limit-1 normal notes and one 'skipping' note. 74610b57cec5SDimitry Andric SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; 74620b57cec5SDimitry Andric SkipCount = OperatorArrows.size() - (Limit - 1); 74630b57cec5SDimitry Andric } 74640b57cec5SDimitry Andric 74650b57cec5SDimitry Andric for (unsigned I = 0; I < OperatorArrows.size(); /**/) { 74660b57cec5SDimitry Andric if (I == SkipStart) { 74670b57cec5SDimitry Andric S.Diag(OperatorArrows[I]->getLocation(), 74680b57cec5SDimitry Andric diag::note_operator_arrows_suppressed) 74690b57cec5SDimitry Andric << SkipCount; 74700b57cec5SDimitry Andric I += SkipCount; 74710b57cec5SDimitry Andric } else { 74720b57cec5SDimitry Andric S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) 74730b57cec5SDimitry Andric << OperatorArrows[I]->getCallResultType(); 74740b57cec5SDimitry Andric ++I; 74750b57cec5SDimitry Andric } 74760b57cec5SDimitry Andric } 74770b57cec5SDimitry Andric } 74780b57cec5SDimitry Andric 74790b57cec5SDimitry Andric ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, 74800b57cec5SDimitry Andric SourceLocation OpLoc, 74810b57cec5SDimitry Andric tok::TokenKind OpKind, 74820b57cec5SDimitry Andric ParsedType &ObjectType, 74830b57cec5SDimitry Andric bool &MayBePseudoDestructor) { 74840b57cec5SDimitry Andric // Since this might be a postfix expression, get rid of ParenListExprs. 74850b57cec5SDimitry Andric ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 74860b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 74870b57cec5SDimitry Andric Base = Result.get(); 74880b57cec5SDimitry Andric 74890b57cec5SDimitry Andric Result = CheckPlaceholderExpr(Base); 74900b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 74910b57cec5SDimitry Andric Base = Result.get(); 74920b57cec5SDimitry Andric 74930b57cec5SDimitry Andric QualType BaseType = Base->getType(); 74940b57cec5SDimitry Andric MayBePseudoDestructor = false; 74950b57cec5SDimitry Andric if (BaseType->isDependentType()) { 74960b57cec5SDimitry Andric // If we have a pointer to a dependent type and are using the -> operator, 74970b57cec5SDimitry Andric // the object type is the type that the pointer points to. We might still 74980b57cec5SDimitry Andric // have enough information about that type to do something useful. 74990b57cec5SDimitry Andric if (OpKind == tok::arrow) 75000b57cec5SDimitry Andric if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 75010b57cec5SDimitry Andric BaseType = Ptr->getPointeeType(); 75020b57cec5SDimitry Andric 75030b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 75040b57cec5SDimitry Andric MayBePseudoDestructor = true; 75050b57cec5SDimitry Andric return Base; 75060b57cec5SDimitry Andric } 75070b57cec5SDimitry Andric 75080b57cec5SDimitry Andric // C++ [over.match.oper]p8: 75090b57cec5SDimitry Andric // [...] When operator->returns, the operator-> is applied to the value 75100b57cec5SDimitry Andric // returned, with the original second operand. 75110b57cec5SDimitry Andric if (OpKind == tok::arrow) { 75120b57cec5SDimitry Andric QualType StartingType = BaseType; 75130b57cec5SDimitry Andric bool NoArrowOperatorFound = false; 75140b57cec5SDimitry Andric bool FirstIteration = true; 75150b57cec5SDimitry Andric FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); 75160b57cec5SDimitry Andric // The set of types we've considered so far. 75170b57cec5SDimitry Andric llvm::SmallPtrSet<CanQualType,8> CTypes; 75180b57cec5SDimitry Andric SmallVector<FunctionDecl*, 8> OperatorArrows; 75190b57cec5SDimitry Andric CTypes.insert(Context.getCanonicalType(BaseType)); 75200b57cec5SDimitry Andric 75210b57cec5SDimitry Andric while (BaseType->isRecordType()) { 75220b57cec5SDimitry Andric if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { 75230b57cec5SDimitry Andric Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) 75240b57cec5SDimitry Andric << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); 75250b57cec5SDimitry Andric noteOperatorArrows(*this, OperatorArrows); 75260b57cec5SDimitry Andric Diag(OpLoc, diag::note_operator_arrow_depth) 75270b57cec5SDimitry Andric << getLangOpts().ArrowDepth; 75280b57cec5SDimitry Andric return ExprError(); 75290b57cec5SDimitry Andric } 75300b57cec5SDimitry Andric 75310b57cec5SDimitry Andric Result = BuildOverloadedArrowExpr( 75320b57cec5SDimitry Andric S, Base, OpLoc, 75330b57cec5SDimitry Andric // When in a template specialization and on the first loop iteration, 75340b57cec5SDimitry Andric // potentially give the default diagnostic (with the fixit in a 75350b57cec5SDimitry Andric // separate note) instead of having the error reported back to here 75360b57cec5SDimitry Andric // and giving a diagnostic with a fixit attached to the error itself. 75370b57cec5SDimitry Andric (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) 75380b57cec5SDimitry Andric ? nullptr 75390b57cec5SDimitry Andric : &NoArrowOperatorFound); 75400b57cec5SDimitry Andric if (Result.isInvalid()) { 75410b57cec5SDimitry Andric if (NoArrowOperatorFound) { 75420b57cec5SDimitry Andric if (FirstIteration) { 75430b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 75440b57cec5SDimitry Andric << BaseType << 1 << Base->getSourceRange() 75450b57cec5SDimitry Andric << FixItHint::CreateReplacement(OpLoc, "."); 75460b57cec5SDimitry Andric OpKind = tok::period; 75470b57cec5SDimitry Andric break; 75480b57cec5SDimitry Andric } 75490b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 75500b57cec5SDimitry Andric << BaseType << Base->getSourceRange(); 75510b57cec5SDimitry Andric CallExpr *CE = dyn_cast<CallExpr>(Base); 75520b57cec5SDimitry Andric if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { 75530b57cec5SDimitry Andric Diag(CD->getBeginLoc(), 75540b57cec5SDimitry Andric diag::note_member_reference_arrow_from_operator_arrow); 75550b57cec5SDimitry Andric } 75560b57cec5SDimitry Andric } 75570b57cec5SDimitry Andric return ExprError(); 75580b57cec5SDimitry Andric } 75590b57cec5SDimitry Andric Base = Result.get(); 75600b57cec5SDimitry Andric if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 75610b57cec5SDimitry Andric OperatorArrows.push_back(OpCall->getDirectCallee()); 75620b57cec5SDimitry Andric BaseType = Base->getType(); 75630b57cec5SDimitry Andric CanQualType CBaseType = Context.getCanonicalType(BaseType); 75640b57cec5SDimitry Andric if (!CTypes.insert(CBaseType).second) { 75650b57cec5SDimitry Andric Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; 75660b57cec5SDimitry Andric noteOperatorArrows(*this, OperatorArrows); 75670b57cec5SDimitry Andric return ExprError(); 75680b57cec5SDimitry Andric } 75690b57cec5SDimitry Andric FirstIteration = false; 75700b57cec5SDimitry Andric } 75710b57cec5SDimitry Andric 75720b57cec5SDimitry Andric if (OpKind == tok::arrow) { 75730b57cec5SDimitry Andric if (BaseType->isPointerType()) 75740b57cec5SDimitry Andric BaseType = BaseType->getPointeeType(); 75750b57cec5SDimitry Andric else if (auto *AT = Context.getAsArrayType(BaseType)) 75760b57cec5SDimitry Andric BaseType = AT->getElementType(); 75770b57cec5SDimitry Andric } 75780b57cec5SDimitry Andric } 75790b57cec5SDimitry Andric 75800b57cec5SDimitry Andric // Objective-C properties allow "." access on Objective-C pointer types, 75810b57cec5SDimitry Andric // so adjust the base type to the object type itself. 75820b57cec5SDimitry Andric if (BaseType->isObjCObjectPointerType()) 75830b57cec5SDimitry Andric BaseType = BaseType->getPointeeType(); 75840b57cec5SDimitry Andric 75850b57cec5SDimitry Andric // C++ [basic.lookup.classref]p2: 75860b57cec5SDimitry Andric // [...] If the type of the object expression is of pointer to scalar 75870b57cec5SDimitry Andric // type, the unqualified-id is looked up in the context of the complete 75880b57cec5SDimitry Andric // postfix-expression. 75890b57cec5SDimitry Andric // 75900b57cec5SDimitry Andric // This also indicates that we could be parsing a pseudo-destructor-name. 75910b57cec5SDimitry Andric // Note that Objective-C class and object types can be pseudo-destructor 75920b57cec5SDimitry Andric // expressions or normal member (ivar or property) access expressions, and 75930b57cec5SDimitry Andric // it's legal for the type to be incomplete if this is a pseudo-destructor 75940b57cec5SDimitry Andric // call. We'll do more incomplete-type checks later in the lookup process, 75950b57cec5SDimitry Andric // so just skip this check for ObjC types. 75960b57cec5SDimitry Andric if (!BaseType->isRecordType()) { 75970b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 75980b57cec5SDimitry Andric MayBePseudoDestructor = true; 75990b57cec5SDimitry Andric return Base; 76000b57cec5SDimitry Andric } 76010b57cec5SDimitry Andric 76020b57cec5SDimitry Andric // The object type must be complete (or dependent), or 76030b57cec5SDimitry Andric // C++11 [expr.prim.general]p3: 76040b57cec5SDimitry Andric // Unlike the object expression in other contexts, *this is not required to 76050b57cec5SDimitry Andric // be of complete type for purposes of class member access (5.2.5) outside 76060b57cec5SDimitry Andric // the member function body. 76070b57cec5SDimitry Andric if (!BaseType->isDependentType() && 76080b57cec5SDimitry Andric !isThisOutsideMemberFunctionBody(BaseType) && 760904eeddc0SDimitry Andric RequireCompleteType(OpLoc, BaseType, 761004eeddc0SDimitry Andric diag::err_incomplete_member_access)) { 761104eeddc0SDimitry Andric return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base}); 761204eeddc0SDimitry Andric } 76130b57cec5SDimitry Andric 76140b57cec5SDimitry Andric // C++ [basic.lookup.classref]p2: 76150b57cec5SDimitry Andric // If the id-expression in a class member access (5.2.5) is an 76160b57cec5SDimitry Andric // unqualified-id, and the type of the object expression is of a class 76170b57cec5SDimitry Andric // type C (or of pointer to a class type C), the unqualified-id is looked 76180b57cec5SDimitry Andric // up in the scope of class C. [...] 76190b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 76200b57cec5SDimitry Andric return Base; 76210b57cec5SDimitry Andric } 76220b57cec5SDimitry Andric 76230b57cec5SDimitry Andric static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, 76240b57cec5SDimitry Andric tok::TokenKind &OpKind, SourceLocation OpLoc) { 76250b57cec5SDimitry Andric if (Base->hasPlaceholderType()) { 76260b57cec5SDimitry Andric ExprResult result = S.CheckPlaceholderExpr(Base); 76270b57cec5SDimitry Andric if (result.isInvalid()) return true; 76280b57cec5SDimitry Andric Base = result.get(); 76290b57cec5SDimitry Andric } 76300b57cec5SDimitry Andric ObjectType = Base->getType(); 76310b57cec5SDimitry Andric 76320b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 76330b57cec5SDimitry Andric // The left-hand side of the dot operator shall be of scalar type. The 76340b57cec5SDimitry Andric // left-hand side of the arrow operator shall be of pointer to scalar type. 76350b57cec5SDimitry Andric // This scalar type is the object type. 76360b57cec5SDimitry Andric // Note that this is rather different from the normal handling for the 76370b57cec5SDimitry Andric // arrow operator. 76380b57cec5SDimitry Andric if (OpKind == tok::arrow) { 7639e8d8bef9SDimitry Andric // The operator requires a prvalue, so perform lvalue conversions. 7640e8d8bef9SDimitry Andric // Only do this if we might plausibly end with a pointer, as otherwise 7641e8d8bef9SDimitry Andric // this was likely to be intended to be a '.'. 7642e8d8bef9SDimitry Andric if (ObjectType->isPointerType() || ObjectType->isArrayType() || 7643e8d8bef9SDimitry Andric ObjectType->isFunctionType()) { 7644e8d8bef9SDimitry Andric ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base); 7645e8d8bef9SDimitry Andric if (BaseResult.isInvalid()) 7646e8d8bef9SDimitry Andric return true; 7647e8d8bef9SDimitry Andric Base = BaseResult.get(); 7648e8d8bef9SDimitry Andric ObjectType = Base->getType(); 7649e8d8bef9SDimitry Andric } 7650e8d8bef9SDimitry Andric 76510b57cec5SDimitry Andric if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 76520b57cec5SDimitry Andric ObjectType = Ptr->getPointeeType(); 76530b57cec5SDimitry Andric } else if (!Base->isTypeDependent()) { 76540b57cec5SDimitry Andric // The user wrote "p->" when they probably meant "p."; fix it. 76550b57cec5SDimitry Andric S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 76560b57cec5SDimitry Andric << ObjectType << true 76570b57cec5SDimitry Andric << FixItHint::CreateReplacement(OpLoc, "."); 76580b57cec5SDimitry Andric if (S.isSFINAEContext()) 76590b57cec5SDimitry Andric return true; 76600b57cec5SDimitry Andric 76610b57cec5SDimitry Andric OpKind = tok::period; 76620b57cec5SDimitry Andric } 76630b57cec5SDimitry Andric } 76640b57cec5SDimitry Andric 76650b57cec5SDimitry Andric return false; 76660b57cec5SDimitry Andric } 76670b57cec5SDimitry Andric 76680b57cec5SDimitry Andric /// Check if it's ok to try and recover dot pseudo destructor calls on 76690b57cec5SDimitry Andric /// pointer objects. 76700b57cec5SDimitry Andric static bool 76710b57cec5SDimitry Andric canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, 76720b57cec5SDimitry Andric QualType DestructedType) { 76730b57cec5SDimitry Andric // If this is a record type, check if its destructor is callable. 76740b57cec5SDimitry Andric if (auto *RD = DestructedType->getAsCXXRecordDecl()) { 76750b57cec5SDimitry Andric if (RD->hasDefinition()) 76760b57cec5SDimitry Andric if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) 76770b57cec5SDimitry Andric return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); 76780b57cec5SDimitry Andric return false; 76790b57cec5SDimitry Andric } 76800b57cec5SDimitry Andric 76810b57cec5SDimitry Andric // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. 76820b57cec5SDimitry Andric return DestructedType->isDependentType() || DestructedType->isScalarType() || 76830b57cec5SDimitry Andric DestructedType->isVectorType(); 76840b57cec5SDimitry Andric } 76850b57cec5SDimitry Andric 76860b57cec5SDimitry Andric ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 76870b57cec5SDimitry Andric SourceLocation OpLoc, 76880b57cec5SDimitry Andric tok::TokenKind OpKind, 76890b57cec5SDimitry Andric const CXXScopeSpec &SS, 76900b57cec5SDimitry Andric TypeSourceInfo *ScopeTypeInfo, 76910b57cec5SDimitry Andric SourceLocation CCLoc, 76920b57cec5SDimitry Andric SourceLocation TildeLoc, 76930b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed) { 76940b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 76950b57cec5SDimitry Andric 76960b57cec5SDimitry Andric QualType ObjectType; 76970b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 76980b57cec5SDimitry Andric return ExprError(); 76990b57cec5SDimitry Andric 77000b57cec5SDimitry Andric if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 77010b57cec5SDimitry Andric !ObjectType->isVectorType()) { 77020b57cec5SDimitry Andric if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) 77030b57cec5SDimitry Andric Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 77040b57cec5SDimitry Andric else { 77050b57cec5SDimitry Andric Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 77060b57cec5SDimitry Andric << ObjectType << Base->getSourceRange(); 77070b57cec5SDimitry Andric return ExprError(); 77080b57cec5SDimitry Andric } 77090b57cec5SDimitry Andric } 77100b57cec5SDimitry Andric 77110b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 77120b57cec5SDimitry Andric // [...] The cv-unqualified versions of the object type and of the type 77130b57cec5SDimitry Andric // designated by the pseudo-destructor-name shall be the same type. 77140b57cec5SDimitry Andric if (DestructedTypeInfo) { 77150b57cec5SDimitry Andric QualType DestructedType = DestructedTypeInfo->getType(); 77160b57cec5SDimitry Andric SourceLocation DestructedTypeStart 77170b57cec5SDimitry Andric = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 77180b57cec5SDimitry Andric if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 77190b57cec5SDimitry Andric if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 77200b57cec5SDimitry Andric // Detect dot pseudo destructor calls on pointer objects, e.g.: 77210b57cec5SDimitry Andric // Foo *foo; 77220b57cec5SDimitry Andric // foo.~Foo(); 77230b57cec5SDimitry Andric if (OpKind == tok::period && ObjectType->isPointerType() && 77240b57cec5SDimitry Andric Context.hasSameUnqualifiedType(DestructedType, 77250b57cec5SDimitry Andric ObjectType->getPointeeType())) { 77260b57cec5SDimitry Andric auto Diagnostic = 77270b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 77280b57cec5SDimitry Andric << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); 77290b57cec5SDimitry Andric 77300b57cec5SDimitry Andric // Issue a fixit only when the destructor is valid. 77310b57cec5SDimitry Andric if (canRecoverDotPseudoDestructorCallsOnPointerObjects( 77320b57cec5SDimitry Andric *this, DestructedType)) 77330b57cec5SDimitry Andric Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); 77340b57cec5SDimitry Andric 77350b57cec5SDimitry Andric // Recover by setting the object type to the destructed type and the 77360b57cec5SDimitry Andric // operator to '->'. 77370b57cec5SDimitry Andric ObjectType = DestructedType; 77380b57cec5SDimitry Andric OpKind = tok::arrow; 77390b57cec5SDimitry Andric } else { 77400b57cec5SDimitry Andric Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 77410b57cec5SDimitry Andric << ObjectType << DestructedType << Base->getSourceRange() 77420b57cec5SDimitry Andric << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 77430b57cec5SDimitry Andric 77440b57cec5SDimitry Andric // Recover by setting the destructed type to the object type. 77450b57cec5SDimitry Andric DestructedType = ObjectType; 77460b57cec5SDimitry Andric DestructedTypeInfo = 77470b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); 77480b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 77490b57cec5SDimitry Andric } 77500b57cec5SDimitry Andric } else if (DestructedType.getObjCLifetime() != 77510b57cec5SDimitry Andric ObjectType.getObjCLifetime()) { 77520b57cec5SDimitry Andric 77530b57cec5SDimitry Andric if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 77540b57cec5SDimitry Andric // Okay: just pretend that the user provided the correctly-qualified 77550b57cec5SDimitry Andric // type. 77560b57cec5SDimitry Andric } else { 77570b57cec5SDimitry Andric Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 77580b57cec5SDimitry Andric << ObjectType << DestructedType << Base->getSourceRange() 77590b57cec5SDimitry Andric << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 77600b57cec5SDimitry Andric } 77610b57cec5SDimitry Andric 77620b57cec5SDimitry Andric // Recover by setting the destructed type to the object type. 77630b57cec5SDimitry Andric DestructedType = ObjectType; 77640b57cec5SDimitry Andric DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 77650b57cec5SDimitry Andric DestructedTypeStart); 77660b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 77670b57cec5SDimitry Andric } 77680b57cec5SDimitry Andric } 77690b57cec5SDimitry Andric } 77700b57cec5SDimitry Andric 77710b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 77720b57cec5SDimitry Andric // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 77730b57cec5SDimitry Andric // form 77740b57cec5SDimitry Andric // 77750b57cec5SDimitry Andric // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 77760b57cec5SDimitry Andric // 77770b57cec5SDimitry Andric // shall designate the same scalar type. 77780b57cec5SDimitry Andric if (ScopeTypeInfo) { 77790b57cec5SDimitry Andric QualType ScopeType = ScopeTypeInfo->getType(); 77800b57cec5SDimitry Andric if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 77810b57cec5SDimitry Andric !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 77820b57cec5SDimitry Andric 77830b57cec5SDimitry Andric Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 77840b57cec5SDimitry Andric diag::err_pseudo_dtor_type_mismatch) 77850b57cec5SDimitry Andric << ObjectType << ScopeType << Base->getSourceRange() 77860b57cec5SDimitry Andric << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 77870b57cec5SDimitry Andric 77880b57cec5SDimitry Andric ScopeType = QualType(); 77890b57cec5SDimitry Andric ScopeTypeInfo = nullptr; 77900b57cec5SDimitry Andric } 77910b57cec5SDimitry Andric } 77920b57cec5SDimitry Andric 77930b57cec5SDimitry Andric Expr *Result 77940b57cec5SDimitry Andric = new (Context) CXXPseudoDestructorExpr(Context, Base, 77950b57cec5SDimitry Andric OpKind == tok::arrow, OpLoc, 77960b57cec5SDimitry Andric SS.getWithLocInContext(Context), 77970b57cec5SDimitry Andric ScopeTypeInfo, 77980b57cec5SDimitry Andric CCLoc, 77990b57cec5SDimitry Andric TildeLoc, 78000b57cec5SDimitry Andric Destructed); 78010b57cec5SDimitry Andric 78020b57cec5SDimitry Andric return Result; 78030b57cec5SDimitry Andric } 78040b57cec5SDimitry Andric 78050b57cec5SDimitry Andric ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 78060b57cec5SDimitry Andric SourceLocation OpLoc, 78070b57cec5SDimitry Andric tok::TokenKind OpKind, 78080b57cec5SDimitry Andric CXXScopeSpec &SS, 78090b57cec5SDimitry Andric UnqualifiedId &FirstTypeName, 78100b57cec5SDimitry Andric SourceLocation CCLoc, 78110b57cec5SDimitry Andric SourceLocation TildeLoc, 78120b57cec5SDimitry Andric UnqualifiedId &SecondTypeName) { 78130b57cec5SDimitry Andric assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 78140b57cec5SDimitry Andric FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 78150b57cec5SDimitry Andric "Invalid first type name in pseudo-destructor"); 78160b57cec5SDimitry Andric assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 78170b57cec5SDimitry Andric SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 78180b57cec5SDimitry Andric "Invalid second type name in pseudo-destructor"); 78190b57cec5SDimitry Andric 78200b57cec5SDimitry Andric QualType ObjectType; 78210b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 78220b57cec5SDimitry Andric return ExprError(); 78230b57cec5SDimitry Andric 78240b57cec5SDimitry Andric // Compute the object type that we should use for name lookup purposes. Only 78250b57cec5SDimitry Andric // record types and dependent types matter. 78260b57cec5SDimitry Andric ParsedType ObjectTypePtrForLookup; 78270b57cec5SDimitry Andric if (!SS.isSet()) { 78280b57cec5SDimitry Andric if (ObjectType->isRecordType()) 78290b57cec5SDimitry Andric ObjectTypePtrForLookup = ParsedType::make(ObjectType); 78300b57cec5SDimitry Andric else if (ObjectType->isDependentType()) 78310b57cec5SDimitry Andric ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 78320b57cec5SDimitry Andric } 78330b57cec5SDimitry Andric 78340b57cec5SDimitry Andric // Convert the name of the type being destructed (following the ~) into a 78350b57cec5SDimitry Andric // type (with source-location information). 78360b57cec5SDimitry Andric QualType DestructedType; 78370b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = nullptr; 78380b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed; 78390b57cec5SDimitry Andric if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 78400b57cec5SDimitry Andric ParsedType T = getTypeName(*SecondTypeName.Identifier, 78410b57cec5SDimitry Andric SecondTypeName.StartLocation, 78420b57cec5SDimitry Andric S, &SS, true, false, ObjectTypePtrForLookup, 78430b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 78440b57cec5SDimitry Andric if (!T && 78450b57cec5SDimitry Andric ((SS.isSet() && !computeDeclContext(SS, false)) || 78460b57cec5SDimitry Andric (!SS.isSet() && ObjectType->isDependentType()))) { 78470b57cec5SDimitry Andric // The name of the type being destroyed is a dependent name, and we 78480b57cec5SDimitry Andric // couldn't find anything useful in scope. Just store the identifier and 78490b57cec5SDimitry Andric // it's location, and we'll perform (qualified) name lookup again at 78500b57cec5SDimitry Andric // template instantiation time. 78510b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 78520b57cec5SDimitry Andric SecondTypeName.StartLocation); 78530b57cec5SDimitry Andric } else if (!T) { 78540b57cec5SDimitry Andric Diag(SecondTypeName.StartLocation, 78550b57cec5SDimitry Andric diag::err_pseudo_dtor_destructor_non_type) 78560b57cec5SDimitry Andric << SecondTypeName.Identifier << ObjectType; 78570b57cec5SDimitry Andric if (isSFINAEContext()) 78580b57cec5SDimitry Andric return ExprError(); 78590b57cec5SDimitry Andric 78600b57cec5SDimitry Andric // Recover by assuming we had the right type all along. 78610b57cec5SDimitry Andric DestructedType = ObjectType; 78620b57cec5SDimitry Andric } else 78630b57cec5SDimitry Andric DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 78640b57cec5SDimitry Andric } else { 78650b57cec5SDimitry Andric // Resolve the template-id to a type. 78660b57cec5SDimitry Andric TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 78670b57cec5SDimitry Andric ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 78680b57cec5SDimitry Andric TemplateId->NumArgs); 78690b57cec5SDimitry Andric TypeResult T = ActOnTemplateIdType(S, 787055e4f9d5SDimitry Andric SS, 78710b57cec5SDimitry Andric TemplateId->TemplateKWLoc, 78720b57cec5SDimitry Andric TemplateId->Template, 78730b57cec5SDimitry Andric TemplateId->Name, 78740b57cec5SDimitry Andric TemplateId->TemplateNameLoc, 78750b57cec5SDimitry Andric TemplateId->LAngleLoc, 78760b57cec5SDimitry Andric TemplateArgsPtr, 78770b57cec5SDimitry Andric TemplateId->RAngleLoc, 78780b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 78790b57cec5SDimitry Andric if (T.isInvalid() || !T.get()) { 78800b57cec5SDimitry Andric // Recover by assuming we had the right type all along. 78810b57cec5SDimitry Andric DestructedType = ObjectType; 78820b57cec5SDimitry Andric } else 78830b57cec5SDimitry Andric DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 78840b57cec5SDimitry Andric } 78850b57cec5SDimitry Andric 78860b57cec5SDimitry Andric // If we've performed some kind of recovery, (re-)build the type source 78870b57cec5SDimitry Andric // information. 78880b57cec5SDimitry Andric if (!DestructedType.isNull()) { 78890b57cec5SDimitry Andric if (!DestructedTypeInfo) 78900b57cec5SDimitry Andric DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 78910b57cec5SDimitry Andric SecondTypeName.StartLocation); 78920b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 78930b57cec5SDimitry Andric } 78940b57cec5SDimitry Andric 78950b57cec5SDimitry Andric // Convert the name of the scope type (the type prior to '::') into a type. 78960b57cec5SDimitry Andric TypeSourceInfo *ScopeTypeInfo = nullptr; 78970b57cec5SDimitry Andric QualType ScopeType; 78980b57cec5SDimitry Andric if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 78990b57cec5SDimitry Andric FirstTypeName.Identifier) { 79000b57cec5SDimitry Andric if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 79010b57cec5SDimitry Andric ParsedType T = getTypeName(*FirstTypeName.Identifier, 79020b57cec5SDimitry Andric FirstTypeName.StartLocation, 79030b57cec5SDimitry Andric S, &SS, true, false, ObjectTypePtrForLookup, 79040b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 79050b57cec5SDimitry Andric if (!T) { 79060b57cec5SDimitry Andric Diag(FirstTypeName.StartLocation, 79070b57cec5SDimitry Andric diag::err_pseudo_dtor_destructor_non_type) 79080b57cec5SDimitry Andric << FirstTypeName.Identifier << ObjectType; 79090b57cec5SDimitry Andric 79100b57cec5SDimitry Andric if (isSFINAEContext()) 79110b57cec5SDimitry Andric return ExprError(); 79120b57cec5SDimitry Andric 79130b57cec5SDimitry Andric // Just drop this type. It's unnecessary anyway. 79140b57cec5SDimitry Andric ScopeType = QualType(); 79150b57cec5SDimitry Andric } else 79160b57cec5SDimitry Andric ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 79170b57cec5SDimitry Andric } else { 79180b57cec5SDimitry Andric // Resolve the template-id to a type. 79190b57cec5SDimitry Andric TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 79200b57cec5SDimitry Andric ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 79210b57cec5SDimitry Andric TemplateId->NumArgs); 79220b57cec5SDimitry Andric TypeResult T = ActOnTemplateIdType(S, 792355e4f9d5SDimitry Andric SS, 79240b57cec5SDimitry Andric TemplateId->TemplateKWLoc, 79250b57cec5SDimitry Andric TemplateId->Template, 79260b57cec5SDimitry Andric TemplateId->Name, 79270b57cec5SDimitry Andric TemplateId->TemplateNameLoc, 79280b57cec5SDimitry Andric TemplateId->LAngleLoc, 79290b57cec5SDimitry Andric TemplateArgsPtr, 79300b57cec5SDimitry Andric TemplateId->RAngleLoc, 79310b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 79320b57cec5SDimitry Andric if (T.isInvalid() || !T.get()) { 79330b57cec5SDimitry Andric // Recover by dropping this type. 79340b57cec5SDimitry Andric ScopeType = QualType(); 79350b57cec5SDimitry Andric } else 79360b57cec5SDimitry Andric ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 79370b57cec5SDimitry Andric } 79380b57cec5SDimitry Andric } 79390b57cec5SDimitry Andric 79400b57cec5SDimitry Andric if (!ScopeType.isNull() && !ScopeTypeInfo) 79410b57cec5SDimitry Andric ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 79420b57cec5SDimitry Andric FirstTypeName.StartLocation); 79430b57cec5SDimitry Andric 79440b57cec5SDimitry Andric 79450b57cec5SDimitry Andric return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 79460b57cec5SDimitry Andric ScopeTypeInfo, CCLoc, TildeLoc, 79470b57cec5SDimitry Andric Destructed); 79480b57cec5SDimitry Andric } 79490b57cec5SDimitry Andric 79500b57cec5SDimitry Andric ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 79510b57cec5SDimitry Andric SourceLocation OpLoc, 79520b57cec5SDimitry Andric tok::TokenKind OpKind, 79530b57cec5SDimitry Andric SourceLocation TildeLoc, 79540b57cec5SDimitry Andric const DeclSpec& DS) { 79550b57cec5SDimitry Andric QualType ObjectType; 79560b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 79570b57cec5SDimitry Andric return ExprError(); 79580b57cec5SDimitry Andric 7959e8d8bef9SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { 7960e8d8bef9SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 7961e8d8bef9SDimitry Andric return true; 7962e8d8bef9SDimitry Andric } 7963e8d8bef9SDimitry Andric 7964349cc55cSDimitry Andric QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false); 79650b57cec5SDimitry Andric 79660b57cec5SDimitry Andric TypeLocBuilder TLB; 79670b57cec5SDimitry Andric DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 796804eeddc0SDimitry Andric DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); 796904eeddc0SDimitry Andric DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 79700b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 79710b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 79720b57cec5SDimitry Andric 79730b57cec5SDimitry Andric return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 79740b57cec5SDimitry Andric nullptr, SourceLocation(), TildeLoc, 79750b57cec5SDimitry Andric Destructed); 79760b57cec5SDimitry Andric } 79770b57cec5SDimitry Andric 79780b57cec5SDimitry Andric ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 79790b57cec5SDimitry Andric CXXConversionDecl *Method, 79800b57cec5SDimitry Andric bool HadMultipleCandidates) { 79810b57cec5SDimitry Andric // Convert the expression to match the conversion function's implicit object 79820b57cec5SDimitry Andric // parameter. 79830b57cec5SDimitry Andric ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 79840b57cec5SDimitry Andric FoundDecl, Method); 79850b57cec5SDimitry Andric if (Exp.isInvalid()) 79860b57cec5SDimitry Andric return true; 79870b57cec5SDimitry Andric 79880b57cec5SDimitry Andric if (Method->getParent()->isLambda() && 79890b57cec5SDimitry Andric Method->getConversionType()->isBlockPointerType()) { 7990a7dea167SDimitry Andric // This is a lambda conversion to block pointer; check if the argument 79910b57cec5SDimitry Andric // was a LambdaExpr. 79920b57cec5SDimitry Andric Expr *SubE = E; 79930b57cec5SDimitry Andric CastExpr *CE = dyn_cast<CastExpr>(SubE); 79940b57cec5SDimitry Andric if (CE && CE->getCastKind() == CK_NoOp) 79950b57cec5SDimitry Andric SubE = CE->getSubExpr(); 79960b57cec5SDimitry Andric SubE = SubE->IgnoreParens(); 79970b57cec5SDimitry Andric if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 79980b57cec5SDimitry Andric SubE = BE->getSubExpr(); 79990b57cec5SDimitry Andric if (isa<LambdaExpr>(SubE)) { 80000b57cec5SDimitry Andric // For the conversion to block pointer on a lambda expression, we 80010b57cec5SDimitry Andric // construct a special BlockLiteral instead; this doesn't really make 80020b57cec5SDimitry Andric // a difference in ARC, but outside of ARC the resulting block literal 80030b57cec5SDimitry Andric // follows the normal lifetime rules for block literals instead of being 80040b57cec5SDimitry Andric // autoreleased. 80050b57cec5SDimitry Andric PushExpressionEvaluationContext( 80060b57cec5SDimitry Andric ExpressionEvaluationContext::PotentiallyEvaluated); 80070b57cec5SDimitry Andric ExprResult BlockExp = BuildBlockForLambdaConversion( 80080b57cec5SDimitry Andric Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); 80090b57cec5SDimitry Andric PopExpressionEvaluationContext(); 80100b57cec5SDimitry Andric 80115ffd83dbSDimitry Andric // FIXME: This note should be produced by a CodeSynthesisContext. 80120b57cec5SDimitry Andric if (BlockExp.isInvalid()) 80130b57cec5SDimitry Andric Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); 80140b57cec5SDimitry Andric return BlockExp; 80150b57cec5SDimitry Andric } 80160b57cec5SDimitry Andric } 80170b57cec5SDimitry Andric 80180b57cec5SDimitry Andric MemberExpr *ME = 80190b57cec5SDimitry Andric BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), 80200b57cec5SDimitry Andric NestedNameSpecifierLoc(), SourceLocation(), Method, 80210b57cec5SDimitry Andric DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), 80220b57cec5SDimitry Andric HadMultipleCandidates, DeclarationNameInfo(), 8023fe6060f1SDimitry Andric Context.BoundMemberTy, VK_PRValue, OK_Ordinary); 80240b57cec5SDimitry Andric 80250b57cec5SDimitry Andric QualType ResultType = Method->getReturnType(); 80260b57cec5SDimitry Andric ExprValueKind VK = Expr::getValueKindForType(ResultType); 80270b57cec5SDimitry Andric ResultType = ResultType.getNonLValueExprType(Context); 80280b57cec5SDimitry Andric 80290b57cec5SDimitry Andric CXXMemberCallExpr *CE = CXXMemberCallExpr::Create( 8030e8d8bef9SDimitry Andric Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(), 8031e8d8bef9SDimitry Andric CurFPFeatureOverrides()); 80320b57cec5SDimitry Andric 80330b57cec5SDimitry Andric if (CheckFunctionCall(Method, CE, 80340b57cec5SDimitry Andric Method->getType()->castAs<FunctionProtoType>())) 80350b57cec5SDimitry Andric return ExprError(); 80360b57cec5SDimitry Andric 8037fe6060f1SDimitry Andric return CheckForImmediateInvocation(CE, CE->getMethodDecl()); 80380b57cec5SDimitry Andric } 80390b57cec5SDimitry Andric 80400b57cec5SDimitry Andric ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 80410b57cec5SDimitry Andric SourceLocation RParen) { 80420b57cec5SDimitry Andric // If the operand is an unresolved lookup expression, the expression is ill- 80430b57cec5SDimitry Andric // formed per [over.over]p1, because overloaded function names cannot be used 80440b57cec5SDimitry Andric // without arguments except in explicit contexts. 80450b57cec5SDimitry Andric ExprResult R = CheckPlaceholderExpr(Operand); 80460b57cec5SDimitry Andric if (R.isInvalid()) 80470b57cec5SDimitry Andric return R; 80480b57cec5SDimitry Andric 8049a7dea167SDimitry Andric R = CheckUnevaluatedOperand(R.get()); 8050a7dea167SDimitry Andric if (R.isInvalid()) 8051a7dea167SDimitry Andric return ExprError(); 8052a7dea167SDimitry Andric 80530b57cec5SDimitry Andric Operand = R.get(); 80540b57cec5SDimitry Andric 8055e8d8bef9SDimitry Andric if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && 8056e8d8bef9SDimitry Andric Operand->HasSideEffects(Context, false)) { 80570b57cec5SDimitry Andric // The expression operand for noexcept is in an unevaluated expression 80580b57cec5SDimitry Andric // context, so side effects could result in unintended consequences. 80590b57cec5SDimitry Andric Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); 80600b57cec5SDimitry Andric } 80610b57cec5SDimitry Andric 80620b57cec5SDimitry Andric CanThrowResult CanThrow = canThrow(Operand); 80630b57cec5SDimitry Andric return new (Context) 80640b57cec5SDimitry Andric CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); 80650b57cec5SDimitry Andric } 80660b57cec5SDimitry Andric 80670b57cec5SDimitry Andric ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 80680b57cec5SDimitry Andric Expr *Operand, SourceLocation RParen) { 80690b57cec5SDimitry Andric return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 80700b57cec5SDimitry Andric } 80710b57cec5SDimitry Andric 8072fe6060f1SDimitry Andric static void MaybeDecrementCount( 8073fe6060f1SDimitry Andric Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 8074fe6060f1SDimitry Andric DeclRefExpr *LHS = nullptr; 807581ad6265SDimitry Andric bool IsCompoundAssign = false; 807681ad6265SDimitry Andric bool isIncrementDecrementUnaryOp = false; 8077fe6060f1SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8078fe6060f1SDimitry Andric if (BO->getLHS()->getType()->isDependentType() || 8079fe6060f1SDimitry Andric BO->getRHS()->getType()->isDependentType()) { 8080fe6060f1SDimitry Andric if (BO->getOpcode() != BO_Assign) 8081fe6060f1SDimitry Andric return; 8082fe6060f1SDimitry Andric } else if (!BO->isAssignmentOp()) 8083fe6060f1SDimitry Andric return; 808481ad6265SDimitry Andric else 808581ad6265SDimitry Andric IsCompoundAssign = BO->isCompoundAssignmentOp(); 8086fe6060f1SDimitry Andric LHS = dyn_cast<DeclRefExpr>(BO->getLHS()); 8087fe6060f1SDimitry Andric } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) { 8088fe6060f1SDimitry Andric if (COCE->getOperator() != OO_Equal) 8089fe6060f1SDimitry Andric return; 8090fe6060f1SDimitry Andric LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0)); 809181ad6265SDimitry Andric } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 809281ad6265SDimitry Andric if (!UO->isIncrementDecrementOp()) 809381ad6265SDimitry Andric return; 809481ad6265SDimitry Andric isIncrementDecrementUnaryOp = true; 809581ad6265SDimitry Andric LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr()); 8096fe6060f1SDimitry Andric } 8097fe6060f1SDimitry Andric if (!LHS) 8098fe6060f1SDimitry Andric return; 8099fe6060f1SDimitry Andric VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl()); 8100fe6060f1SDimitry Andric if (!VD) 8101fe6060f1SDimitry Andric return; 810281ad6265SDimitry Andric // Don't decrement RefsMinusAssignments if volatile variable with compound 810381ad6265SDimitry Andric // assignment (+=, ...) or increment/decrement unary operator to avoid 810481ad6265SDimitry Andric // potential unused-but-set-variable warning. 810581ad6265SDimitry Andric if ((IsCompoundAssign || isIncrementDecrementUnaryOp) && 810681ad6265SDimitry Andric VD->getType().isVolatileQualified()) 810781ad6265SDimitry Andric return; 8108fe6060f1SDimitry Andric auto iter = RefsMinusAssignments.find(VD); 8109fe6060f1SDimitry Andric if (iter == RefsMinusAssignments.end()) 8110fe6060f1SDimitry Andric return; 8111fe6060f1SDimitry Andric iter->getSecond()--; 8112fe6060f1SDimitry Andric } 8113fe6060f1SDimitry Andric 81140b57cec5SDimitry Andric /// Perform the conversions required for an expression used in a 81150b57cec5SDimitry Andric /// context that ignores the result. 81160b57cec5SDimitry Andric ExprResult Sema::IgnoredValueConversions(Expr *E) { 8117fe6060f1SDimitry Andric MaybeDecrementCount(E, RefsMinusAssignments); 8118fe6060f1SDimitry Andric 81190b57cec5SDimitry Andric if (E->hasPlaceholderType()) { 81200b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(E); 81210b57cec5SDimitry Andric if (result.isInvalid()) return E; 81220b57cec5SDimitry Andric E = result.get(); 81230b57cec5SDimitry Andric } 81240b57cec5SDimitry Andric 81250b57cec5SDimitry Andric // C99 6.3.2.1: 81260b57cec5SDimitry Andric // [Except in specific positions,] an lvalue that does not have 81270b57cec5SDimitry Andric // array type is converted to the value stored in the 81280b57cec5SDimitry Andric // designated object (and is no longer an lvalue). 8129fe6060f1SDimitry Andric if (E->isPRValue()) { 81300b57cec5SDimitry Andric // In C, function designators (i.e. expressions of function type) 81310b57cec5SDimitry Andric // are r-values, but we still want to do function-to-pointer decay 81320b57cec5SDimitry Andric // on them. This is both technically correct and convenient for 81330b57cec5SDimitry Andric // some clients. 81340b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 81350b57cec5SDimitry Andric return DefaultFunctionArrayConversion(E); 81360b57cec5SDimitry Andric 81370b57cec5SDimitry Andric return E; 81380b57cec5SDimitry Andric } 81390b57cec5SDimitry Andric 81400b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 81410b57cec5SDimitry Andric // The C++11 standard defines the notion of a discarded-value expression; 81420b57cec5SDimitry Andric // normally, we don't need to do anything to handle it, but if it is a 81430b57cec5SDimitry Andric // volatile lvalue with a special form, we perform an lvalue-to-rvalue 81440b57cec5SDimitry Andric // conversion. 81455ffd83dbSDimitry Andric if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { 81460b57cec5SDimitry Andric ExprResult Res = DefaultLvalueConversion(E); 81470b57cec5SDimitry Andric if (Res.isInvalid()) 81480b57cec5SDimitry Andric return E; 81490b57cec5SDimitry Andric E = Res.get(); 8150a7dea167SDimitry Andric } else { 8151a7dea167SDimitry Andric // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 8152a7dea167SDimitry Andric // it occurs as a discarded-value expression. 8153a7dea167SDimitry Andric CheckUnusedVolatileAssignment(E); 8154a7dea167SDimitry Andric } 81550b57cec5SDimitry Andric 81560b57cec5SDimitry Andric // C++1z: 81570b57cec5SDimitry Andric // If the expression is a prvalue after this optional conversion, the 81580b57cec5SDimitry Andric // temporary materialization conversion is applied. 81590b57cec5SDimitry Andric // 81600b57cec5SDimitry Andric // We skip this step: IR generation is able to synthesize the storage for 81610b57cec5SDimitry Andric // itself in the aggregate case, and adding the extra node to the AST is 81620b57cec5SDimitry Andric // just clutter. 81630b57cec5SDimitry Andric // FIXME: We don't emit lifetime markers for the temporaries due to this. 81640b57cec5SDimitry Andric // FIXME: Do any other AST consumers care about this? 81650b57cec5SDimitry Andric return E; 81660b57cec5SDimitry Andric } 81670b57cec5SDimitry Andric 81680b57cec5SDimitry Andric // GCC seems to also exclude expressions of incomplete enum type. 81690b57cec5SDimitry Andric if (const EnumType *T = E->getType()->getAs<EnumType>()) { 81700b57cec5SDimitry Andric if (!T->getDecl()->isComplete()) { 81710b57cec5SDimitry Andric // FIXME: stupid workaround for a codegen bug! 81720b57cec5SDimitry Andric E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); 81730b57cec5SDimitry Andric return E; 81740b57cec5SDimitry Andric } 81750b57cec5SDimitry Andric } 81760b57cec5SDimitry Andric 81770b57cec5SDimitry Andric ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 81780b57cec5SDimitry Andric if (Res.isInvalid()) 81790b57cec5SDimitry Andric return E; 81800b57cec5SDimitry Andric E = Res.get(); 81810b57cec5SDimitry Andric 81820b57cec5SDimitry Andric if (!E->getType()->isVoidType()) 81830b57cec5SDimitry Andric RequireCompleteType(E->getExprLoc(), E->getType(), 81840b57cec5SDimitry Andric diag::err_incomplete_type); 81850b57cec5SDimitry Andric return E; 81860b57cec5SDimitry Andric } 81870b57cec5SDimitry Andric 8188a7dea167SDimitry Andric ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { 8189a7dea167SDimitry Andric // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 8190a7dea167SDimitry Andric // it occurs as an unevaluated operand. 8191a7dea167SDimitry Andric CheckUnusedVolatileAssignment(E); 8192a7dea167SDimitry Andric 8193a7dea167SDimitry Andric return E; 8194a7dea167SDimitry Andric } 8195a7dea167SDimitry Andric 81960b57cec5SDimitry Andric // If we can unambiguously determine whether Var can never be used 81970b57cec5SDimitry Andric // in a constant expression, return true. 81980b57cec5SDimitry Andric // - if the variable and its initializer are non-dependent, then 81990b57cec5SDimitry Andric // we can unambiguously check if the variable is a constant expression. 82000b57cec5SDimitry Andric // - if the initializer is not value dependent - we can determine whether 82010b57cec5SDimitry Andric // it can be used to initialize a constant expression. If Init can not 82020b57cec5SDimitry Andric // be used to initialize a constant expression we conclude that Var can 82030b57cec5SDimitry Andric // never be a constant expression. 82040b57cec5SDimitry Andric // - FXIME: if the initializer is dependent, we can still do some analysis and 82050b57cec5SDimitry Andric // identify certain cases unambiguously as non-const by using a Visitor: 82060b57cec5SDimitry Andric // - such as those that involve odr-use of a ParmVarDecl, involve a new 82070b57cec5SDimitry Andric // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... 82080b57cec5SDimitry Andric static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 82090b57cec5SDimitry Andric ASTContext &Context) { 82100b57cec5SDimitry Andric if (isa<ParmVarDecl>(Var)) return true; 82110b57cec5SDimitry Andric const VarDecl *DefVD = nullptr; 82120b57cec5SDimitry Andric 82130b57cec5SDimitry Andric // If there is no initializer - this can not be a constant expression. 82140b57cec5SDimitry Andric if (!Var->getAnyInitializer(DefVD)) return true; 82150b57cec5SDimitry Andric assert(DefVD); 82160b57cec5SDimitry Andric if (DefVD->isWeak()) return false; 82170b57cec5SDimitry Andric EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 82180b57cec5SDimitry Andric 82190b57cec5SDimitry Andric Expr *Init = cast<Expr>(Eval->Value); 82200b57cec5SDimitry Andric 82210b57cec5SDimitry Andric if (Var->getType()->isDependentType() || Init->isValueDependent()) { 82220b57cec5SDimitry Andric // FIXME: Teach the constant evaluator to deal with the non-dependent parts 82230b57cec5SDimitry Andric // of value-dependent expressions, and use it here to determine whether the 82240b57cec5SDimitry Andric // initializer is a potential constant expression. 82250b57cec5SDimitry Andric return false; 82260b57cec5SDimitry Andric } 82270b57cec5SDimitry Andric 82280b57cec5SDimitry Andric return !Var->isUsableInConstantExpressions(Context); 82290b57cec5SDimitry Andric } 82300b57cec5SDimitry Andric 82310b57cec5SDimitry Andric /// Check if the current lambda has any potential captures 82320b57cec5SDimitry Andric /// that must be captured by any of its enclosing lambdas that are ready to 82330b57cec5SDimitry Andric /// capture. If there is a lambda that can capture a nested 82340b57cec5SDimitry Andric /// potential-capture, go ahead and do so. Also, check to see if any 82350b57cec5SDimitry Andric /// variables are uncaptureable or do not involve an odr-use so do not 82360b57cec5SDimitry Andric /// need to be captured. 82370b57cec5SDimitry Andric 82380b57cec5SDimitry Andric static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( 82390b57cec5SDimitry Andric Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { 82400b57cec5SDimitry Andric 82410b57cec5SDimitry Andric assert(!S.isUnevaluatedContext()); 82420b57cec5SDimitry Andric assert(S.CurContext->isDependentContext()); 82430b57cec5SDimitry Andric #ifndef NDEBUG 82440b57cec5SDimitry Andric DeclContext *DC = S.CurContext; 82450b57cec5SDimitry Andric while (DC && isa<CapturedDecl>(DC)) 82460b57cec5SDimitry Andric DC = DC->getParent(); 82470b57cec5SDimitry Andric assert( 82480b57cec5SDimitry Andric CurrentLSI->CallOperator == DC && 82490b57cec5SDimitry Andric "The current call operator must be synchronized with Sema's CurContext"); 82500b57cec5SDimitry Andric #endif // NDEBUG 82510b57cec5SDimitry Andric 82520b57cec5SDimitry Andric const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); 82530b57cec5SDimitry Andric 82540b57cec5SDimitry Andric // All the potentially captureable variables in the current nested 82550b57cec5SDimitry Andric // lambda (within a generic outer lambda), must be captured by an 82560b57cec5SDimitry Andric // outer lambda that is enclosed within a non-dependent context. 82570b57cec5SDimitry Andric CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) { 82580b57cec5SDimitry Andric // If the variable is clearly identified as non-odr-used and the full 82590b57cec5SDimitry Andric // expression is not instantiation dependent, only then do we not 82600b57cec5SDimitry Andric // need to check enclosing lambda's for speculative captures. 82610b57cec5SDimitry Andric // For e.g.: 82620b57cec5SDimitry Andric // Even though 'x' is not odr-used, it should be captured. 82630b57cec5SDimitry Andric // int test() { 82640b57cec5SDimitry Andric // const int x = 10; 82650b57cec5SDimitry Andric // auto L = [=](auto a) { 82660b57cec5SDimitry Andric // (void) +x + a; 82670b57cec5SDimitry Andric // }; 82680b57cec5SDimitry Andric // } 82690b57cec5SDimitry Andric if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && 82700b57cec5SDimitry Andric !IsFullExprInstantiationDependent) 82710b57cec5SDimitry Andric return; 82720b57cec5SDimitry Andric 82730b57cec5SDimitry Andric // If we have a capture-capable lambda for the variable, go ahead and 82740b57cec5SDimitry Andric // capture the variable in that lambda (and all its enclosing lambdas). 82750b57cec5SDimitry Andric if (const Optional<unsigned> Index = 82760b57cec5SDimitry Andric getStackIndexOfNearestEnclosingCaptureCapableLambda( 82770b57cec5SDimitry Andric S.FunctionScopes, Var, S)) 827881ad6265SDimitry Andric S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index); 82790b57cec5SDimitry Andric const bool IsVarNeverAConstantExpression = 82800b57cec5SDimitry Andric VariableCanNeverBeAConstantExpression(Var, S.Context); 82810b57cec5SDimitry Andric if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { 82820b57cec5SDimitry Andric // This full expression is not instantiation dependent or the variable 82830b57cec5SDimitry Andric // can not be used in a constant expression - which means 82840b57cec5SDimitry Andric // this variable must be odr-used here, so diagnose a 82850b57cec5SDimitry Andric // capture violation early, if the variable is un-captureable. 82860b57cec5SDimitry Andric // This is purely for diagnosing errors early. Otherwise, this 82870b57cec5SDimitry Andric // error would get diagnosed when the lambda becomes capture ready. 82880b57cec5SDimitry Andric QualType CaptureType, DeclRefType; 82890b57cec5SDimitry Andric SourceLocation ExprLoc = VarExpr->getExprLoc(); 82900b57cec5SDimitry Andric if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 82910b57cec5SDimitry Andric /*EllipsisLoc*/ SourceLocation(), 82920b57cec5SDimitry Andric /*BuildAndDiagnose*/false, CaptureType, 82930b57cec5SDimitry Andric DeclRefType, nullptr)) { 82940b57cec5SDimitry Andric // We will never be able to capture this variable, and we need 82950b57cec5SDimitry Andric // to be able to in any and all instantiations, so diagnose it. 82960b57cec5SDimitry Andric S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 82970b57cec5SDimitry Andric /*EllipsisLoc*/ SourceLocation(), 82980b57cec5SDimitry Andric /*BuildAndDiagnose*/true, CaptureType, 82990b57cec5SDimitry Andric DeclRefType, nullptr); 83000b57cec5SDimitry Andric } 83010b57cec5SDimitry Andric } 83020b57cec5SDimitry Andric }); 83030b57cec5SDimitry Andric 83040b57cec5SDimitry Andric // Check if 'this' needs to be captured. 83050b57cec5SDimitry Andric if (CurrentLSI->hasPotentialThisCapture()) { 83060b57cec5SDimitry Andric // If we have a capture-capable lambda for 'this', go ahead and capture 83070b57cec5SDimitry Andric // 'this' in that lambda (and all its enclosing lambdas). 83080b57cec5SDimitry Andric if (const Optional<unsigned> Index = 83090b57cec5SDimitry Andric getStackIndexOfNearestEnclosingCaptureCapableLambda( 83100b57cec5SDimitry Andric S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { 831181ad6265SDimitry Andric const unsigned FunctionScopeIndexOfCapturableLambda = *Index; 83120b57cec5SDimitry Andric S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, 83130b57cec5SDimitry Andric /*Explicit*/ false, /*BuildAndDiagnose*/ true, 83140b57cec5SDimitry Andric &FunctionScopeIndexOfCapturableLambda); 83150b57cec5SDimitry Andric } 83160b57cec5SDimitry Andric } 83170b57cec5SDimitry Andric 83180b57cec5SDimitry Andric // Reset all the potential captures at the end of each full-expression. 83190b57cec5SDimitry Andric CurrentLSI->clearPotentialCaptures(); 83200b57cec5SDimitry Andric } 83210b57cec5SDimitry Andric 83220b57cec5SDimitry Andric static ExprResult attemptRecovery(Sema &SemaRef, 83230b57cec5SDimitry Andric const TypoCorrectionConsumer &Consumer, 83240b57cec5SDimitry Andric const TypoCorrection &TC) { 83250b57cec5SDimitry Andric LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), 83260b57cec5SDimitry Andric Consumer.getLookupResult().getLookupKind()); 83270b57cec5SDimitry Andric const CXXScopeSpec *SS = Consumer.getSS(); 83280b57cec5SDimitry Andric CXXScopeSpec NewSS; 83290b57cec5SDimitry Andric 83300b57cec5SDimitry Andric // Use an approprate CXXScopeSpec for building the expr. 83310b57cec5SDimitry Andric if (auto *NNS = TC.getCorrectionSpecifier()) 83320b57cec5SDimitry Andric NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); 83330b57cec5SDimitry Andric else if (SS && !TC.WillReplaceSpecifier()) 83340b57cec5SDimitry Andric NewSS = *SS; 83350b57cec5SDimitry Andric 83360b57cec5SDimitry Andric if (auto *ND = TC.getFoundDecl()) { 83370b57cec5SDimitry Andric R.setLookupName(ND->getDeclName()); 83380b57cec5SDimitry Andric R.addDecl(ND); 83390b57cec5SDimitry Andric if (ND->isCXXClassMember()) { 83400b57cec5SDimitry Andric // Figure out the correct naming class to add to the LookupResult. 83410b57cec5SDimitry Andric CXXRecordDecl *Record = nullptr; 83420b57cec5SDimitry Andric if (auto *NNS = TC.getCorrectionSpecifier()) 83430b57cec5SDimitry Andric Record = NNS->getAsType()->getAsCXXRecordDecl(); 83440b57cec5SDimitry Andric if (!Record) 83450b57cec5SDimitry Andric Record = 83460b57cec5SDimitry Andric dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); 83470b57cec5SDimitry Andric if (Record) 83480b57cec5SDimitry Andric R.setNamingClass(Record); 83490b57cec5SDimitry Andric 83500b57cec5SDimitry Andric // Detect and handle the case where the decl might be an implicit 83510b57cec5SDimitry Andric // member. 83520b57cec5SDimitry Andric bool MightBeImplicitMember; 83530b57cec5SDimitry Andric if (!Consumer.isAddressOfOperand()) 83540b57cec5SDimitry Andric MightBeImplicitMember = true; 83550b57cec5SDimitry Andric else if (!NewSS.isEmpty()) 83560b57cec5SDimitry Andric MightBeImplicitMember = false; 83570b57cec5SDimitry Andric else if (R.isOverloadedResult()) 83580b57cec5SDimitry Andric MightBeImplicitMember = false; 83590b57cec5SDimitry Andric else if (R.isUnresolvableResult()) 83600b57cec5SDimitry Andric MightBeImplicitMember = true; 83610b57cec5SDimitry Andric else 83620b57cec5SDimitry Andric MightBeImplicitMember = isa<FieldDecl>(ND) || 83630b57cec5SDimitry Andric isa<IndirectFieldDecl>(ND) || 83640b57cec5SDimitry Andric isa<MSPropertyDecl>(ND); 83650b57cec5SDimitry Andric 83660b57cec5SDimitry Andric if (MightBeImplicitMember) 83670b57cec5SDimitry Andric return SemaRef.BuildPossibleImplicitMemberExpr( 83680b57cec5SDimitry Andric NewSS, /*TemplateKWLoc*/ SourceLocation(), R, 83690b57cec5SDimitry Andric /*TemplateArgs*/ nullptr, /*S*/ nullptr); 83700b57cec5SDimitry Andric } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 83710b57cec5SDimitry Andric return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), 83720b57cec5SDimitry Andric Ivar->getIdentifier()); 83730b57cec5SDimitry Andric } 83740b57cec5SDimitry Andric } 83750b57cec5SDimitry Andric 83760b57cec5SDimitry Andric return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, 83770b57cec5SDimitry Andric /*AcceptInvalidDecl*/ true); 83780b57cec5SDimitry Andric } 83790b57cec5SDimitry Andric 83800b57cec5SDimitry Andric namespace { 83810b57cec5SDimitry Andric class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { 83820b57cec5SDimitry Andric llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; 83830b57cec5SDimitry Andric 83840b57cec5SDimitry Andric public: 83850b57cec5SDimitry Andric explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) 83860b57cec5SDimitry Andric : TypoExprs(TypoExprs) {} 83870b57cec5SDimitry Andric bool VisitTypoExpr(TypoExpr *TE) { 83880b57cec5SDimitry Andric TypoExprs.insert(TE); 83890b57cec5SDimitry Andric return true; 83900b57cec5SDimitry Andric } 83910b57cec5SDimitry Andric }; 83920b57cec5SDimitry Andric 83930b57cec5SDimitry Andric class TransformTypos : public TreeTransform<TransformTypos> { 83940b57cec5SDimitry Andric typedef TreeTransform<TransformTypos> BaseTransform; 83950b57cec5SDimitry Andric 83960b57cec5SDimitry Andric VarDecl *InitDecl; // A decl to avoid as a correction because it is in the 83970b57cec5SDimitry Andric // process of being initialized. 83980b57cec5SDimitry Andric llvm::function_ref<ExprResult(Expr *)> ExprFilter; 83990b57cec5SDimitry Andric llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; 84000b57cec5SDimitry Andric llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; 84010b57cec5SDimitry Andric llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; 84020b57cec5SDimitry Andric 84030b57cec5SDimitry Andric /// Emit diagnostics for all of the TypoExprs encountered. 8404a7dea167SDimitry Andric /// 84050b57cec5SDimitry Andric /// If the TypoExprs were successfully corrected, then the diagnostics should 84060b57cec5SDimitry Andric /// suggest the corrections. Otherwise the diagnostics will not suggest 84070b57cec5SDimitry Andric /// anything (having been passed an empty TypoCorrection). 8408a7dea167SDimitry Andric /// 8409a7dea167SDimitry Andric /// If we've failed to correct due to ambiguous corrections, we need to 8410a7dea167SDimitry Andric /// be sure to pass empty corrections and replacements. Otherwise it's 8411a7dea167SDimitry Andric /// possible that the Consumer has a TypoCorrection that failed to ambiguity 8412a7dea167SDimitry Andric /// and we don't want to report those diagnostics. 8413a7dea167SDimitry Andric void EmitAllDiagnostics(bool IsAmbiguous) { 84140b57cec5SDimitry Andric for (TypoExpr *TE : TypoExprs) { 84150b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(TE); 84160b57cec5SDimitry Andric if (State.DiagHandler) { 8417a7dea167SDimitry Andric TypoCorrection TC = IsAmbiguous 8418a7dea167SDimitry Andric ? TypoCorrection() : State.Consumer->getCurrentCorrection(); 8419a7dea167SDimitry Andric ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; 84200b57cec5SDimitry Andric 84210b57cec5SDimitry Andric // Extract the NamedDecl from the transformed TypoExpr and add it to the 84220b57cec5SDimitry Andric // TypoCorrection, replacing the existing decls. This ensures the right 84230b57cec5SDimitry Andric // NamedDecl is used in diagnostics e.g. in the case where overload 84240b57cec5SDimitry Andric // resolution was used to select one from several possible decls that 84250b57cec5SDimitry Andric // had been stored in the TypoCorrection. 84260b57cec5SDimitry Andric if (auto *ND = getDeclFromExpr( 84270b57cec5SDimitry Andric Replacement.isInvalid() ? nullptr : Replacement.get())) 84280b57cec5SDimitry Andric TC.setCorrectionDecl(ND); 84290b57cec5SDimitry Andric 84300b57cec5SDimitry Andric State.DiagHandler(TC); 84310b57cec5SDimitry Andric } 84320b57cec5SDimitry Andric SemaRef.clearDelayedTypo(TE); 84330b57cec5SDimitry Andric } 84340b57cec5SDimitry Andric } 84350b57cec5SDimitry Andric 8436590d96feSDimitry Andric /// Try to advance the typo correction state of the first unfinished TypoExpr. 8437590d96feSDimitry Andric /// We allow advancement of the correction stream by removing it from the 8438590d96feSDimitry Andric /// TransformCache which allows `TransformTypoExpr` to advance during the 8439590d96feSDimitry Andric /// next transformation attempt. 8440590d96feSDimitry Andric /// 8441590d96feSDimitry Andric /// Any substitution attempts for the previous TypoExprs (which must have been 8442590d96feSDimitry Andric /// finished) will need to be retried since it's possible that they will now 8443590d96feSDimitry Andric /// be invalid given the latest advancement. 8444590d96feSDimitry Andric /// 8445590d96feSDimitry Andric /// We need to be sure that we're making progress - it's possible that the 8446590d96feSDimitry Andric /// tree is so malformed that the transform never makes it to the 8447590d96feSDimitry Andric /// `TransformTypoExpr`. 8448590d96feSDimitry Andric /// 8449590d96feSDimitry Andric /// Returns true if there are any untried correction combinations. 84500b57cec5SDimitry Andric bool CheckAndAdvanceTypoExprCorrectionStreams() { 84510b57cec5SDimitry Andric for (auto TE : TypoExprs) { 84520b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(TE); 84530b57cec5SDimitry Andric TransformCache.erase(TE); 8454590d96feSDimitry Andric if (!State.Consumer->hasMadeAnyCorrectionProgress()) 8455590d96feSDimitry Andric return false; 84560b57cec5SDimitry Andric if (!State.Consumer->finished()) 84570b57cec5SDimitry Andric return true; 84580b57cec5SDimitry Andric State.Consumer->resetCorrectionStream(); 84590b57cec5SDimitry Andric } 84600b57cec5SDimitry Andric return false; 84610b57cec5SDimitry Andric } 84620b57cec5SDimitry Andric 84630b57cec5SDimitry Andric NamedDecl *getDeclFromExpr(Expr *E) { 84640b57cec5SDimitry Andric if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) 84650b57cec5SDimitry Andric E = OverloadResolution[OE]; 84660b57cec5SDimitry Andric 84670b57cec5SDimitry Andric if (!E) 84680b57cec5SDimitry Andric return nullptr; 84690b57cec5SDimitry Andric if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 84700b57cec5SDimitry Andric return DRE->getFoundDecl(); 84710b57cec5SDimitry Andric if (auto *ME = dyn_cast<MemberExpr>(E)) 84720b57cec5SDimitry Andric return ME->getFoundDecl(); 84730b57cec5SDimitry Andric // FIXME: Add any other expr types that could be be seen by the delayed typo 84740b57cec5SDimitry Andric // correction TreeTransform for which the corresponding TypoCorrection could 84750b57cec5SDimitry Andric // contain multiple decls. 84760b57cec5SDimitry Andric return nullptr; 84770b57cec5SDimitry Andric } 84780b57cec5SDimitry Andric 84790b57cec5SDimitry Andric ExprResult TryTransform(Expr *E) { 84800b57cec5SDimitry Andric Sema::SFINAETrap Trap(SemaRef); 84810b57cec5SDimitry Andric ExprResult Res = TransformExpr(E); 84820b57cec5SDimitry Andric if (Trap.hasErrorOccurred() || Res.isInvalid()) 84830b57cec5SDimitry Andric return ExprError(); 84840b57cec5SDimitry Andric 84850b57cec5SDimitry Andric return ExprFilter(Res.get()); 84860b57cec5SDimitry Andric } 84870b57cec5SDimitry Andric 8488a7dea167SDimitry Andric // Since correcting typos may intoduce new TypoExprs, this function 8489a7dea167SDimitry Andric // checks for new TypoExprs and recurses if it finds any. Note that it will 8490a7dea167SDimitry Andric // only succeed if it is able to correct all typos in the given expression. 8491a7dea167SDimitry Andric ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { 8492a7dea167SDimitry Andric if (Res.isInvalid()) { 8493a7dea167SDimitry Andric return Res; 8494a7dea167SDimitry Andric } 8495a7dea167SDimitry Andric // Check to see if any new TypoExprs were created. If so, we need to recurse 8496a7dea167SDimitry Andric // to check their validity. 8497a7dea167SDimitry Andric Expr *FixedExpr = Res.get(); 8498a7dea167SDimitry Andric 8499a7dea167SDimitry Andric auto SavedTypoExprs = std::move(TypoExprs); 8500a7dea167SDimitry Andric auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); 8501a7dea167SDimitry Andric TypoExprs.clear(); 8502a7dea167SDimitry Andric AmbiguousTypoExprs.clear(); 8503a7dea167SDimitry Andric 8504a7dea167SDimitry Andric FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); 8505a7dea167SDimitry Andric if (!TypoExprs.empty()) { 8506a7dea167SDimitry Andric // Recurse to handle newly created TypoExprs. If we're not able to 8507a7dea167SDimitry Andric // handle them, discard these TypoExprs. 8508a7dea167SDimitry Andric ExprResult RecurResult = 8509a7dea167SDimitry Andric RecursiveTransformLoop(FixedExpr, IsAmbiguous); 8510a7dea167SDimitry Andric if (RecurResult.isInvalid()) { 8511a7dea167SDimitry Andric Res = ExprError(); 8512a7dea167SDimitry Andric // Recursive corrections didn't work, wipe them away and don't add 8513a7dea167SDimitry Andric // them to the TypoExprs set. Remove them from Sema's TypoExpr list 8514a7dea167SDimitry Andric // since we don't want to clear them twice. Note: it's possible the 8515a7dea167SDimitry Andric // TypoExprs were created recursively and thus won't be in our 8516a7dea167SDimitry Andric // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. 8517a7dea167SDimitry Andric auto &SemaTypoExprs = SemaRef.TypoExprs; 8518a7dea167SDimitry Andric for (auto TE : TypoExprs) { 8519a7dea167SDimitry Andric TransformCache.erase(TE); 8520a7dea167SDimitry Andric SemaRef.clearDelayedTypo(TE); 8521a7dea167SDimitry Andric 8522a7dea167SDimitry Andric auto SI = find(SemaTypoExprs, TE); 8523a7dea167SDimitry Andric if (SI != SemaTypoExprs.end()) { 8524a7dea167SDimitry Andric SemaTypoExprs.erase(SI); 8525a7dea167SDimitry Andric } 8526a7dea167SDimitry Andric } 8527a7dea167SDimitry Andric } else { 8528a7dea167SDimitry Andric // TypoExpr is valid: add newly created TypoExprs since we were 8529a7dea167SDimitry Andric // able to correct them. 8530a7dea167SDimitry Andric Res = RecurResult; 8531a7dea167SDimitry Andric SavedTypoExprs.set_union(TypoExprs); 8532a7dea167SDimitry Andric } 8533a7dea167SDimitry Andric } 8534a7dea167SDimitry Andric 8535a7dea167SDimitry Andric TypoExprs = std::move(SavedTypoExprs); 8536a7dea167SDimitry Andric AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); 8537a7dea167SDimitry Andric 8538a7dea167SDimitry Andric return Res; 8539a7dea167SDimitry Andric } 8540a7dea167SDimitry Andric 8541a7dea167SDimitry Andric // Try to transform the given expression, looping through the correction 8542a7dea167SDimitry Andric // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. 8543a7dea167SDimitry Andric // 8544a7dea167SDimitry Andric // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to 8545a7dea167SDimitry Andric // true and this method immediately will return an `ExprError`. 8546a7dea167SDimitry Andric ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { 8547a7dea167SDimitry Andric ExprResult Res; 8548a7dea167SDimitry Andric auto SavedTypoExprs = std::move(SemaRef.TypoExprs); 8549a7dea167SDimitry Andric SemaRef.TypoExprs.clear(); 8550a7dea167SDimitry Andric 8551a7dea167SDimitry Andric while (true) { 8552a7dea167SDimitry Andric Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 8553a7dea167SDimitry Andric 8554a7dea167SDimitry Andric // Recursion encountered an ambiguous correction. This means that our 8555a7dea167SDimitry Andric // correction itself is ambiguous, so stop now. 8556a7dea167SDimitry Andric if (IsAmbiguous) 8557a7dea167SDimitry Andric break; 8558a7dea167SDimitry Andric 8559a7dea167SDimitry Andric // If the transform is still valid after checking for any new typos, 8560a7dea167SDimitry Andric // it's good to go. 8561a7dea167SDimitry Andric if (!Res.isInvalid()) 8562a7dea167SDimitry Andric break; 8563a7dea167SDimitry Andric 8564a7dea167SDimitry Andric // The transform was invalid, see if we have any TypoExprs with untried 8565a7dea167SDimitry Andric // correction candidates. 8566a7dea167SDimitry Andric if (!CheckAndAdvanceTypoExprCorrectionStreams()) 8567a7dea167SDimitry Andric break; 8568a7dea167SDimitry Andric } 8569a7dea167SDimitry Andric 8570a7dea167SDimitry Andric // If we found a valid result, double check to make sure it's not ambiguous. 8571a7dea167SDimitry Andric if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { 8572480093f4SDimitry Andric auto SavedTransformCache = 8573480093f4SDimitry Andric llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); 8574480093f4SDimitry Andric 8575a7dea167SDimitry Andric // Ensure none of the TypoExprs have multiple typo correction candidates 8576a7dea167SDimitry Andric // with the same edit length that pass all the checks and filters. 8577a7dea167SDimitry Andric while (!AmbiguousTypoExprs.empty()) { 8578a7dea167SDimitry Andric auto TE = AmbiguousTypoExprs.back(); 8579a7dea167SDimitry Andric 8580a7dea167SDimitry Andric // TryTransform itself can create new Typos, adding them to the TypoExpr map 8581a7dea167SDimitry Andric // and invalidating our TypoExprState, so always fetch it instead of storing. 8582a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); 8583a7dea167SDimitry Andric 8584a7dea167SDimitry Andric TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); 8585a7dea167SDimitry Andric TypoCorrection Next; 8586a7dea167SDimitry Andric do { 8587a7dea167SDimitry Andric // Fetch the next correction by erasing the typo from the cache and calling 8588a7dea167SDimitry Andric // `TryTransform` which will iterate through corrections in 8589a7dea167SDimitry Andric // `TransformTypoExpr`. 8590a7dea167SDimitry Andric TransformCache.erase(TE); 8591a7dea167SDimitry Andric ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 8592a7dea167SDimitry Andric 8593a7dea167SDimitry Andric if (!AmbigRes.isInvalid() || IsAmbiguous) { 8594a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); 8595a7dea167SDimitry Andric SavedTransformCache.erase(TE); 8596a7dea167SDimitry Andric Res = ExprError(); 8597a7dea167SDimitry Andric IsAmbiguous = true; 8598a7dea167SDimitry Andric break; 8599a7dea167SDimitry Andric } 8600a7dea167SDimitry Andric } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && 8601a7dea167SDimitry Andric Next.getEditDistance(false) == TC.getEditDistance(false)); 8602a7dea167SDimitry Andric 8603a7dea167SDimitry Andric if (IsAmbiguous) 8604a7dea167SDimitry Andric break; 8605a7dea167SDimitry Andric 8606a7dea167SDimitry Andric AmbiguousTypoExprs.remove(TE); 8607a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); 8608fe6060f1SDimitry Andric TransformCache[TE] = SavedTransformCache[TE]; 8609a7dea167SDimitry Andric } 8610a7dea167SDimitry Andric TransformCache = std::move(SavedTransformCache); 8611a7dea167SDimitry Andric } 8612a7dea167SDimitry Andric 8613a7dea167SDimitry Andric // Wipe away any newly created TypoExprs that we don't know about. Since we 8614a7dea167SDimitry Andric // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only 8615a7dea167SDimitry Andric // possible if a `TypoExpr` is created during a transformation but then 8616a7dea167SDimitry Andric // fails before we can discover it. 8617a7dea167SDimitry Andric auto &SemaTypoExprs = SemaRef.TypoExprs; 8618a7dea167SDimitry Andric for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { 8619a7dea167SDimitry Andric auto TE = *Iterator; 8620a7dea167SDimitry Andric auto FI = find(TypoExprs, TE); 8621a7dea167SDimitry Andric if (FI != TypoExprs.end()) { 8622a7dea167SDimitry Andric Iterator++; 8623a7dea167SDimitry Andric continue; 8624a7dea167SDimitry Andric } 8625a7dea167SDimitry Andric SemaRef.clearDelayedTypo(TE); 8626a7dea167SDimitry Andric Iterator = SemaTypoExprs.erase(Iterator); 8627a7dea167SDimitry Andric } 8628a7dea167SDimitry Andric SemaRef.TypoExprs = std::move(SavedTypoExprs); 8629a7dea167SDimitry Andric 8630a7dea167SDimitry Andric return Res; 8631a7dea167SDimitry Andric } 8632a7dea167SDimitry Andric 86330b57cec5SDimitry Andric public: 86340b57cec5SDimitry Andric TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) 86350b57cec5SDimitry Andric : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} 86360b57cec5SDimitry Andric 86370b57cec5SDimitry Andric ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, 86380b57cec5SDimitry Andric MultiExprArg Args, 86390b57cec5SDimitry Andric SourceLocation RParenLoc, 86400b57cec5SDimitry Andric Expr *ExecConfig = nullptr) { 86410b57cec5SDimitry Andric auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, 86420b57cec5SDimitry Andric RParenLoc, ExecConfig); 86430b57cec5SDimitry Andric if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { 86440b57cec5SDimitry Andric if (Result.isUsable()) { 86450b57cec5SDimitry Andric Expr *ResultCall = Result.get(); 86460b57cec5SDimitry Andric if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) 86470b57cec5SDimitry Andric ResultCall = BE->getSubExpr(); 86480b57cec5SDimitry Andric if (auto *CE = dyn_cast<CallExpr>(ResultCall)) 86490b57cec5SDimitry Andric OverloadResolution[OE] = CE->getCallee(); 86500b57cec5SDimitry Andric } 86510b57cec5SDimitry Andric } 86520b57cec5SDimitry Andric return Result; 86530b57cec5SDimitry Andric } 86540b57cec5SDimitry Andric 86550b57cec5SDimitry Andric ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } 86560b57cec5SDimitry Andric 86570b57cec5SDimitry Andric ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } 86580b57cec5SDimitry Andric 86590b57cec5SDimitry Andric ExprResult Transform(Expr *E) { 8660a7dea167SDimitry Andric bool IsAmbiguous = false; 8661a7dea167SDimitry Andric ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); 86620b57cec5SDimitry Andric 86630b57cec5SDimitry Andric if (!Res.isUsable()) 86640b57cec5SDimitry Andric FindTypoExprs(TypoExprs).TraverseStmt(E); 86650b57cec5SDimitry Andric 8666a7dea167SDimitry Andric EmitAllDiagnostics(IsAmbiguous); 86670b57cec5SDimitry Andric 86680b57cec5SDimitry Andric return Res; 86690b57cec5SDimitry Andric } 86700b57cec5SDimitry Andric 86710b57cec5SDimitry Andric ExprResult TransformTypoExpr(TypoExpr *E) { 86720b57cec5SDimitry Andric // If the TypoExpr hasn't been seen before, record it. Otherwise, return the 86730b57cec5SDimitry Andric // cached transformation result if there is one and the TypoExpr isn't the 86740b57cec5SDimitry Andric // first one that was encountered. 86750b57cec5SDimitry Andric auto &CacheEntry = TransformCache[E]; 86760b57cec5SDimitry Andric if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { 86770b57cec5SDimitry Andric return CacheEntry; 86780b57cec5SDimitry Andric } 86790b57cec5SDimitry Andric 86800b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(E); 86810b57cec5SDimitry Andric assert(State.Consumer && "Cannot transform a cleared TypoExpr"); 86820b57cec5SDimitry Andric 86830b57cec5SDimitry Andric // For the first TypoExpr and an uncached TypoExpr, find the next likely 86840b57cec5SDimitry Andric // typo correction and return it. 86850b57cec5SDimitry Andric while (TypoCorrection TC = State.Consumer->getNextCorrection()) { 86860b57cec5SDimitry Andric if (InitDecl && TC.getFoundDecl() == InitDecl) 86870b57cec5SDimitry Andric continue; 86880b57cec5SDimitry Andric // FIXME: If we would typo-correct to an invalid declaration, it's 86890b57cec5SDimitry Andric // probably best to just suppress all errors from this typo correction. 86900b57cec5SDimitry Andric ExprResult NE = State.RecoveryHandler ? 86910b57cec5SDimitry Andric State.RecoveryHandler(SemaRef, E, TC) : 86920b57cec5SDimitry Andric attemptRecovery(SemaRef, *State.Consumer, TC); 86930b57cec5SDimitry Andric if (!NE.isInvalid()) { 86940b57cec5SDimitry Andric // Check whether there may be a second viable correction with the same 86950b57cec5SDimitry Andric // edit distance; if so, remember this TypoExpr may have an ambiguous 86960b57cec5SDimitry Andric // correction so it can be more thoroughly vetted later. 86970b57cec5SDimitry Andric TypoCorrection Next; 86980b57cec5SDimitry Andric if ((Next = State.Consumer->peekNextCorrection()) && 86990b57cec5SDimitry Andric Next.getEditDistance(false) == TC.getEditDistance(false)) { 87000b57cec5SDimitry Andric AmbiguousTypoExprs.insert(E); 87010b57cec5SDimitry Andric } else { 87020b57cec5SDimitry Andric AmbiguousTypoExprs.remove(E); 87030b57cec5SDimitry Andric } 87040b57cec5SDimitry Andric assert(!NE.isUnset() && 87050b57cec5SDimitry Andric "Typo was transformed into a valid-but-null ExprResult"); 87060b57cec5SDimitry Andric return CacheEntry = NE; 87070b57cec5SDimitry Andric } 87080b57cec5SDimitry Andric } 87090b57cec5SDimitry Andric return CacheEntry = ExprError(); 87100b57cec5SDimitry Andric } 87110b57cec5SDimitry Andric }; 87120b57cec5SDimitry Andric } 87130b57cec5SDimitry Andric 87140b57cec5SDimitry Andric ExprResult 87150b57cec5SDimitry Andric Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, 87165ffd83dbSDimitry Andric bool RecoverUncorrectedTypos, 87170b57cec5SDimitry Andric llvm::function_ref<ExprResult(Expr *)> Filter) { 87180b57cec5SDimitry Andric // If the current evaluation context indicates there are uncorrected typos 87190b57cec5SDimitry Andric // and the current expression isn't guaranteed to not have typos, try to 87200b57cec5SDimitry Andric // resolve any TypoExpr nodes that might be in the expression. 87210b57cec5SDimitry Andric if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && 87220b57cec5SDimitry Andric (E->isTypeDependent() || E->isValueDependent() || 87230b57cec5SDimitry Andric E->isInstantiationDependent())) { 87240b57cec5SDimitry Andric auto TyposResolved = DelayedTypos.size(); 87250b57cec5SDimitry Andric auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); 87260b57cec5SDimitry Andric TyposResolved -= DelayedTypos.size(); 87270b57cec5SDimitry Andric if (Result.isInvalid() || Result.get() != E) { 87280b57cec5SDimitry Andric ExprEvalContexts.back().NumTypos -= TyposResolved; 87295ffd83dbSDimitry Andric if (Result.isInvalid() && RecoverUncorrectedTypos) { 87305ffd83dbSDimitry Andric struct TyposReplace : TreeTransform<TyposReplace> { 87315ffd83dbSDimitry Andric TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {} 87325ffd83dbSDimitry Andric ExprResult TransformTypoExpr(clang::TypoExpr *E) { 87335ffd83dbSDimitry Andric return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(), 87345ffd83dbSDimitry Andric E->getEndLoc(), {}); 87355ffd83dbSDimitry Andric } 87365ffd83dbSDimitry Andric } TT(*this); 87375ffd83dbSDimitry Andric return TT.TransformExpr(E); 87385ffd83dbSDimitry Andric } 87390b57cec5SDimitry Andric return Result; 87400b57cec5SDimitry Andric } 87410b57cec5SDimitry Andric assert(TyposResolved == 0 && "Corrected typo but got same Expr back?"); 87420b57cec5SDimitry Andric } 87430b57cec5SDimitry Andric return E; 87440b57cec5SDimitry Andric } 87450b57cec5SDimitry Andric 87460b57cec5SDimitry Andric ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, 87470b57cec5SDimitry Andric bool DiscardedValue, 87480b57cec5SDimitry Andric bool IsConstexpr) { 87490b57cec5SDimitry Andric ExprResult FullExpr = FE; 87500b57cec5SDimitry Andric 87510b57cec5SDimitry Andric if (!FullExpr.get()) 87520b57cec5SDimitry Andric return ExprError(); 87530b57cec5SDimitry Andric 87540b57cec5SDimitry Andric if (DiagnoseUnexpandedParameterPack(FullExpr.get())) 87550b57cec5SDimitry Andric return ExprError(); 87560b57cec5SDimitry Andric 87570b57cec5SDimitry Andric if (DiscardedValue) { 87580b57cec5SDimitry Andric // Top-level expressions default to 'id' when we're in a debugger. 87590b57cec5SDimitry Andric if (getLangOpts().DebuggerCastResultToId && 87600b57cec5SDimitry Andric FullExpr.get()->getType() == Context.UnknownAnyTy) { 87610b57cec5SDimitry Andric FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); 87620b57cec5SDimitry Andric if (FullExpr.isInvalid()) 87630b57cec5SDimitry Andric return ExprError(); 87640b57cec5SDimitry Andric } 87650b57cec5SDimitry Andric 87660b57cec5SDimitry Andric FullExpr = CheckPlaceholderExpr(FullExpr.get()); 87670b57cec5SDimitry Andric if (FullExpr.isInvalid()) 87680b57cec5SDimitry Andric return ExprError(); 87690b57cec5SDimitry Andric 87700b57cec5SDimitry Andric FullExpr = IgnoredValueConversions(FullExpr.get()); 87710b57cec5SDimitry Andric if (FullExpr.isInvalid()) 87720b57cec5SDimitry Andric return ExprError(); 87730b57cec5SDimitry Andric 8774349cc55cSDimitry Andric DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr); 87750b57cec5SDimitry Andric } 87760b57cec5SDimitry Andric 87775ffd83dbSDimitry Andric FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr, 87785ffd83dbSDimitry Andric /*RecoverUncorrectedTypos=*/true); 87790b57cec5SDimitry Andric if (FullExpr.isInvalid()) 87800b57cec5SDimitry Andric return ExprError(); 87810b57cec5SDimitry Andric 87820b57cec5SDimitry Andric CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); 87830b57cec5SDimitry Andric 87840b57cec5SDimitry Andric // At the end of this full expression (which could be a deeply nested 87850b57cec5SDimitry Andric // lambda), if there is a potential capture within the nested lambda, 87860b57cec5SDimitry Andric // have the outer capture-able lambda try and capture it. 87870b57cec5SDimitry Andric // Consider the following code: 87880b57cec5SDimitry Andric // void f(int, int); 87890b57cec5SDimitry Andric // void f(const int&, double); 87900b57cec5SDimitry Andric // void foo() { 87910b57cec5SDimitry Andric // const int x = 10, y = 20; 87920b57cec5SDimitry Andric // auto L = [=](auto a) { 87930b57cec5SDimitry Andric // auto M = [=](auto b) { 87940b57cec5SDimitry Andric // f(x, b); <-- requires x to be captured by L and M 87950b57cec5SDimitry Andric // f(y, a); <-- requires y to be captured by L, but not all Ms 87960b57cec5SDimitry Andric // }; 87970b57cec5SDimitry Andric // }; 87980b57cec5SDimitry Andric // } 87990b57cec5SDimitry Andric 88000b57cec5SDimitry Andric // FIXME: Also consider what happens for something like this that involves 88010b57cec5SDimitry Andric // the gnu-extension statement-expressions or even lambda-init-captures: 88020b57cec5SDimitry Andric // void f() { 88030b57cec5SDimitry Andric // const int n = 0; 88040b57cec5SDimitry Andric // auto L = [&](auto a) { 88050b57cec5SDimitry Andric // +n + ({ 0; a; }); 88060b57cec5SDimitry Andric // }; 88070b57cec5SDimitry Andric // } 88080b57cec5SDimitry Andric // 88090b57cec5SDimitry Andric // Here, we see +n, and then the full-expression 0; ends, so we don't 88100b57cec5SDimitry Andric // capture n (and instead remove it from our list of potential captures), 88110b57cec5SDimitry Andric // and then the full-expression +n + ({ 0; }); ends, but it's too late 88120b57cec5SDimitry Andric // for us to see that we need to capture n after all. 88130b57cec5SDimitry Andric 88140b57cec5SDimitry Andric LambdaScopeInfo *const CurrentLSI = 88150b57cec5SDimitry Andric getCurLambda(/*IgnoreCapturedRegions=*/true); 88160b57cec5SDimitry Andric // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 88170b57cec5SDimitry Andric // even if CurContext is not a lambda call operator. Refer to that Bug Report 88180b57cec5SDimitry Andric // for an example of the code that might cause this asynchrony. 88190b57cec5SDimitry Andric // By ensuring we are in the context of a lambda's call operator 88200b57cec5SDimitry Andric // we can fix the bug (we only need to check whether we need to capture 88210b57cec5SDimitry Andric // if we are within a lambda's body); but per the comments in that 88220b57cec5SDimitry Andric // PR, a proper fix would entail : 88230b57cec5SDimitry Andric // "Alternative suggestion: 88240b57cec5SDimitry Andric // - Add to Sema an integer holding the smallest (outermost) scope 88250b57cec5SDimitry Andric // index that we are *lexically* within, and save/restore/set to 88260b57cec5SDimitry Andric // FunctionScopes.size() in InstantiatingTemplate's 88270b57cec5SDimitry Andric // constructor/destructor. 88280b57cec5SDimitry Andric // - Teach the handful of places that iterate over FunctionScopes to 88290b57cec5SDimitry Andric // stop at the outermost enclosing lexical scope." 88300b57cec5SDimitry Andric DeclContext *DC = CurContext; 88310b57cec5SDimitry Andric while (DC && isa<CapturedDecl>(DC)) 88320b57cec5SDimitry Andric DC = DC->getParent(); 88330b57cec5SDimitry Andric const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); 88340b57cec5SDimitry Andric if (IsInLambdaDeclContext && CurrentLSI && 88350b57cec5SDimitry Andric CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) 88360b57cec5SDimitry Andric CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, 88370b57cec5SDimitry Andric *this); 88380b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(FullExpr); 88390b57cec5SDimitry Andric } 88400b57cec5SDimitry Andric 88410b57cec5SDimitry Andric StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 88420b57cec5SDimitry Andric if (!FullStmt) return StmtError(); 88430b57cec5SDimitry Andric 88440b57cec5SDimitry Andric return MaybeCreateStmtWithCleanups(FullStmt); 88450b57cec5SDimitry Andric } 88460b57cec5SDimitry Andric 88470b57cec5SDimitry Andric Sema::IfExistsResult 88480b57cec5SDimitry Andric Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 88490b57cec5SDimitry Andric CXXScopeSpec &SS, 88500b57cec5SDimitry Andric const DeclarationNameInfo &TargetNameInfo) { 88510b57cec5SDimitry Andric DeclarationName TargetName = TargetNameInfo.getName(); 88520b57cec5SDimitry Andric if (!TargetName) 88530b57cec5SDimitry Andric return IER_DoesNotExist; 88540b57cec5SDimitry Andric 88550b57cec5SDimitry Andric // If the name itself is dependent, then the result is dependent. 88560b57cec5SDimitry Andric if (TargetName.isDependentName()) 88570b57cec5SDimitry Andric return IER_Dependent; 88580b57cec5SDimitry Andric 88590b57cec5SDimitry Andric // Do the redeclaration lookup in the current scope. 88600b57cec5SDimitry Andric LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 88610b57cec5SDimitry Andric Sema::NotForRedeclaration); 88620b57cec5SDimitry Andric LookupParsedName(R, S, &SS); 88630b57cec5SDimitry Andric R.suppressDiagnostics(); 88640b57cec5SDimitry Andric 88650b57cec5SDimitry Andric switch (R.getResultKind()) { 88660b57cec5SDimitry Andric case LookupResult::Found: 88670b57cec5SDimitry Andric case LookupResult::FoundOverloaded: 88680b57cec5SDimitry Andric case LookupResult::FoundUnresolvedValue: 88690b57cec5SDimitry Andric case LookupResult::Ambiguous: 88700b57cec5SDimitry Andric return IER_Exists; 88710b57cec5SDimitry Andric 88720b57cec5SDimitry Andric case LookupResult::NotFound: 88730b57cec5SDimitry Andric return IER_DoesNotExist; 88740b57cec5SDimitry Andric 88750b57cec5SDimitry Andric case LookupResult::NotFoundInCurrentInstantiation: 88760b57cec5SDimitry Andric return IER_Dependent; 88770b57cec5SDimitry Andric } 88780b57cec5SDimitry Andric 88790b57cec5SDimitry Andric llvm_unreachable("Invalid LookupResult Kind!"); 88800b57cec5SDimitry Andric } 88810b57cec5SDimitry Andric 88820b57cec5SDimitry Andric Sema::IfExistsResult 88830b57cec5SDimitry Andric Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 88840b57cec5SDimitry Andric bool IsIfExists, CXXScopeSpec &SS, 88850b57cec5SDimitry Andric UnqualifiedId &Name) { 88860b57cec5SDimitry Andric DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 88870b57cec5SDimitry Andric 88880b57cec5SDimitry Andric // Check for an unexpanded parameter pack. 88890b57cec5SDimitry Andric auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; 88900b57cec5SDimitry Andric if (DiagnoseUnexpandedParameterPack(SS, UPPC) || 88910b57cec5SDimitry Andric DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) 88920b57cec5SDimitry Andric return IER_Error; 88930b57cec5SDimitry Andric 88940b57cec5SDimitry Andric return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 88950b57cec5SDimitry Andric } 889655e4f9d5SDimitry Andric 889755e4f9d5SDimitry Andric concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { 889855e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/true, 889955e4f9d5SDimitry Andric /*NoexceptLoc=*/SourceLocation(), 890055e4f9d5SDimitry Andric /*ReturnTypeRequirement=*/{}); 890155e4f9d5SDimitry Andric } 890255e4f9d5SDimitry Andric 890355e4f9d5SDimitry Andric concepts::Requirement * 890455e4f9d5SDimitry Andric Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, 890555e4f9d5SDimitry Andric SourceLocation NameLoc, IdentifierInfo *TypeName, 890655e4f9d5SDimitry Andric TemplateIdAnnotation *TemplateId) { 890755e4f9d5SDimitry Andric assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && 890855e4f9d5SDimitry Andric "Exactly one of TypeName and TemplateId must be specified."); 890955e4f9d5SDimitry Andric TypeSourceInfo *TSI = nullptr; 891055e4f9d5SDimitry Andric if (TypeName) { 891155e4f9d5SDimitry Andric QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc, 891255e4f9d5SDimitry Andric SS.getWithLocInContext(Context), *TypeName, 891304eeddc0SDimitry Andric NameLoc, &TSI, /*DeducedTSTContext=*/false); 891455e4f9d5SDimitry Andric if (T.isNull()) 891555e4f9d5SDimitry Andric return nullptr; 891655e4f9d5SDimitry Andric } else { 891755e4f9d5SDimitry Andric ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), 891855e4f9d5SDimitry Andric TemplateId->NumArgs); 891955e4f9d5SDimitry Andric TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS, 892055e4f9d5SDimitry Andric TemplateId->TemplateKWLoc, 892155e4f9d5SDimitry Andric TemplateId->Template, TemplateId->Name, 892255e4f9d5SDimitry Andric TemplateId->TemplateNameLoc, 892355e4f9d5SDimitry Andric TemplateId->LAngleLoc, ArgsPtr, 892455e4f9d5SDimitry Andric TemplateId->RAngleLoc); 892555e4f9d5SDimitry Andric if (T.isInvalid()) 892655e4f9d5SDimitry Andric return nullptr; 892755e4f9d5SDimitry Andric if (GetTypeFromParser(T.get(), &TSI).isNull()) 892855e4f9d5SDimitry Andric return nullptr; 892955e4f9d5SDimitry Andric } 893055e4f9d5SDimitry Andric return BuildTypeRequirement(TSI); 893155e4f9d5SDimitry Andric } 893255e4f9d5SDimitry Andric 893355e4f9d5SDimitry Andric concepts::Requirement * 893455e4f9d5SDimitry Andric Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { 893555e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, 893655e4f9d5SDimitry Andric /*ReturnTypeRequirement=*/{}); 893755e4f9d5SDimitry Andric } 893855e4f9d5SDimitry Andric 893955e4f9d5SDimitry Andric concepts::Requirement * 894055e4f9d5SDimitry Andric Sema::ActOnCompoundRequirement( 894155e4f9d5SDimitry Andric Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 894255e4f9d5SDimitry Andric TemplateIdAnnotation *TypeConstraint, unsigned Depth) { 894355e4f9d5SDimitry Andric // C++2a [expr.prim.req.compound] p1.3.3 894455e4f9d5SDimitry Andric // [..] the expression is deduced against an invented function template 894555e4f9d5SDimitry Andric // F [...] F is a void function template with a single type template 894655e4f9d5SDimitry Andric // parameter T declared with the constrained-parameter. Form a new 894755e4f9d5SDimitry Andric // cv-qualifier-seq cv by taking the union of const and volatile specifiers 894855e4f9d5SDimitry Andric // around the constrained-parameter. F has a single parameter whose 894955e4f9d5SDimitry Andric // type-specifier is cv T followed by the abstract-declarator. [...] 895055e4f9d5SDimitry Andric // 895155e4f9d5SDimitry Andric // The cv part is done in the calling function - we get the concept with 895255e4f9d5SDimitry Andric // arguments and the abstract declarator with the correct CV qualification and 895355e4f9d5SDimitry Andric // have to synthesize T and the single parameter of F. 895455e4f9d5SDimitry Andric auto &II = Context.Idents.get("expr-type"); 895555e4f9d5SDimitry Andric auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, 895655e4f9d5SDimitry Andric SourceLocation(), 895755e4f9d5SDimitry Andric SourceLocation(), Depth, 895855e4f9d5SDimitry Andric /*Index=*/0, &II, 895955e4f9d5SDimitry Andric /*Typename=*/true, 896055e4f9d5SDimitry Andric /*ParameterPack=*/false, 896155e4f9d5SDimitry Andric /*HasTypeConstraint=*/true); 896255e4f9d5SDimitry Andric 8963fe6060f1SDimitry Andric if (BuildTypeConstraint(SS, TypeConstraint, TParam, 896404eeddc0SDimitry Andric /*EllipsisLoc=*/SourceLocation(), 8965fe6060f1SDimitry Andric /*AllowUnexpandedPack=*/true)) 896655e4f9d5SDimitry Andric // Just produce a requirement with no type requirements. 896755e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {}); 896855e4f9d5SDimitry Andric 896955e4f9d5SDimitry Andric auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), 897055e4f9d5SDimitry Andric SourceLocation(), 897155e4f9d5SDimitry Andric ArrayRef<NamedDecl *>(TParam), 897255e4f9d5SDimitry Andric SourceLocation(), 897355e4f9d5SDimitry Andric /*RequiresClause=*/nullptr); 897455e4f9d5SDimitry Andric return BuildExprRequirement( 897555e4f9d5SDimitry Andric E, /*IsSimple=*/false, NoexceptLoc, 897655e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement(TPL)); 897755e4f9d5SDimitry Andric } 897855e4f9d5SDimitry Andric 897955e4f9d5SDimitry Andric concepts::ExprRequirement * 898055e4f9d5SDimitry Andric Sema::BuildExprRequirement( 898155e4f9d5SDimitry Andric Expr *E, bool IsSimple, SourceLocation NoexceptLoc, 898255e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 898355e4f9d5SDimitry Andric auto Status = concepts::ExprRequirement::SS_Satisfied; 898455e4f9d5SDimitry Andric ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; 898555e4f9d5SDimitry Andric if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent()) 898655e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_Dependent; 898755e4f9d5SDimitry Andric else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) 898855e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_NoexceptNotMet; 898955e4f9d5SDimitry Andric else if (ReturnTypeRequirement.isSubstitutionFailure()) 899055e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; 899155e4f9d5SDimitry Andric else if (ReturnTypeRequirement.isTypeConstraint()) { 899255e4f9d5SDimitry Andric // C++2a [expr.prim.req]p1.3.3 899355e4f9d5SDimitry Andric // The immediately-declared constraint ([temp]) of decltype((E)) shall 899455e4f9d5SDimitry Andric // be satisfied. 899555e4f9d5SDimitry Andric TemplateParameterList *TPL = 899655e4f9d5SDimitry Andric ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); 899755e4f9d5SDimitry Andric QualType MatchedType = 8998349cc55cSDimitry Andric Context.getReferenceQualifiedType(E).getCanonicalType(); 899955e4f9d5SDimitry Andric llvm::SmallVector<TemplateArgument, 1> Args; 900055e4f9d5SDimitry Andric Args.push_back(TemplateArgument(MatchedType)); 900155e4f9d5SDimitry Andric TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args); 900255e4f9d5SDimitry Andric MultiLevelTemplateArgumentList MLTAL(TAL); 900355e4f9d5SDimitry Andric for (unsigned I = 0; I < TPL->getDepth(); ++I) 900455e4f9d5SDimitry Andric MLTAL.addOuterRetainedLevel(); 900555e4f9d5SDimitry Andric Expr *IDC = 900655e4f9d5SDimitry Andric cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint() 900755e4f9d5SDimitry Andric ->getImmediatelyDeclaredConstraint(); 900855e4f9d5SDimitry Andric ExprResult Constraint = SubstExpr(IDC, MLTAL); 900955e4f9d5SDimitry Andric assert(!Constraint.isInvalid() && 901055e4f9d5SDimitry Andric "Substitution cannot fail as it is simply putting a type template " 901155e4f9d5SDimitry Andric "argument into a concept specialization expression's parameter."); 901255e4f9d5SDimitry Andric 901355e4f9d5SDimitry Andric SubstitutedConstraintExpr = 901455e4f9d5SDimitry Andric cast<ConceptSpecializationExpr>(Constraint.get()); 901555e4f9d5SDimitry Andric if (!SubstitutedConstraintExpr->isSatisfied()) 901655e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; 901755e4f9d5SDimitry Andric } 901855e4f9d5SDimitry Andric return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, 901955e4f9d5SDimitry Andric ReturnTypeRequirement, Status, 902055e4f9d5SDimitry Andric SubstitutedConstraintExpr); 902155e4f9d5SDimitry Andric } 902255e4f9d5SDimitry Andric 902355e4f9d5SDimitry Andric concepts::ExprRequirement * 902455e4f9d5SDimitry Andric Sema::BuildExprRequirement( 902555e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, 902655e4f9d5SDimitry Andric bool IsSimple, SourceLocation NoexceptLoc, 902755e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 902855e4f9d5SDimitry Andric return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, 902955e4f9d5SDimitry Andric IsSimple, NoexceptLoc, 903055e4f9d5SDimitry Andric ReturnTypeRequirement); 903155e4f9d5SDimitry Andric } 903255e4f9d5SDimitry Andric 903355e4f9d5SDimitry Andric concepts::TypeRequirement * 903455e4f9d5SDimitry Andric Sema::BuildTypeRequirement(TypeSourceInfo *Type) { 903555e4f9d5SDimitry Andric return new (Context) concepts::TypeRequirement(Type); 903655e4f9d5SDimitry Andric } 903755e4f9d5SDimitry Andric 903855e4f9d5SDimitry Andric concepts::TypeRequirement * 903955e4f9d5SDimitry Andric Sema::BuildTypeRequirement( 904055e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 904155e4f9d5SDimitry Andric return new (Context) concepts::TypeRequirement(SubstDiag); 904255e4f9d5SDimitry Andric } 904355e4f9d5SDimitry Andric 904455e4f9d5SDimitry Andric concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { 904555e4f9d5SDimitry Andric return BuildNestedRequirement(Constraint); 904655e4f9d5SDimitry Andric } 904755e4f9d5SDimitry Andric 904855e4f9d5SDimitry Andric concepts::NestedRequirement * 904955e4f9d5SDimitry Andric Sema::BuildNestedRequirement(Expr *Constraint) { 905055e4f9d5SDimitry Andric ConstraintSatisfaction Satisfaction; 905155e4f9d5SDimitry Andric if (!Constraint->isInstantiationDependent() && 905213138422SDimitry Andric CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{}, 905313138422SDimitry Andric Constraint->getSourceRange(), Satisfaction)) 905455e4f9d5SDimitry Andric return nullptr; 905555e4f9d5SDimitry Andric return new (Context) concepts::NestedRequirement(Context, Constraint, 905655e4f9d5SDimitry Andric Satisfaction); 905755e4f9d5SDimitry Andric } 905855e4f9d5SDimitry Andric 905955e4f9d5SDimitry Andric concepts::NestedRequirement * 906055e4f9d5SDimitry Andric Sema::BuildNestedRequirement( 906155e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 906255e4f9d5SDimitry Andric return new (Context) concepts::NestedRequirement(SubstDiag); 906355e4f9d5SDimitry Andric } 906455e4f9d5SDimitry Andric 906555e4f9d5SDimitry Andric RequiresExprBodyDecl * 906655e4f9d5SDimitry Andric Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 906755e4f9d5SDimitry Andric ArrayRef<ParmVarDecl *> LocalParameters, 906855e4f9d5SDimitry Andric Scope *BodyScope) { 906955e4f9d5SDimitry Andric assert(BodyScope); 907055e4f9d5SDimitry Andric 907155e4f9d5SDimitry Andric RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext, 907255e4f9d5SDimitry Andric RequiresKWLoc); 907355e4f9d5SDimitry Andric 907455e4f9d5SDimitry Andric PushDeclContext(BodyScope, Body); 907555e4f9d5SDimitry Andric 907655e4f9d5SDimitry Andric for (ParmVarDecl *Param : LocalParameters) { 907755e4f9d5SDimitry Andric if (Param->hasDefaultArg()) 907855e4f9d5SDimitry Andric // C++2a [expr.prim.req] p4 907955e4f9d5SDimitry Andric // [...] A local parameter of a requires-expression shall not have a 908055e4f9d5SDimitry Andric // default argument. [...] 908155e4f9d5SDimitry Andric Diag(Param->getDefaultArgRange().getBegin(), 908255e4f9d5SDimitry Andric diag::err_requires_expr_local_parameter_default_argument); 908355e4f9d5SDimitry Andric // Ignore default argument and move on 908455e4f9d5SDimitry Andric 908555e4f9d5SDimitry Andric Param->setDeclContext(Body); 908655e4f9d5SDimitry Andric // If this has an identifier, add it to the scope stack. 908755e4f9d5SDimitry Andric if (Param->getIdentifier()) { 908855e4f9d5SDimitry Andric CheckShadow(BodyScope, Param); 908955e4f9d5SDimitry Andric PushOnScopeChains(Param, BodyScope); 909055e4f9d5SDimitry Andric } 909155e4f9d5SDimitry Andric } 909255e4f9d5SDimitry Andric return Body; 909355e4f9d5SDimitry Andric } 909455e4f9d5SDimitry Andric 909555e4f9d5SDimitry Andric void Sema::ActOnFinishRequiresExpr() { 909655e4f9d5SDimitry Andric assert(CurContext && "DeclContext imbalance!"); 909755e4f9d5SDimitry Andric CurContext = CurContext->getLexicalParent(); 909855e4f9d5SDimitry Andric assert(CurContext && "Popped translation unit!"); 909955e4f9d5SDimitry Andric } 910055e4f9d5SDimitry Andric 910155e4f9d5SDimitry Andric ExprResult 910255e4f9d5SDimitry Andric Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc, 910355e4f9d5SDimitry Andric RequiresExprBodyDecl *Body, 910455e4f9d5SDimitry Andric ArrayRef<ParmVarDecl *> LocalParameters, 910555e4f9d5SDimitry Andric ArrayRef<concepts::Requirement *> Requirements, 910655e4f9d5SDimitry Andric SourceLocation ClosingBraceLoc) { 9107e8d8bef9SDimitry Andric auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters, 910855e4f9d5SDimitry Andric Requirements, ClosingBraceLoc); 9109e8d8bef9SDimitry Andric if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) 9110e8d8bef9SDimitry Andric return ExprError(); 9111e8d8bef9SDimitry Andric return RE; 911255e4f9d5SDimitry Andric } 9113