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 1455e4f9d5SDimitry Andric #include "clang/Sema/Template.h" 150b57cec5SDimitry Andric #include "clang/Sema/SemaInternal.h" 160b57cec5SDimitry Andric #include "TreeTransform.h" 170b57cec5SDimitry Andric #include "TypeLocBuilder.h" 180b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 190b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h" 200b57cec5SDimitry Andric #include "clang/AST/CXXInheritance.h" 210b57cec5SDimitry Andric #include "clang/AST/CharUnits.h" 220b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 230b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h" 240b57cec5SDimitry Andric #include "clang/AST/ExprObjC.h" 250b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 260b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h" 270b57cec5SDimitry Andric #include "clang/Basic/AlignedAllocation.h" 280b57cec5SDimitry Andric #include "clang/Basic/PartialDiagnostic.h" 290b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.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" 370b57cec5SDimitry Andric #include "clang/Sema/SemaLambda.h" 380b57cec5SDimitry Andric #include "clang/Sema/TemplateDeduction.h" 390b57cec5SDimitry Andric #include "llvm/ADT/APInt.h" 400b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 410b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 420b57cec5SDimitry Andric using namespace clang; 430b57cec5SDimitry Andric using namespace sema; 440b57cec5SDimitry Andric 450b57cec5SDimitry Andric /// Handle the result of the special case name lookup for inheriting 460b57cec5SDimitry Andric /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as 470b57cec5SDimitry Andric /// constructor names in member using declarations, even if 'X' is not the 480b57cec5SDimitry Andric /// name of the corresponding type. 490b57cec5SDimitry Andric ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, 500b57cec5SDimitry Andric SourceLocation NameLoc, 510b57cec5SDimitry Andric IdentifierInfo &Name) { 520b57cec5SDimitry Andric NestedNameSpecifier *NNS = SS.getScopeRep(); 530b57cec5SDimitry Andric 540b57cec5SDimitry Andric // Convert the nested-name-specifier into a type. 550b57cec5SDimitry Andric QualType Type; 560b57cec5SDimitry Andric switch (NNS->getKind()) { 570b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpec: 580b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpecWithTemplate: 590b57cec5SDimitry Andric Type = QualType(NNS->getAsType(), 0); 600b57cec5SDimitry Andric break; 610b57cec5SDimitry Andric 620b57cec5SDimitry Andric case NestedNameSpecifier::Identifier: 630b57cec5SDimitry Andric // Strip off the last layer of the nested-name-specifier and build a 640b57cec5SDimitry Andric // typename type for it. 650b57cec5SDimitry Andric assert(NNS->getAsIdentifier() == &Name && "not a constructor name"); 660b57cec5SDimitry Andric Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(), 670b57cec5SDimitry Andric NNS->getAsIdentifier()); 680b57cec5SDimitry Andric break; 690b57cec5SDimitry Andric 700b57cec5SDimitry Andric case NestedNameSpecifier::Global: 710b57cec5SDimitry Andric case NestedNameSpecifier::Super: 720b57cec5SDimitry Andric case NestedNameSpecifier::Namespace: 730b57cec5SDimitry Andric case NestedNameSpecifier::NamespaceAlias: 740b57cec5SDimitry Andric llvm_unreachable("Nested name specifier is not a type for inheriting ctor"); 750b57cec5SDimitry Andric } 760b57cec5SDimitry Andric 770b57cec5SDimitry Andric // This reference to the type is located entirely at the location of the 780b57cec5SDimitry Andric // final identifier in the qualified-id. 790b57cec5SDimitry Andric return CreateParsedType(Type, 800b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(Type, NameLoc)); 810b57cec5SDimitry Andric } 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric ParsedType Sema::getConstructorName(IdentifierInfo &II, 840b57cec5SDimitry Andric SourceLocation NameLoc, 850b57cec5SDimitry Andric Scope *S, CXXScopeSpec &SS, 860b57cec5SDimitry Andric bool EnteringContext) { 870b57cec5SDimitry Andric CXXRecordDecl *CurClass = getCurrentClass(S, &SS); 880b57cec5SDimitry Andric assert(CurClass && &II == CurClass->getIdentifier() && 890b57cec5SDimitry Andric "not a constructor name"); 900b57cec5SDimitry Andric 910b57cec5SDimitry Andric // When naming a constructor as a member of a dependent context (eg, in a 920b57cec5SDimitry Andric // friend declaration or an inherited constructor declaration), form an 930b57cec5SDimitry Andric // unresolved "typename" type. 940b57cec5SDimitry Andric if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { 950b57cec5SDimitry Andric QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II); 960b57cec5SDimitry Andric return ParsedType::make(T); 970b57cec5SDimitry Andric } 980b57cec5SDimitry Andric 990b57cec5SDimitry Andric if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) 1000b57cec5SDimitry Andric return ParsedType(); 1010b57cec5SDimitry Andric 1020b57cec5SDimitry Andric // Find the injected-class-name declaration. Note that we make no attempt to 1030b57cec5SDimitry Andric // diagnose cases where the injected-class-name is shadowed: the only 1040b57cec5SDimitry Andric // declaration that can validly shadow the injected-class-name is a 1050b57cec5SDimitry Andric // non-static data member, and if the class contains both a non-static data 1060b57cec5SDimitry Andric // member and a constructor then it is ill-formed (we check that in 1070b57cec5SDimitry Andric // CheckCompletedCXXClass). 1080b57cec5SDimitry Andric CXXRecordDecl *InjectedClassName = nullptr; 1090b57cec5SDimitry Andric for (NamedDecl *ND : CurClass->lookup(&II)) { 1100b57cec5SDimitry Andric auto *RD = dyn_cast<CXXRecordDecl>(ND); 1110b57cec5SDimitry Andric if (RD && RD->isInjectedClassName()) { 1120b57cec5SDimitry Andric InjectedClassName = RD; 1130b57cec5SDimitry Andric break; 1140b57cec5SDimitry Andric } 1150b57cec5SDimitry Andric } 1160b57cec5SDimitry Andric if (!InjectedClassName) { 1170b57cec5SDimitry Andric if (!CurClass->isInvalidDecl()) { 1180b57cec5SDimitry Andric // FIXME: RequireCompleteDeclContext doesn't check dependent contexts 1190b57cec5SDimitry Andric // properly. Work around it here for now. 1200b57cec5SDimitry Andric Diag(SS.getLastQualifierNameLoc(), 1210b57cec5SDimitry Andric diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); 1220b57cec5SDimitry Andric } 1230b57cec5SDimitry Andric return ParsedType(); 1240b57cec5SDimitry Andric } 1250b57cec5SDimitry Andric 1260b57cec5SDimitry Andric QualType T = Context.getTypeDeclType(InjectedClassName); 1270b57cec5SDimitry Andric DiagnoseUseOfDecl(InjectedClassName, NameLoc); 1280b57cec5SDimitry Andric MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); 1290b57cec5SDimitry Andric 1300b57cec5SDimitry Andric return ParsedType::make(T); 1310b57cec5SDimitry Andric } 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric ParsedType Sema::getDestructorName(SourceLocation TildeLoc, 1340b57cec5SDimitry Andric IdentifierInfo &II, 1350b57cec5SDimitry Andric SourceLocation NameLoc, 1360b57cec5SDimitry Andric Scope *S, CXXScopeSpec &SS, 1370b57cec5SDimitry Andric ParsedType ObjectTypePtr, 1380b57cec5SDimitry Andric bool EnteringContext) { 1390b57cec5SDimitry Andric // Determine where to perform name lookup. 1400b57cec5SDimitry Andric 1410b57cec5SDimitry Andric // FIXME: This area of the standard is very messy, and the current 1420b57cec5SDimitry Andric // wording is rather unclear about which scopes we search for the 1430b57cec5SDimitry Andric // destructor name; see core issues 399 and 555. Issue 399 in 1440b57cec5SDimitry Andric // particular shows where the current description of destructor name 1450b57cec5SDimitry Andric // lookup is completely out of line with existing practice, e.g., 1460b57cec5SDimitry Andric // this appears to be ill-formed: 1470b57cec5SDimitry Andric // 1480b57cec5SDimitry Andric // namespace N { 1490b57cec5SDimitry Andric // template <typename T> struct S { 1500b57cec5SDimitry Andric // ~S(); 1510b57cec5SDimitry Andric // }; 1520b57cec5SDimitry Andric // } 1530b57cec5SDimitry Andric // 1540b57cec5SDimitry Andric // void f(N::S<int>* s) { 1550b57cec5SDimitry Andric // s->N::S<int>::~S(); 1560b57cec5SDimitry Andric // } 1570b57cec5SDimitry Andric // 1580b57cec5SDimitry Andric // See also PR6358 and PR6359. 1595ffd83dbSDimitry Andric // 1605ffd83dbSDimitry Andric // For now, we accept all the cases in which the name given could plausibly 1615ffd83dbSDimitry Andric // be interpreted as a correct destructor name, issuing off-by-default 1625ffd83dbSDimitry Andric // extension diagnostics on the cases that don't strictly conform to the 1635ffd83dbSDimitry Andric // C++20 rules. This basically means we always consider looking in the 1645ffd83dbSDimitry Andric // nested-name-specifier prefix, the complete nested-name-specifier, and 1655ffd83dbSDimitry Andric // the scope, and accept if we find the expected type in any of the three 1665ffd83dbSDimitry Andric // places. 1670b57cec5SDimitry Andric 1680b57cec5SDimitry Andric if (SS.isInvalid()) 1690b57cec5SDimitry Andric return nullptr; 1700b57cec5SDimitry Andric 1715ffd83dbSDimitry Andric // Whether we've failed with a diagnostic already. 1725ffd83dbSDimitry Andric bool Failed = false; 1735ffd83dbSDimitry Andric 1745ffd83dbSDimitry Andric llvm::SmallVector<NamedDecl*, 8> FoundDecls; 175e8d8bef9SDimitry Andric llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; 1765ffd83dbSDimitry Andric 1770b57cec5SDimitry Andric // If we have an object type, it's because we are in a 1780b57cec5SDimitry Andric // pseudo-destructor-expression or a member access expression, and 1790b57cec5SDimitry Andric // we know what type we're looking for. 1805ffd83dbSDimitry Andric QualType SearchType = 1815ffd83dbSDimitry Andric ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType(); 1820b57cec5SDimitry Andric 1835ffd83dbSDimitry Andric auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { 1845ffd83dbSDimitry Andric auto IsAcceptableResult = [&](NamedDecl *D) -> bool { 1855ffd83dbSDimitry Andric auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl()); 1865ffd83dbSDimitry Andric if (!Type) 1875ffd83dbSDimitry Andric return false; 1880b57cec5SDimitry Andric 1895ffd83dbSDimitry Andric if (SearchType.isNull() || SearchType->isDependentType()) 1905ffd83dbSDimitry Andric return true; 1915ffd83dbSDimitry Andric 1925ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(Type); 1935ffd83dbSDimitry Andric return Context.hasSameUnqualifiedType(T, SearchType); 1945ffd83dbSDimitry Andric }; 1955ffd83dbSDimitry Andric 1965ffd83dbSDimitry Andric unsigned NumAcceptableResults = 0; 1975ffd83dbSDimitry Andric for (NamedDecl *D : Found) { 1985ffd83dbSDimitry Andric if (IsAcceptableResult(D)) 1995ffd83dbSDimitry Andric ++NumAcceptableResults; 2005ffd83dbSDimitry Andric 2015ffd83dbSDimitry Andric // Don't list a class twice in the lookup failure diagnostic if it's 2025ffd83dbSDimitry Andric // found by both its injected-class-name and by the name in the enclosing 2035ffd83dbSDimitry Andric // scope. 2045ffd83dbSDimitry Andric if (auto *RD = dyn_cast<CXXRecordDecl>(D)) 2055ffd83dbSDimitry Andric if (RD->isInjectedClassName()) 2065ffd83dbSDimitry Andric D = cast<NamedDecl>(RD->getParent()); 2075ffd83dbSDimitry Andric 2085ffd83dbSDimitry Andric if (FoundDeclSet.insert(D).second) 2095ffd83dbSDimitry Andric FoundDecls.push_back(D); 2100b57cec5SDimitry Andric } 2110b57cec5SDimitry Andric 2125ffd83dbSDimitry Andric // As an extension, attempt to "fix" an ambiguity by erasing all non-type 2135ffd83dbSDimitry Andric // results, and all non-matching results if we have a search type. It's not 2145ffd83dbSDimitry Andric // clear what the right behavior is if destructor lookup hits an ambiguity, 2155ffd83dbSDimitry Andric // but other compilers do generally accept at least some kinds of 2165ffd83dbSDimitry Andric // ambiguity. 2175ffd83dbSDimitry Andric if (Found.isAmbiguous() && NumAcceptableResults == 1) { 2185ffd83dbSDimitry Andric Diag(NameLoc, diag::ext_dtor_name_ambiguous); 2195ffd83dbSDimitry Andric LookupResult::Filter F = Found.makeFilter(); 2205ffd83dbSDimitry Andric while (F.hasNext()) { 2215ffd83dbSDimitry Andric NamedDecl *D = F.next(); 2225ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) 2235ffd83dbSDimitry Andric Diag(D->getLocation(), diag::note_destructor_type_here) 2245ffd83dbSDimitry Andric << Context.getTypeDeclType(TD); 2255ffd83dbSDimitry Andric else 2265ffd83dbSDimitry Andric Diag(D->getLocation(), diag::note_destructor_nontype_here); 2275ffd83dbSDimitry Andric 2285ffd83dbSDimitry Andric if (!IsAcceptableResult(D)) 2295ffd83dbSDimitry Andric F.erase(); 2300b57cec5SDimitry Andric } 2315ffd83dbSDimitry Andric F.done(); 2325ffd83dbSDimitry Andric } 2335ffd83dbSDimitry Andric 2345ffd83dbSDimitry Andric if (Found.isAmbiguous()) 2355ffd83dbSDimitry Andric Failed = true; 2365ffd83dbSDimitry Andric 2375ffd83dbSDimitry Andric if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 2385ffd83dbSDimitry Andric if (IsAcceptableResult(Type)) { 2395ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(Type); 2405ffd83dbSDimitry Andric MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 2415ffd83dbSDimitry Andric return CreateParsedType(T, 2425ffd83dbSDimitry Andric Context.getTrivialTypeSourceInfo(T, NameLoc)); 2435ffd83dbSDimitry Andric } 2445ffd83dbSDimitry Andric } 2455ffd83dbSDimitry Andric 2465ffd83dbSDimitry Andric return nullptr; 2475ffd83dbSDimitry Andric }; 2485ffd83dbSDimitry Andric 2495ffd83dbSDimitry Andric bool IsDependent = false; 2505ffd83dbSDimitry Andric 2515ffd83dbSDimitry Andric auto LookupInObjectType = [&]() -> ParsedType { 2525ffd83dbSDimitry Andric if (Failed || SearchType.isNull()) 2535ffd83dbSDimitry Andric return nullptr; 2545ffd83dbSDimitry Andric 2555ffd83dbSDimitry Andric IsDependent |= SearchType->isDependentType(); 2565ffd83dbSDimitry Andric 2575ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2585ffd83dbSDimitry Andric DeclContext *LookupCtx = computeDeclContext(SearchType); 2595ffd83dbSDimitry Andric if (!LookupCtx) 2605ffd83dbSDimitry Andric return nullptr; 2615ffd83dbSDimitry Andric LookupQualifiedName(Found, LookupCtx); 2625ffd83dbSDimitry Andric return CheckLookupResult(Found); 2635ffd83dbSDimitry Andric }; 2645ffd83dbSDimitry Andric 2655ffd83dbSDimitry Andric auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { 2665ffd83dbSDimitry Andric if (Failed) 2675ffd83dbSDimitry Andric return nullptr; 2685ffd83dbSDimitry Andric 2695ffd83dbSDimitry Andric IsDependent |= isDependentScopeSpecifier(LookupSS); 2705ffd83dbSDimitry Andric DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext); 2715ffd83dbSDimitry Andric if (!LookupCtx) 2725ffd83dbSDimitry Andric return nullptr; 2735ffd83dbSDimitry Andric 2745ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2755ffd83dbSDimitry Andric if (RequireCompleteDeclContext(LookupSS, LookupCtx)) { 2765ffd83dbSDimitry Andric Failed = true; 2775ffd83dbSDimitry Andric return nullptr; 2785ffd83dbSDimitry Andric } 2795ffd83dbSDimitry Andric LookupQualifiedName(Found, LookupCtx); 2805ffd83dbSDimitry Andric return CheckLookupResult(Found); 2815ffd83dbSDimitry Andric }; 2825ffd83dbSDimitry Andric 2835ffd83dbSDimitry Andric auto LookupInScope = [&]() -> ParsedType { 2845ffd83dbSDimitry Andric if (Failed || !S) 2855ffd83dbSDimitry Andric return nullptr; 2865ffd83dbSDimitry Andric 2875ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2885ffd83dbSDimitry Andric LookupName(Found, S); 2895ffd83dbSDimitry Andric return CheckLookupResult(Found); 2905ffd83dbSDimitry Andric }; 2915ffd83dbSDimitry Andric 2925ffd83dbSDimitry Andric // C++2a [basic.lookup.qual]p6: 2935ffd83dbSDimitry Andric // In a qualified-id of the form 2945ffd83dbSDimitry Andric // 2955ffd83dbSDimitry Andric // nested-name-specifier[opt] type-name :: ~ type-name 2965ffd83dbSDimitry Andric // 2975ffd83dbSDimitry Andric // the second type-name is looked up in the same scope as the first. 2985ffd83dbSDimitry Andric // 2995ffd83dbSDimitry Andric // We interpret this as meaning that if you do a dual-scope lookup for the 3005ffd83dbSDimitry Andric // first name, you also do a dual-scope lookup for the second name, per 3015ffd83dbSDimitry Andric // C++ [basic.lookup.classref]p4: 3025ffd83dbSDimitry Andric // 3035ffd83dbSDimitry Andric // If the id-expression in a class member access is a qualified-id of the 3045ffd83dbSDimitry Andric // form 3055ffd83dbSDimitry Andric // 3065ffd83dbSDimitry Andric // class-name-or-namespace-name :: ... 3075ffd83dbSDimitry Andric // 3085ffd83dbSDimitry Andric // the class-name-or-namespace-name following the . or -> is first looked 3095ffd83dbSDimitry Andric // up in the class of the object expression and the name, if found, is used. 3105ffd83dbSDimitry Andric // Otherwise, it is looked up in the context of the entire 3115ffd83dbSDimitry Andric // postfix-expression. 3125ffd83dbSDimitry Andric // 3135ffd83dbSDimitry Andric // This looks in the same scopes as for an unqualified destructor name: 3145ffd83dbSDimitry Andric // 3150b57cec5SDimitry Andric // C++ [basic.lookup.classref]p3: 3160b57cec5SDimitry Andric // If the unqualified-id is ~ type-name, the type-name is looked up 3170b57cec5SDimitry Andric // in the context of the entire postfix-expression. If the type T 3180b57cec5SDimitry Andric // of the object expression is of a class type C, the type-name is 3190b57cec5SDimitry Andric // also looked up in the scope of class C. At least one of the 3205ffd83dbSDimitry Andric // lookups shall find a name that refers to cv T. 3215ffd83dbSDimitry Andric // 3225ffd83dbSDimitry Andric // FIXME: The intent is unclear here. Should type-name::~type-name look in 3235ffd83dbSDimitry Andric // the scope anyway if it finds a non-matching name declared in the class? 3245ffd83dbSDimitry Andric // If both lookups succeed and find a dependent result, which result should 3255ffd83dbSDimitry Andric // we retain? (Same question for p->~type-name().) 3260b57cec5SDimitry Andric 3275ffd83dbSDimitry Andric if (NestedNameSpecifier *Prefix = 3285ffd83dbSDimitry Andric SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { 3295ffd83dbSDimitry Andric // This is 3305ffd83dbSDimitry Andric // 3315ffd83dbSDimitry Andric // nested-name-specifier type-name :: ~ type-name 3325ffd83dbSDimitry Andric // 3335ffd83dbSDimitry Andric // Look for the second type-name in the nested-name-specifier. 3345ffd83dbSDimitry Andric CXXScopeSpec PrefixSS; 3355ffd83dbSDimitry Andric PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 3365ffd83dbSDimitry Andric if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) 3375ffd83dbSDimitry Andric return T; 3380b57cec5SDimitry Andric } else { 3395ffd83dbSDimitry Andric // This is one of 3405ffd83dbSDimitry Andric // 3415ffd83dbSDimitry Andric // type-name :: ~ type-name 3425ffd83dbSDimitry Andric // ~ type-name 3435ffd83dbSDimitry Andric // 3445ffd83dbSDimitry Andric // Look in the scope and (if any) the object type. 3455ffd83dbSDimitry Andric if (ParsedType T = LookupInScope()) 3465ffd83dbSDimitry Andric return T; 3475ffd83dbSDimitry Andric if (ParsedType T = LookupInObjectType()) 3485ffd83dbSDimitry Andric return T; 3490b57cec5SDimitry Andric } 3500b57cec5SDimitry Andric 3515ffd83dbSDimitry Andric if (Failed) 3520b57cec5SDimitry Andric return nullptr; 3530b57cec5SDimitry Andric 3545ffd83dbSDimitry Andric if (IsDependent) { 3555ffd83dbSDimitry Andric // We didn't find our type, but that's OK: it's dependent anyway. 3560b57cec5SDimitry Andric 3570b57cec5SDimitry Andric // FIXME: What if we have no nested-name-specifier? 3580b57cec5SDimitry Andric QualType T = CheckTypenameType(ETK_None, SourceLocation(), 3590b57cec5SDimitry Andric SS.getWithLocInContext(Context), 3600b57cec5SDimitry Andric II, NameLoc); 3610b57cec5SDimitry Andric return ParsedType::make(T); 3620b57cec5SDimitry Andric } 3630b57cec5SDimitry Andric 3645ffd83dbSDimitry Andric // The remaining cases are all non-standard extensions imitating the behavior 3655ffd83dbSDimitry Andric // of various other compilers. 3665ffd83dbSDimitry Andric unsigned NumNonExtensionDecls = FoundDecls.size(); 3675ffd83dbSDimitry Andric 3685ffd83dbSDimitry Andric if (SS.isSet()) { 3695ffd83dbSDimitry Andric // For compatibility with older broken C++ rules and existing code, 3705ffd83dbSDimitry Andric // 3715ffd83dbSDimitry Andric // nested-name-specifier :: ~ type-name 3725ffd83dbSDimitry Andric // 3735ffd83dbSDimitry Andric // also looks for type-name within the nested-name-specifier. 3745ffd83dbSDimitry Andric if (ParsedType T = LookupInNestedNameSpec(SS)) { 3755ffd83dbSDimitry Andric Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) 3765ffd83dbSDimitry Andric << SS.getRange() 3775ffd83dbSDimitry Andric << FixItHint::CreateInsertion(SS.getEndLoc(), 3785ffd83dbSDimitry Andric ("::" + II.getName()).str()); 3795ffd83dbSDimitry Andric return T; 3800b57cec5SDimitry Andric } 3815ffd83dbSDimitry Andric 3825ffd83dbSDimitry Andric // For compatibility with other compilers and older versions of Clang, 3835ffd83dbSDimitry Andric // 3845ffd83dbSDimitry Andric // nested-name-specifier type-name :: ~ type-name 3855ffd83dbSDimitry Andric // 3865ffd83dbSDimitry Andric // also looks for type-name in the scope. Unfortunately, we can't 3875ffd83dbSDimitry Andric // reasonably apply this fallback for dependent nested-name-specifiers. 3885ffd83dbSDimitry Andric if (SS.getScopeRep()->getPrefix()) { 3895ffd83dbSDimitry Andric if (ParsedType T = LookupInScope()) { 3905ffd83dbSDimitry Andric Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) 3915ffd83dbSDimitry Andric << FixItHint::CreateRemoval(SS.getRange()); 3925ffd83dbSDimitry Andric Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) 3935ffd83dbSDimitry Andric << GetTypeFromParser(T); 3945ffd83dbSDimitry Andric return T; 3955ffd83dbSDimitry Andric } 3965ffd83dbSDimitry Andric } 3975ffd83dbSDimitry Andric } 3985ffd83dbSDimitry Andric 3995ffd83dbSDimitry Andric // We didn't find anything matching; tell the user what we did find (if 4005ffd83dbSDimitry Andric // anything). 4015ffd83dbSDimitry Andric 4025ffd83dbSDimitry Andric // Don't tell the user about declarations we shouldn't have found. 4035ffd83dbSDimitry Andric FoundDecls.resize(NumNonExtensionDecls); 4045ffd83dbSDimitry Andric 4055ffd83dbSDimitry Andric // List types before non-types. 4065ffd83dbSDimitry Andric std::stable_sort(FoundDecls.begin(), FoundDecls.end(), 4075ffd83dbSDimitry Andric [](NamedDecl *A, NamedDecl *B) { 4085ffd83dbSDimitry Andric return isa<TypeDecl>(A->getUnderlyingDecl()) > 4095ffd83dbSDimitry Andric isa<TypeDecl>(B->getUnderlyingDecl()); 4105ffd83dbSDimitry Andric }); 4115ffd83dbSDimitry Andric 4125ffd83dbSDimitry Andric // Suggest a fixit to properly name the destroyed type. 4135ffd83dbSDimitry Andric auto MakeFixItHint = [&]{ 4145ffd83dbSDimitry Andric const CXXRecordDecl *Destroyed = nullptr; 4155ffd83dbSDimitry Andric // FIXME: If we have a scope specifier, suggest its last component? 4165ffd83dbSDimitry Andric if (!SearchType.isNull()) 4175ffd83dbSDimitry Andric Destroyed = SearchType->getAsCXXRecordDecl(); 4185ffd83dbSDimitry Andric else if (S) 4195ffd83dbSDimitry Andric Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity()); 4205ffd83dbSDimitry Andric if (Destroyed) 4215ffd83dbSDimitry Andric return FixItHint::CreateReplacement(SourceRange(NameLoc), 4225ffd83dbSDimitry Andric Destroyed->getNameAsString()); 4235ffd83dbSDimitry Andric return FixItHint(); 4245ffd83dbSDimitry Andric }; 4255ffd83dbSDimitry Andric 4265ffd83dbSDimitry Andric if (FoundDecls.empty()) { 4275ffd83dbSDimitry Andric // FIXME: Attempt typo-correction? 4285ffd83dbSDimitry Andric Diag(NameLoc, diag::err_undeclared_destructor_name) 4295ffd83dbSDimitry Andric << &II << MakeFixItHint(); 4305ffd83dbSDimitry Andric } else if (!SearchType.isNull() && FoundDecls.size() == 1) { 4315ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) { 4325ffd83dbSDimitry Andric assert(!SearchType.isNull() && 4335ffd83dbSDimitry Andric "should only reject a type result if we have a search type"); 4345ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(TD); 4355ffd83dbSDimitry Andric Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 4365ffd83dbSDimitry Andric << T << SearchType << MakeFixItHint(); 4375ffd83dbSDimitry Andric } else { 4385ffd83dbSDimitry Andric Diag(NameLoc, diag::err_destructor_expr_nontype) 4395ffd83dbSDimitry Andric << &II << MakeFixItHint(); 4405ffd83dbSDimitry Andric } 4415ffd83dbSDimitry Andric } else { 4425ffd83dbSDimitry Andric Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype 4435ffd83dbSDimitry Andric : diag::err_destructor_expr_mismatch) 4445ffd83dbSDimitry Andric << &II << SearchType << MakeFixItHint(); 4455ffd83dbSDimitry Andric } 4465ffd83dbSDimitry Andric 4475ffd83dbSDimitry Andric for (NamedDecl *FoundD : FoundDecls) { 4485ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) 4495ffd83dbSDimitry Andric Diag(FoundD->getLocation(), diag::note_destructor_type_here) 4505ffd83dbSDimitry Andric << Context.getTypeDeclType(TD); 4515ffd83dbSDimitry Andric else 4525ffd83dbSDimitry Andric Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) 4535ffd83dbSDimitry Andric << FoundD; 4540b57cec5SDimitry Andric } 4550b57cec5SDimitry Andric 4560b57cec5SDimitry Andric return nullptr; 4570b57cec5SDimitry Andric } 4580b57cec5SDimitry Andric 4590b57cec5SDimitry Andric ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, 4600b57cec5SDimitry Andric ParsedType ObjectType) { 4610b57cec5SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_error) 4620b57cec5SDimitry Andric return nullptr; 4630b57cec5SDimitry Andric 4640b57cec5SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { 4650b57cec5SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4660b57cec5SDimitry Andric return nullptr; 4670b57cec5SDimitry Andric } 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric assert(DS.getTypeSpecType() == DeclSpec::TST_decltype && 4700b57cec5SDimitry Andric "unexpected type in getDestructorType"); 4710b57cec5SDimitry Andric QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4720b57cec5SDimitry Andric 4730b57cec5SDimitry Andric // If we know the type of the object, check that the correct destructor 4740b57cec5SDimitry Andric // type was named now; we can give better diagnostics this way. 4750b57cec5SDimitry Andric QualType SearchType = GetTypeFromParser(ObjectType); 4760b57cec5SDimitry Andric if (!SearchType.isNull() && !SearchType->isDependentType() && 4770b57cec5SDimitry Andric !Context.hasSameUnqualifiedType(T, SearchType)) { 4780b57cec5SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 4790b57cec5SDimitry Andric << T << SearchType; 4800b57cec5SDimitry Andric return nullptr; 4810b57cec5SDimitry Andric } 4820b57cec5SDimitry Andric 4830b57cec5SDimitry Andric return ParsedType::make(T); 4840b57cec5SDimitry Andric } 4850b57cec5SDimitry Andric 4860b57cec5SDimitry Andric bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, 4870b57cec5SDimitry Andric const UnqualifiedId &Name) { 4880b57cec5SDimitry Andric assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); 4890b57cec5SDimitry Andric 4900b57cec5SDimitry Andric if (!SS.isValid()) 4910b57cec5SDimitry Andric return false; 4920b57cec5SDimitry Andric 4930b57cec5SDimitry Andric switch (SS.getScopeRep()->getKind()) { 4940b57cec5SDimitry Andric case NestedNameSpecifier::Identifier: 4950b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpec: 4960b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpecWithTemplate: 4970b57cec5SDimitry Andric // Per C++11 [over.literal]p2, literal operators can only be declared at 4980b57cec5SDimitry Andric // namespace scope. Therefore, this unqualified-id cannot name anything. 4990b57cec5SDimitry Andric // Reject it early, because we have no AST representation for this in the 5000b57cec5SDimitry Andric // case where the scope is dependent. 5010b57cec5SDimitry Andric Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) 5020b57cec5SDimitry Andric << SS.getScopeRep(); 5030b57cec5SDimitry Andric return true; 5040b57cec5SDimitry Andric 5050b57cec5SDimitry Andric case NestedNameSpecifier::Global: 5060b57cec5SDimitry Andric case NestedNameSpecifier::Super: 5070b57cec5SDimitry Andric case NestedNameSpecifier::Namespace: 5080b57cec5SDimitry Andric case NestedNameSpecifier::NamespaceAlias: 5090b57cec5SDimitry Andric return false; 5100b57cec5SDimitry Andric } 5110b57cec5SDimitry Andric 5120b57cec5SDimitry Andric llvm_unreachable("unknown nested name specifier kind"); 5130b57cec5SDimitry Andric } 5140b57cec5SDimitry Andric 5150b57cec5SDimitry Andric /// Build a C++ typeid expression with a type operand. 5160b57cec5SDimitry Andric ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 5170b57cec5SDimitry Andric SourceLocation TypeidLoc, 5180b57cec5SDimitry Andric TypeSourceInfo *Operand, 5190b57cec5SDimitry Andric SourceLocation RParenLoc) { 5200b57cec5SDimitry Andric // C++ [expr.typeid]p4: 5210b57cec5SDimitry Andric // The top-level cv-qualifiers of the lvalue expression or the type-id 5220b57cec5SDimitry Andric // that is the operand of typeid are always ignored. 5230b57cec5SDimitry Andric // If the type of the type-id is a class type or a reference to a class 5240b57cec5SDimitry Andric // type, the class shall be completely-defined. 5250b57cec5SDimitry Andric Qualifiers Quals; 5260b57cec5SDimitry Andric QualType T 5270b57cec5SDimitry Andric = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 5280b57cec5SDimitry Andric Quals); 5290b57cec5SDimitry Andric if (T->getAs<RecordType>() && 5300b57cec5SDimitry Andric RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 5310b57cec5SDimitry Andric return ExprError(); 5320b57cec5SDimitry Andric 5330b57cec5SDimitry Andric if (T->isVariablyModifiedType()) 5340b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); 5350b57cec5SDimitry Andric 536a7dea167SDimitry Andric if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) 537a7dea167SDimitry Andric return ExprError(); 538a7dea167SDimitry Andric 5390b57cec5SDimitry Andric return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, 5400b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 5410b57cec5SDimitry Andric } 5420b57cec5SDimitry Andric 5430b57cec5SDimitry Andric /// Build a C++ typeid expression with an expression operand. 5440b57cec5SDimitry Andric ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 5450b57cec5SDimitry Andric SourceLocation TypeidLoc, 5460b57cec5SDimitry Andric Expr *E, 5470b57cec5SDimitry Andric SourceLocation RParenLoc) { 5480b57cec5SDimitry Andric bool WasEvaluated = false; 5490b57cec5SDimitry Andric if (E && !E->isTypeDependent()) { 5500b57cec5SDimitry Andric if (E->getType()->isPlaceholderType()) { 5510b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(E); 5520b57cec5SDimitry Andric if (result.isInvalid()) return ExprError(); 5530b57cec5SDimitry Andric E = result.get(); 5540b57cec5SDimitry Andric } 5550b57cec5SDimitry Andric 5560b57cec5SDimitry Andric QualType T = E->getType(); 5570b57cec5SDimitry Andric if (const RecordType *RecordT = T->getAs<RecordType>()) { 5580b57cec5SDimitry Andric CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 5590b57cec5SDimitry Andric // C++ [expr.typeid]p3: 5600b57cec5SDimitry Andric // [...] If the type of the expression is a class type, the class 5610b57cec5SDimitry Andric // shall be completely-defined. 5620b57cec5SDimitry Andric if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 5630b57cec5SDimitry Andric return ExprError(); 5640b57cec5SDimitry Andric 5650b57cec5SDimitry Andric // C++ [expr.typeid]p3: 5660b57cec5SDimitry Andric // When typeid is applied to an expression other than an glvalue of a 5670b57cec5SDimitry Andric // polymorphic class type [...] [the] expression is an unevaluated 5680b57cec5SDimitry Andric // operand. [...] 5690b57cec5SDimitry Andric if (RecordD->isPolymorphic() && E->isGLValue()) { 5700b57cec5SDimitry Andric // The subexpression is potentially evaluated; switch the context 5710b57cec5SDimitry Andric // and recheck the subexpression. 5720b57cec5SDimitry Andric ExprResult Result = TransformToPotentiallyEvaluated(E); 5730b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 5740b57cec5SDimitry Andric E = Result.get(); 5750b57cec5SDimitry Andric 5760b57cec5SDimitry Andric // We require a vtable to query the type at run time. 5770b57cec5SDimitry Andric MarkVTableUsed(TypeidLoc, RecordD); 5780b57cec5SDimitry Andric WasEvaluated = true; 5790b57cec5SDimitry Andric } 5800b57cec5SDimitry Andric } 5810b57cec5SDimitry Andric 582a7dea167SDimitry Andric ExprResult Result = CheckUnevaluatedOperand(E); 583a7dea167SDimitry Andric if (Result.isInvalid()) 584a7dea167SDimitry Andric return ExprError(); 585a7dea167SDimitry Andric E = Result.get(); 586a7dea167SDimitry Andric 5870b57cec5SDimitry Andric // C++ [expr.typeid]p4: 5880b57cec5SDimitry Andric // [...] If the type of the type-id is a reference to a possibly 5890b57cec5SDimitry Andric // cv-qualified type, the result of the typeid expression refers to a 5900b57cec5SDimitry Andric // std::type_info object representing the cv-unqualified referenced 5910b57cec5SDimitry Andric // type. 5920b57cec5SDimitry Andric Qualifiers Quals; 5930b57cec5SDimitry Andric QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 5940b57cec5SDimitry Andric if (!Context.hasSameType(T, UnqualT)) { 5950b57cec5SDimitry Andric T = UnqualT; 5960b57cec5SDimitry Andric E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); 5970b57cec5SDimitry Andric } 5980b57cec5SDimitry Andric } 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric if (E->getType()->isVariablyModifiedType()) 6010b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) 6020b57cec5SDimitry Andric << E->getType()); 6030b57cec5SDimitry Andric else if (!inTemplateInstantiation() && 6040b57cec5SDimitry Andric E->HasSideEffects(Context, WasEvaluated)) { 6050b57cec5SDimitry Andric // The expression operand for typeid is in an unevaluated expression 6060b57cec5SDimitry Andric // context, so side effects could result in unintended consequences. 6070b57cec5SDimitry Andric Diag(E->getExprLoc(), WasEvaluated 6080b57cec5SDimitry Andric ? diag::warn_side_effects_typeid 6090b57cec5SDimitry Andric : diag::warn_side_effects_unevaluated_context); 6100b57cec5SDimitry Andric } 6110b57cec5SDimitry Andric 6120b57cec5SDimitry Andric return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, 6130b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 6140b57cec5SDimitry Andric } 6150b57cec5SDimitry Andric 6160b57cec5SDimitry Andric /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 6170b57cec5SDimitry Andric ExprResult 6180b57cec5SDimitry Andric Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 6190b57cec5SDimitry Andric bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 6200b57cec5SDimitry Andric // typeid is not supported in OpenCL. 6210b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) { 6220b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) 6230b57cec5SDimitry Andric << "typeid"); 6240b57cec5SDimitry Andric } 6250b57cec5SDimitry Andric 6260b57cec5SDimitry Andric // Find the std::type_info type. 6270b57cec5SDimitry Andric if (!getStdNamespace()) 6280b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 6290b57cec5SDimitry Andric 6300b57cec5SDimitry Andric if (!CXXTypeInfoDecl) { 6310b57cec5SDimitry Andric IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 6320b57cec5SDimitry Andric LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 6330b57cec5SDimitry Andric LookupQualifiedName(R, getStdNamespace()); 6340b57cec5SDimitry Andric CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 6350b57cec5SDimitry Andric // Microsoft's typeinfo doesn't have type_info in std but in the global 6360b57cec5SDimitry Andric // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. 6370b57cec5SDimitry Andric if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { 6380b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 6390b57cec5SDimitry Andric CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 6400b57cec5SDimitry Andric } 6410b57cec5SDimitry Andric if (!CXXTypeInfoDecl) 6420b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 6430b57cec5SDimitry Andric } 6440b57cec5SDimitry Andric 6450b57cec5SDimitry Andric if (!getLangOpts().RTTI) { 6460b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 6470b57cec5SDimitry Andric } 6480b57cec5SDimitry Andric 6490b57cec5SDimitry Andric QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 6500b57cec5SDimitry Andric 6510b57cec5SDimitry Andric if (isType) { 6520b57cec5SDimitry Andric // The operand is a type; handle it as such. 6530b57cec5SDimitry Andric TypeSourceInfo *TInfo = nullptr; 6540b57cec5SDimitry Andric QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 6550b57cec5SDimitry Andric &TInfo); 6560b57cec5SDimitry Andric if (T.isNull()) 6570b57cec5SDimitry Andric return ExprError(); 6580b57cec5SDimitry Andric 6590b57cec5SDimitry Andric if (!TInfo) 6600b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 6610b57cec5SDimitry Andric 6620b57cec5SDimitry Andric return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 6630b57cec5SDimitry Andric } 6640b57cec5SDimitry Andric 6650b57cec5SDimitry Andric // The operand is an expression. 666e8d8bef9SDimitry Andric ExprResult Result = 667e8d8bef9SDimitry Andric BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc); 668e8d8bef9SDimitry Andric 669e8d8bef9SDimitry Andric if (!getLangOpts().RTTIData && !Result.isInvalid()) 670e8d8bef9SDimitry Andric if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) 671e8d8bef9SDimitry Andric if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) 672e8d8bef9SDimitry Andric Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) 673e8d8bef9SDimitry Andric << (getDiagnostics().getDiagnosticOptions().getFormat() == 674e8d8bef9SDimitry Andric DiagnosticOptions::MSVC); 675e8d8bef9SDimitry Andric return Result; 6760b57cec5SDimitry Andric } 6770b57cec5SDimitry Andric 6780b57cec5SDimitry Andric /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to 6790b57cec5SDimitry Andric /// a single GUID. 6800b57cec5SDimitry Andric static void 6810b57cec5SDimitry Andric getUuidAttrOfType(Sema &SemaRef, QualType QT, 6820b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { 6830b57cec5SDimitry Andric // Optionally remove one level of pointer, reference or array indirection. 6840b57cec5SDimitry Andric const Type *Ty = QT.getTypePtr(); 6850b57cec5SDimitry Andric if (QT->isPointerType() || QT->isReferenceType()) 6860b57cec5SDimitry Andric Ty = QT->getPointeeType().getTypePtr(); 6870b57cec5SDimitry Andric else if (QT->isArrayType()) 6880b57cec5SDimitry Andric Ty = Ty->getBaseElementTypeUnsafe(); 6890b57cec5SDimitry Andric 6900b57cec5SDimitry Andric const auto *TD = Ty->getAsTagDecl(); 6910b57cec5SDimitry Andric if (!TD) 6920b57cec5SDimitry Andric return; 6930b57cec5SDimitry Andric 6940b57cec5SDimitry Andric if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { 6950b57cec5SDimitry Andric UuidAttrs.insert(Uuid); 6960b57cec5SDimitry Andric return; 6970b57cec5SDimitry Andric } 6980b57cec5SDimitry Andric 6990b57cec5SDimitry Andric // __uuidof can grab UUIDs from template arguments. 7000b57cec5SDimitry Andric if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { 7010b57cec5SDimitry Andric const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 7020b57cec5SDimitry Andric for (const TemplateArgument &TA : TAL.asArray()) { 7030b57cec5SDimitry Andric const UuidAttr *UuidForTA = nullptr; 7040b57cec5SDimitry Andric if (TA.getKind() == TemplateArgument::Type) 7050b57cec5SDimitry Andric getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); 7060b57cec5SDimitry Andric else if (TA.getKind() == TemplateArgument::Declaration) 7070b57cec5SDimitry Andric getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); 7080b57cec5SDimitry Andric 7090b57cec5SDimitry Andric if (UuidForTA) 7100b57cec5SDimitry Andric UuidAttrs.insert(UuidForTA); 7110b57cec5SDimitry Andric } 7120b57cec5SDimitry Andric } 7130b57cec5SDimitry Andric } 7140b57cec5SDimitry Andric 7150b57cec5SDimitry Andric /// Build a Microsoft __uuidof expression with a type operand. 7165ffd83dbSDimitry Andric ExprResult Sema::BuildCXXUuidof(QualType Type, 7170b57cec5SDimitry Andric SourceLocation TypeidLoc, 7180b57cec5SDimitry Andric TypeSourceInfo *Operand, 7190b57cec5SDimitry Andric SourceLocation RParenLoc) { 7205ffd83dbSDimitry Andric MSGuidDecl *Guid = nullptr; 7210b57cec5SDimitry Andric if (!Operand->getType()->isDependentType()) { 7220b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 7230b57cec5SDimitry Andric getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); 7240b57cec5SDimitry Andric if (UuidAttrs.empty()) 7250b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 7260b57cec5SDimitry Andric if (UuidAttrs.size() > 1) 7270b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 7285ffd83dbSDimitry Andric Guid = UuidAttrs.back()->getGuidDecl(); 7290b57cec5SDimitry Andric } 7300b57cec5SDimitry Andric 7315ffd83dbSDimitry Andric return new (Context) 7325ffd83dbSDimitry Andric CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); 7330b57cec5SDimitry Andric } 7340b57cec5SDimitry Andric 7350b57cec5SDimitry Andric /// Build a Microsoft __uuidof expression with an expression operand. 7365ffd83dbSDimitry Andric ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, 7375ffd83dbSDimitry Andric Expr *E, SourceLocation RParenLoc) { 7385ffd83dbSDimitry Andric MSGuidDecl *Guid = nullptr; 7390b57cec5SDimitry Andric if (!E->getType()->isDependentType()) { 7400b57cec5SDimitry Andric if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 7415ffd83dbSDimitry Andric // A null pointer results in {00000000-0000-0000-0000-000000000000}. 7425ffd83dbSDimitry Andric Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{}); 7430b57cec5SDimitry Andric } else { 7440b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 7450b57cec5SDimitry Andric getUuidAttrOfType(*this, E->getType(), UuidAttrs); 7460b57cec5SDimitry Andric if (UuidAttrs.empty()) 7470b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 7480b57cec5SDimitry Andric if (UuidAttrs.size() > 1) 7490b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 7505ffd83dbSDimitry Andric Guid = UuidAttrs.back()->getGuidDecl(); 7510b57cec5SDimitry Andric } 7520b57cec5SDimitry Andric } 7530b57cec5SDimitry Andric 7545ffd83dbSDimitry Andric return new (Context) 7555ffd83dbSDimitry Andric CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); 7560b57cec5SDimitry Andric } 7570b57cec5SDimitry Andric 7580b57cec5SDimitry Andric /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 7590b57cec5SDimitry Andric ExprResult 7600b57cec5SDimitry Andric Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 7610b57cec5SDimitry Andric bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 7625ffd83dbSDimitry Andric QualType GuidType = Context.getMSGuidType(); 7635ffd83dbSDimitry Andric GuidType.addConst(); 7640b57cec5SDimitry Andric 7650b57cec5SDimitry Andric if (isType) { 7660b57cec5SDimitry Andric // The operand is a type; handle it as such. 7670b57cec5SDimitry Andric TypeSourceInfo *TInfo = nullptr; 7680b57cec5SDimitry Andric QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 7690b57cec5SDimitry Andric &TInfo); 7700b57cec5SDimitry Andric if (T.isNull()) 7710b57cec5SDimitry Andric return ExprError(); 7720b57cec5SDimitry Andric 7730b57cec5SDimitry Andric if (!TInfo) 7740b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 7750b57cec5SDimitry Andric 7760b57cec5SDimitry Andric return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 7770b57cec5SDimitry Andric } 7780b57cec5SDimitry Andric 7790b57cec5SDimitry Andric // The operand is an expression. 7800b57cec5SDimitry Andric return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 7810b57cec5SDimitry Andric } 7820b57cec5SDimitry Andric 7830b57cec5SDimitry Andric /// ActOnCXXBoolLiteral - Parse {true,false} literals. 7840b57cec5SDimitry Andric ExprResult 7850b57cec5SDimitry Andric Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 7860b57cec5SDimitry Andric assert((Kind == tok::kw_true || Kind == tok::kw_false) && 7870b57cec5SDimitry Andric "Unknown C++ Boolean value!"); 7880b57cec5SDimitry Andric return new (Context) 7890b57cec5SDimitry Andric CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 7900b57cec5SDimitry Andric } 7910b57cec5SDimitry Andric 7920b57cec5SDimitry Andric /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 7930b57cec5SDimitry Andric ExprResult 7940b57cec5SDimitry Andric Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 7950b57cec5SDimitry Andric return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 7960b57cec5SDimitry Andric } 7970b57cec5SDimitry Andric 7980b57cec5SDimitry Andric /// ActOnCXXThrow - Parse throw expressions. 7990b57cec5SDimitry Andric ExprResult 8000b57cec5SDimitry Andric Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 8010b57cec5SDimitry Andric bool IsThrownVarInScope = false; 8020b57cec5SDimitry Andric if (Ex) { 8030b57cec5SDimitry Andric // C++0x [class.copymove]p31: 8040b57cec5SDimitry Andric // When certain criteria are met, an implementation is allowed to omit the 8050b57cec5SDimitry Andric // copy/move construction of a class object [...] 8060b57cec5SDimitry Andric // 8070b57cec5SDimitry Andric // - in a throw-expression, when the operand is the name of a 8080b57cec5SDimitry Andric // non-volatile automatic object (other than a function or catch- 8090b57cec5SDimitry Andric // clause parameter) whose scope does not extend beyond the end of the 8100b57cec5SDimitry Andric // innermost enclosing try-block (if there is one), the copy/move 8110b57cec5SDimitry Andric // operation from the operand to the exception object (15.1) can be 8120b57cec5SDimitry Andric // omitted by constructing the automatic object directly into the 8130b57cec5SDimitry Andric // exception object 8140b57cec5SDimitry Andric if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 8150b57cec5SDimitry Andric if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 8160b57cec5SDimitry Andric if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { 8170b57cec5SDimitry Andric for( ; S; S = S->getParent()) { 8180b57cec5SDimitry Andric if (S->isDeclScope(Var)) { 8190b57cec5SDimitry Andric IsThrownVarInScope = true; 8200b57cec5SDimitry Andric break; 8210b57cec5SDimitry Andric } 8220b57cec5SDimitry Andric 8230b57cec5SDimitry Andric if (S->getFlags() & 8240b57cec5SDimitry Andric (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 8250b57cec5SDimitry Andric Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | 8260b57cec5SDimitry Andric Scope::TryScope)) 8270b57cec5SDimitry Andric break; 8280b57cec5SDimitry Andric } 8290b57cec5SDimitry Andric } 8300b57cec5SDimitry Andric } 8310b57cec5SDimitry Andric } 8320b57cec5SDimitry Andric 8330b57cec5SDimitry Andric return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 8340b57cec5SDimitry Andric } 8350b57cec5SDimitry Andric 8360b57cec5SDimitry Andric ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 8370b57cec5SDimitry Andric bool IsThrownVarInScope) { 8380b57cec5SDimitry Andric // Don't report an error if 'throw' is used in system headers. 8390b57cec5SDimitry Andric if (!getLangOpts().CXXExceptions && 8400b57cec5SDimitry Andric !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { 8410b57cec5SDimitry Andric // Delay error emission for the OpenMP device code. 8420b57cec5SDimitry Andric targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; 8430b57cec5SDimitry Andric } 8440b57cec5SDimitry Andric 8450b57cec5SDimitry Andric // Exceptions aren't allowed in CUDA device code. 8460b57cec5SDimitry Andric if (getLangOpts().CUDA) 8470b57cec5SDimitry Andric CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) 8480b57cec5SDimitry Andric << "throw" << CurrentCUDATarget(); 8490b57cec5SDimitry Andric 8500b57cec5SDimitry Andric if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 8510b57cec5SDimitry Andric Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; 8520b57cec5SDimitry Andric 8530b57cec5SDimitry Andric if (Ex && !Ex->isTypeDependent()) { 8540b57cec5SDimitry Andric QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); 8550b57cec5SDimitry Andric if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) 8560b57cec5SDimitry Andric return ExprError(); 8570b57cec5SDimitry Andric 8580b57cec5SDimitry Andric // Initialize the exception result. This implicitly weeds out 8590b57cec5SDimitry Andric // abstract types or types with inaccessible copy constructors. 8600b57cec5SDimitry Andric 8610b57cec5SDimitry Andric // C++0x [class.copymove]p31: 8620b57cec5SDimitry Andric // When certain criteria are met, an implementation is allowed to omit the 8630b57cec5SDimitry Andric // copy/move construction of a class object [...] 8640b57cec5SDimitry Andric // 8650b57cec5SDimitry Andric // - in a throw-expression, when the operand is the name of a 8660b57cec5SDimitry Andric // non-volatile automatic object (other than a function or 8670b57cec5SDimitry Andric // catch-clause 8680b57cec5SDimitry Andric // parameter) whose scope does not extend beyond the end of the 8690b57cec5SDimitry Andric // innermost enclosing try-block (if there is one), the copy/move 8700b57cec5SDimitry Andric // operation from the operand to the exception object (15.1) can be 8710b57cec5SDimitry Andric // omitted by constructing the automatic object directly into the 8720b57cec5SDimitry Andric // exception object 8730b57cec5SDimitry Andric const VarDecl *NRVOVariable = nullptr; 8740b57cec5SDimitry Andric if (IsThrownVarInScope) 8750b57cec5SDimitry Andric NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict); 8760b57cec5SDimitry Andric 8770b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeException( 8780b57cec5SDimitry Andric OpLoc, ExceptionObjectTy, 8790b57cec5SDimitry Andric /*NRVO=*/NRVOVariable != nullptr); 8800b57cec5SDimitry Andric ExprResult Res = PerformMoveOrCopyInitialization( 8810b57cec5SDimitry Andric Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope); 8820b57cec5SDimitry Andric if (Res.isInvalid()) 8830b57cec5SDimitry Andric return ExprError(); 8840b57cec5SDimitry Andric Ex = Res.get(); 8850b57cec5SDimitry Andric } 8860b57cec5SDimitry Andric 887e8d8bef9SDimitry Andric // PPC MMA non-pointer types are not allowed as throw expr types. 888e8d8bef9SDimitry Andric if (Ex && Context.getTargetInfo().getTriple().isPPC64()) 889e8d8bef9SDimitry Andric CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc()); 890e8d8bef9SDimitry Andric 8910b57cec5SDimitry Andric return new (Context) 8920b57cec5SDimitry Andric CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); 8930b57cec5SDimitry Andric } 8940b57cec5SDimitry Andric 8950b57cec5SDimitry Andric static void 8960b57cec5SDimitry Andric collectPublicBases(CXXRecordDecl *RD, 8970b57cec5SDimitry Andric llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, 8980b57cec5SDimitry Andric llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, 8990b57cec5SDimitry Andric llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, 9000b57cec5SDimitry Andric bool ParentIsPublic) { 9010b57cec5SDimitry Andric for (const CXXBaseSpecifier &BS : RD->bases()) { 9020b57cec5SDimitry Andric CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 9030b57cec5SDimitry Andric bool NewSubobject; 9040b57cec5SDimitry Andric // Virtual bases constitute the same subobject. Non-virtual bases are 9050b57cec5SDimitry Andric // always distinct subobjects. 9060b57cec5SDimitry Andric if (BS.isVirtual()) 9070b57cec5SDimitry Andric NewSubobject = VBases.insert(BaseDecl).second; 9080b57cec5SDimitry Andric else 9090b57cec5SDimitry Andric NewSubobject = true; 9100b57cec5SDimitry Andric 9110b57cec5SDimitry Andric if (NewSubobject) 9120b57cec5SDimitry Andric ++SubobjectsSeen[BaseDecl]; 9130b57cec5SDimitry Andric 9140b57cec5SDimitry Andric // Only add subobjects which have public access throughout the entire chain. 9150b57cec5SDimitry Andric bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; 9160b57cec5SDimitry Andric if (PublicPath) 9170b57cec5SDimitry Andric PublicSubobjectsSeen.insert(BaseDecl); 9180b57cec5SDimitry Andric 9190b57cec5SDimitry Andric // Recurse on to each base subobject. 9200b57cec5SDimitry Andric collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, 9210b57cec5SDimitry Andric PublicPath); 9220b57cec5SDimitry Andric } 9230b57cec5SDimitry Andric } 9240b57cec5SDimitry Andric 9250b57cec5SDimitry Andric static void getUnambiguousPublicSubobjects( 9260b57cec5SDimitry Andric CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { 9270b57cec5SDimitry Andric llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; 9280b57cec5SDimitry Andric llvm::SmallSet<CXXRecordDecl *, 2> VBases; 9290b57cec5SDimitry Andric llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; 9300b57cec5SDimitry Andric SubobjectsSeen[RD] = 1; 9310b57cec5SDimitry Andric PublicSubobjectsSeen.insert(RD); 9320b57cec5SDimitry Andric collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, 9330b57cec5SDimitry Andric /*ParentIsPublic=*/true); 9340b57cec5SDimitry Andric 9350b57cec5SDimitry Andric for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { 9360b57cec5SDimitry Andric // Skip ambiguous objects. 9370b57cec5SDimitry Andric if (SubobjectsSeen[PublicSubobject] > 1) 9380b57cec5SDimitry Andric continue; 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric Objects.push_back(PublicSubobject); 9410b57cec5SDimitry Andric } 9420b57cec5SDimitry Andric } 9430b57cec5SDimitry Andric 9440b57cec5SDimitry Andric /// CheckCXXThrowOperand - Validate the operand of a throw. 9450b57cec5SDimitry Andric bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, 9460b57cec5SDimitry Andric QualType ExceptionObjectTy, Expr *E) { 9470b57cec5SDimitry Andric // If the type of the exception would be an incomplete type or a pointer 9480b57cec5SDimitry Andric // to an incomplete type other than (cv) void the program is ill-formed. 9490b57cec5SDimitry Andric QualType Ty = ExceptionObjectTy; 9500b57cec5SDimitry Andric bool isPointer = false; 9510b57cec5SDimitry Andric if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 9520b57cec5SDimitry Andric Ty = Ptr->getPointeeType(); 9530b57cec5SDimitry Andric isPointer = true; 9540b57cec5SDimitry Andric } 9550b57cec5SDimitry Andric if (!isPointer || !Ty->isVoidType()) { 9560b57cec5SDimitry Andric if (RequireCompleteType(ThrowLoc, Ty, 9570b57cec5SDimitry Andric isPointer ? diag::err_throw_incomplete_ptr 9580b57cec5SDimitry Andric : diag::err_throw_incomplete, 9590b57cec5SDimitry Andric E->getSourceRange())) 9600b57cec5SDimitry Andric return true; 9610b57cec5SDimitry Andric 9625ffd83dbSDimitry Andric if (!isPointer && Ty->isSizelessType()) { 9635ffd83dbSDimitry Andric Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); 9645ffd83dbSDimitry Andric return true; 9655ffd83dbSDimitry Andric } 9665ffd83dbSDimitry Andric 9670b57cec5SDimitry Andric if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, 9680b57cec5SDimitry Andric diag::err_throw_abstract_type, E)) 9690b57cec5SDimitry Andric return true; 9700b57cec5SDimitry Andric } 9710b57cec5SDimitry Andric 9720b57cec5SDimitry Andric // If the exception has class type, we need additional handling. 9730b57cec5SDimitry Andric CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9740b57cec5SDimitry Andric if (!RD) 9750b57cec5SDimitry Andric return false; 9760b57cec5SDimitry Andric 9770b57cec5SDimitry Andric // If we are throwing a polymorphic class type or pointer thereof, 9780b57cec5SDimitry Andric // exception handling will make use of the vtable. 9790b57cec5SDimitry Andric MarkVTableUsed(ThrowLoc, RD); 9800b57cec5SDimitry Andric 9810b57cec5SDimitry Andric // If a pointer is thrown, the referenced object will not be destroyed. 9820b57cec5SDimitry Andric if (isPointer) 9830b57cec5SDimitry Andric return false; 9840b57cec5SDimitry Andric 9850b57cec5SDimitry Andric // If the class has a destructor, we must be able to call it. 9860b57cec5SDimitry Andric if (!RD->hasIrrelevantDestructor()) { 9870b57cec5SDimitry Andric if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 9880b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), Destructor); 9890b57cec5SDimitry Andric CheckDestructorAccess(E->getExprLoc(), Destructor, 9900b57cec5SDimitry Andric PDiag(diag::err_access_dtor_exception) << Ty); 9910b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 9920b57cec5SDimitry Andric return true; 9930b57cec5SDimitry Andric } 9940b57cec5SDimitry Andric } 9950b57cec5SDimitry Andric 9960b57cec5SDimitry Andric // The MSVC ABI creates a list of all types which can catch the exception 9970b57cec5SDimitry Andric // object. This list also references the appropriate copy constructor to call 9980b57cec5SDimitry Andric // if the object is caught by value and has a non-trivial copy constructor. 9990b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 10000b57cec5SDimitry Andric // We are only interested in the public, unambiguous bases contained within 10010b57cec5SDimitry Andric // the exception object. Bases which are ambiguous or otherwise 10020b57cec5SDimitry Andric // inaccessible are not catchable types. 10030b57cec5SDimitry Andric llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; 10040b57cec5SDimitry Andric getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); 10050b57cec5SDimitry Andric 10060b57cec5SDimitry Andric for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { 10070b57cec5SDimitry Andric // Attempt to lookup the copy constructor. Various pieces of machinery 10080b57cec5SDimitry Andric // will spring into action, like template instantiation, which means this 10090b57cec5SDimitry Andric // cannot be a simple walk of the class's decls. Instead, we must perform 10100b57cec5SDimitry Andric // lookup and overload resolution. 10110b57cec5SDimitry Andric CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); 1012480093f4SDimitry Andric if (!CD || CD->isDeleted()) 10130b57cec5SDimitry Andric continue; 10140b57cec5SDimitry Andric 10150b57cec5SDimitry Andric // Mark the constructor referenced as it is used by this throw expression. 10160b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), CD); 10170b57cec5SDimitry Andric 10180b57cec5SDimitry Andric // Skip this copy constructor if it is trivial, we don't need to record it 10190b57cec5SDimitry Andric // in the catchable type data. 10200b57cec5SDimitry Andric if (CD->isTrivial()) 10210b57cec5SDimitry Andric continue; 10220b57cec5SDimitry Andric 10230b57cec5SDimitry Andric // The copy constructor is non-trivial, create a mapping from this class 10240b57cec5SDimitry Andric // type to this constructor. 10250b57cec5SDimitry Andric // N.B. The selection of copy constructor is not sensitive to this 10260b57cec5SDimitry Andric // particular throw-site. Lookup will be performed at the catch-site to 10270b57cec5SDimitry Andric // ensure that the copy constructor is, in fact, accessible (via 10280b57cec5SDimitry Andric // friendship or any other means). 10290b57cec5SDimitry Andric Context.addCopyConstructorForExceptionObject(Subobject, CD); 10300b57cec5SDimitry Andric 10310b57cec5SDimitry Andric // We don't keep the instantiated default argument expressions around so 10320b57cec5SDimitry Andric // we must rebuild them here. 10330b57cec5SDimitry Andric for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { 10340b57cec5SDimitry Andric if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) 10350b57cec5SDimitry Andric return true; 10360b57cec5SDimitry Andric } 10370b57cec5SDimitry Andric } 10380b57cec5SDimitry Andric } 10390b57cec5SDimitry Andric 10400b57cec5SDimitry Andric // Under the Itanium C++ ABI, memory for the exception object is allocated by 10410b57cec5SDimitry Andric // the runtime with no ability for the compiler to request additional 10420b57cec5SDimitry Andric // alignment. Warn if the exception type requires alignment beyond the minimum 10430b57cec5SDimitry Andric // guaranteed by the target C++ runtime. 10440b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { 10450b57cec5SDimitry Andric CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); 10460b57cec5SDimitry Andric CharUnits ExnObjAlign = Context.getExnObjectAlignment(); 10470b57cec5SDimitry Andric if (ExnObjAlign < TypeAlign) { 10480b57cec5SDimitry Andric Diag(ThrowLoc, diag::warn_throw_underaligned_obj); 10490b57cec5SDimitry Andric Diag(ThrowLoc, diag::note_throw_underaligned_obj) 10500b57cec5SDimitry Andric << Ty << (unsigned)TypeAlign.getQuantity() 10510b57cec5SDimitry Andric << (unsigned)ExnObjAlign.getQuantity(); 10520b57cec5SDimitry Andric } 10530b57cec5SDimitry Andric } 10540b57cec5SDimitry Andric 10550b57cec5SDimitry Andric return false; 10560b57cec5SDimitry Andric } 10570b57cec5SDimitry Andric 10580b57cec5SDimitry Andric static QualType adjustCVQualifiersForCXXThisWithinLambda( 10590b57cec5SDimitry Andric ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, 10600b57cec5SDimitry Andric DeclContext *CurSemaContext, ASTContext &ASTCtx) { 10610b57cec5SDimitry Andric 10620b57cec5SDimitry Andric QualType ClassType = ThisTy->getPointeeType(); 10630b57cec5SDimitry Andric LambdaScopeInfo *CurLSI = nullptr; 10640b57cec5SDimitry Andric DeclContext *CurDC = CurSemaContext; 10650b57cec5SDimitry Andric 10660b57cec5SDimitry Andric // Iterate through the stack of lambdas starting from the innermost lambda to 10670b57cec5SDimitry Andric // the outermost lambda, checking if '*this' is ever captured by copy - since 10680b57cec5SDimitry Andric // that could change the cv-qualifiers of the '*this' object. 10690b57cec5SDimitry Andric // The object referred to by '*this' starts out with the cv-qualifiers of its 10700b57cec5SDimitry Andric // member function. We then start with the innermost lambda and iterate 10710b57cec5SDimitry Andric // outward checking to see if any lambda performs a by-copy capture of '*this' 10720b57cec5SDimitry Andric // - and if so, any nested lambda must respect the 'constness' of that 10730b57cec5SDimitry Andric // capturing lamdbda's call operator. 10740b57cec5SDimitry Andric // 10750b57cec5SDimitry Andric 10760b57cec5SDimitry Andric // Since the FunctionScopeInfo stack is representative of the lexical 10770b57cec5SDimitry Andric // nesting of the lambda expressions during initial parsing (and is the best 10780b57cec5SDimitry Andric // place for querying information about captures about lambdas that are 10790b57cec5SDimitry Andric // partially processed) and perhaps during instantiation of function templates 10800b57cec5SDimitry Andric // that contain lambda expressions that need to be transformed BUT not 10810b57cec5SDimitry Andric // necessarily during instantiation of a nested generic lambda's function call 10820b57cec5SDimitry Andric // operator (which might even be instantiated at the end of the TU) - at which 10830b57cec5SDimitry Andric // time the DeclContext tree is mature enough to query capture information 10840b57cec5SDimitry Andric // reliably - we use a two pronged approach to walk through all the lexically 10850b57cec5SDimitry Andric // enclosing lambda expressions: 10860b57cec5SDimitry Andric // 10870b57cec5SDimitry Andric // 1) Climb down the FunctionScopeInfo stack as long as each item represents 10880b57cec5SDimitry Andric // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically 10890b57cec5SDimitry Andric // enclosed by the call-operator of the LSI below it on the stack (while 10900b57cec5SDimitry Andric // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on 10910b57cec5SDimitry Andric // the stack represents the innermost lambda. 10920b57cec5SDimitry Andric // 10930b57cec5SDimitry Andric // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext 10940b57cec5SDimitry Andric // represents a lambda's call operator. If it does, we must be instantiating 10950b57cec5SDimitry Andric // a generic lambda's call operator (represented by the Current LSI, and 10960b57cec5SDimitry Andric // should be the only scenario where an inconsistency between the LSI and the 10970b57cec5SDimitry Andric // DeclContext should occur), so climb out the DeclContexts if they 10980b57cec5SDimitry Andric // represent lambdas, while querying the corresponding closure types 10990b57cec5SDimitry Andric // regarding capture information. 11000b57cec5SDimitry Andric 11010b57cec5SDimitry Andric // 1) Climb down the function scope info stack. 11020b57cec5SDimitry Andric for (int I = FunctionScopes.size(); 11030b57cec5SDimitry Andric I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && 11040b57cec5SDimitry Andric (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == 11050b57cec5SDimitry Andric cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); 11060b57cec5SDimitry Andric CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { 11070b57cec5SDimitry Andric CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); 11080b57cec5SDimitry Andric 11090b57cec5SDimitry Andric if (!CurLSI->isCXXThisCaptured()) 11100b57cec5SDimitry Andric continue; 11110b57cec5SDimitry Andric 11120b57cec5SDimitry Andric auto C = CurLSI->getCXXThisCapture(); 11130b57cec5SDimitry Andric 11140b57cec5SDimitry Andric if (C.isCopyCapture()) { 11150b57cec5SDimitry Andric ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 11160b57cec5SDimitry Andric if (CurLSI->CallOperator->isConst()) 11170b57cec5SDimitry Andric ClassType.addConst(); 11180b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11190b57cec5SDimitry Andric } 11200b57cec5SDimitry Andric } 11210b57cec5SDimitry Andric 11220b57cec5SDimitry Andric // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can 11230b57cec5SDimitry Andric // happen during instantiation of its nested generic lambda call operator) 11240b57cec5SDimitry Andric if (isLambdaCallOperator(CurDC)) { 11250b57cec5SDimitry Andric assert(CurLSI && "While computing 'this' capture-type for a generic " 11260b57cec5SDimitry Andric "lambda, we must have a corresponding LambdaScopeInfo"); 11270b57cec5SDimitry Andric assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && 11280b57cec5SDimitry Andric "While computing 'this' capture-type for a generic lambda, when we " 11290b57cec5SDimitry Andric "run out of enclosing LSI's, yet the enclosing DC is a " 11300b57cec5SDimitry Andric "lambda-call-operator we must be (i.e. Current LSI) in a generic " 11310b57cec5SDimitry Andric "lambda call oeprator"); 11320b57cec5SDimitry Andric assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); 11330b57cec5SDimitry Andric 11340b57cec5SDimitry Andric auto IsThisCaptured = 11350b57cec5SDimitry Andric [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { 11360b57cec5SDimitry Andric IsConst = false; 11370b57cec5SDimitry Andric IsByCopy = false; 11380b57cec5SDimitry Andric for (auto &&C : Closure->captures()) { 11390b57cec5SDimitry Andric if (C.capturesThis()) { 11400b57cec5SDimitry Andric if (C.getCaptureKind() == LCK_StarThis) 11410b57cec5SDimitry Andric IsByCopy = true; 11420b57cec5SDimitry Andric if (Closure->getLambdaCallOperator()->isConst()) 11430b57cec5SDimitry Andric IsConst = true; 11440b57cec5SDimitry Andric return true; 11450b57cec5SDimitry Andric } 11460b57cec5SDimitry Andric } 11470b57cec5SDimitry Andric return false; 11480b57cec5SDimitry Andric }; 11490b57cec5SDimitry Andric 11500b57cec5SDimitry Andric bool IsByCopyCapture = false; 11510b57cec5SDimitry Andric bool IsConstCapture = false; 11520b57cec5SDimitry Andric CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); 11530b57cec5SDimitry Andric while (Closure && 11540b57cec5SDimitry Andric IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { 11550b57cec5SDimitry Andric if (IsByCopyCapture) { 11560b57cec5SDimitry Andric ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 11570b57cec5SDimitry Andric if (IsConstCapture) 11580b57cec5SDimitry Andric ClassType.addConst(); 11590b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11600b57cec5SDimitry Andric } 11610b57cec5SDimitry Andric Closure = isLambdaCallOperator(Closure->getParent()) 11620b57cec5SDimitry Andric ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) 11630b57cec5SDimitry Andric : nullptr; 11640b57cec5SDimitry Andric } 11650b57cec5SDimitry Andric } 11660b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11670b57cec5SDimitry Andric } 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric QualType Sema::getCurrentThisType() { 11700b57cec5SDimitry Andric DeclContext *DC = getFunctionLevelDeclContext(); 11710b57cec5SDimitry Andric QualType ThisTy = CXXThisTypeOverride; 11720b57cec5SDimitry Andric 11730b57cec5SDimitry Andric if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 11740b57cec5SDimitry Andric if (method && method->isInstance()) 11750b57cec5SDimitry Andric ThisTy = method->getThisType(); 11760b57cec5SDimitry Andric } 11770b57cec5SDimitry Andric 11780b57cec5SDimitry Andric if (ThisTy.isNull() && isLambdaCallOperator(CurContext) && 11790b57cec5SDimitry Andric inTemplateInstantiation()) { 11800b57cec5SDimitry Andric 11810b57cec5SDimitry Andric assert(isa<CXXRecordDecl>(DC) && 11820b57cec5SDimitry Andric "Trying to get 'this' type from static method?"); 11830b57cec5SDimitry Andric 11840b57cec5SDimitry Andric // This is a lambda call operator that is being instantiated as a default 11850b57cec5SDimitry Andric // initializer. DC must point to the enclosing class type, so we can recover 11860b57cec5SDimitry Andric // the 'this' type from it. 11870b57cec5SDimitry Andric 11880b57cec5SDimitry Andric QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); 11890b57cec5SDimitry Andric // There are no cv-qualifiers for 'this' within default initializers, 11900b57cec5SDimitry Andric // per [expr.prim.general]p4. 11910b57cec5SDimitry Andric ThisTy = Context.getPointerType(ClassTy); 11920b57cec5SDimitry Andric } 11930b57cec5SDimitry Andric 11940b57cec5SDimitry Andric // If we are within a lambda's call operator, the cv-qualifiers of 'this' 11950b57cec5SDimitry Andric // might need to be adjusted if the lambda or any of its enclosing lambda's 11960b57cec5SDimitry Andric // captures '*this' by copy. 11970b57cec5SDimitry Andric if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) 11980b57cec5SDimitry Andric return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, 11990b57cec5SDimitry Andric CurContext, Context); 12000b57cec5SDimitry Andric return ThisTy; 12010b57cec5SDimitry Andric } 12020b57cec5SDimitry Andric 12030b57cec5SDimitry Andric Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 12040b57cec5SDimitry Andric Decl *ContextDecl, 12050b57cec5SDimitry Andric Qualifiers CXXThisTypeQuals, 12060b57cec5SDimitry Andric bool Enabled) 12070b57cec5SDimitry Andric : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 12080b57cec5SDimitry Andric { 12090b57cec5SDimitry Andric if (!Enabled || !ContextDecl) 12100b57cec5SDimitry Andric return; 12110b57cec5SDimitry Andric 12120b57cec5SDimitry Andric CXXRecordDecl *Record = nullptr; 12130b57cec5SDimitry Andric if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 12140b57cec5SDimitry Andric Record = Template->getTemplatedDecl(); 12150b57cec5SDimitry Andric else 12160b57cec5SDimitry Andric Record = cast<CXXRecordDecl>(ContextDecl); 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric QualType T = S.Context.getRecordType(Record); 12190b57cec5SDimitry Andric T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); 12200b57cec5SDimitry Andric 12210b57cec5SDimitry Andric S.CXXThisTypeOverride = S.Context.getPointerType(T); 12220b57cec5SDimitry Andric 12230b57cec5SDimitry Andric this->Enabled = true; 12240b57cec5SDimitry Andric } 12250b57cec5SDimitry Andric 12260b57cec5SDimitry Andric 12270b57cec5SDimitry Andric Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { 12280b57cec5SDimitry Andric if (Enabled) { 12290b57cec5SDimitry Andric S.CXXThisTypeOverride = OldCXXThisTypeOverride; 12300b57cec5SDimitry Andric } 12310b57cec5SDimitry Andric } 12320b57cec5SDimitry Andric 12330b57cec5SDimitry Andric bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, 12340b57cec5SDimitry Andric bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, 12350b57cec5SDimitry Andric const bool ByCopy) { 12360b57cec5SDimitry Andric // We don't need to capture this in an unevaluated context. 12370b57cec5SDimitry Andric if (isUnevaluatedContext() && !Explicit) 12380b57cec5SDimitry Andric return true; 12390b57cec5SDimitry Andric 12400b57cec5SDimitry Andric assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); 12410b57cec5SDimitry Andric 12420b57cec5SDimitry Andric const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12430b57cec5SDimitry Andric ? *FunctionScopeIndexToStopAt 12440b57cec5SDimitry Andric : FunctionScopes.size() - 1; 12450b57cec5SDimitry Andric 12460b57cec5SDimitry Andric // Check that we can capture the *enclosing object* (referred to by '*this') 12470b57cec5SDimitry Andric // by the capturing-entity/closure (lambda/block/etc) at 12480b57cec5SDimitry Andric // MaxFunctionScopesIndex-deep on the FunctionScopes stack. 12490b57cec5SDimitry Andric 12500b57cec5SDimitry Andric // Note: The *enclosing object* can only be captured by-value by a 12510b57cec5SDimitry Andric // closure that is a lambda, using the explicit notation: 12520b57cec5SDimitry Andric // [*this] { ... }. 12530b57cec5SDimitry Andric // Every other capture of the *enclosing object* results in its by-reference 12540b57cec5SDimitry Andric // capture. 12550b57cec5SDimitry Andric 12560b57cec5SDimitry Andric // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes 12570b57cec5SDimitry Andric // stack), we can capture the *enclosing object* only if: 12580b57cec5SDimitry Andric // - 'L' has an explicit byref or byval capture of the *enclosing object* 12590b57cec5SDimitry Andric // - or, 'L' has an implicit capture. 12600b57cec5SDimitry Andric // AND 12610b57cec5SDimitry Andric // -- there is no enclosing closure 12620b57cec5SDimitry Andric // -- or, there is some enclosing closure 'E' that has already captured the 12630b57cec5SDimitry Andric // *enclosing object*, and every intervening closure (if any) between 'E' 12640b57cec5SDimitry Andric // and 'L' can implicitly capture the *enclosing object*. 12650b57cec5SDimitry Andric // -- or, every enclosing closure can implicitly capture the 12660b57cec5SDimitry Andric // *enclosing object* 12670b57cec5SDimitry Andric 12680b57cec5SDimitry Andric 12690b57cec5SDimitry Andric unsigned NumCapturingClosures = 0; 12700b57cec5SDimitry Andric for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { 12710b57cec5SDimitry Andric if (CapturingScopeInfo *CSI = 12720b57cec5SDimitry Andric dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 12730b57cec5SDimitry Andric if (CSI->CXXThisCaptureIndex != 0) { 12740b57cec5SDimitry Andric // 'this' is already being captured; there isn't anything more to do. 12750b57cec5SDimitry Andric CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); 12760b57cec5SDimitry Andric break; 12770b57cec5SDimitry Andric } 12780b57cec5SDimitry Andric LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); 12790b57cec5SDimitry Andric if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 12800b57cec5SDimitry Andric // This context can't implicitly capture 'this'; fail out. 12810b57cec5SDimitry Andric if (BuildAndDiagnose) 12820b57cec5SDimitry Andric Diag(Loc, diag::err_this_capture) 12830b57cec5SDimitry Andric << (Explicit && idx == MaxFunctionScopesIndex); 12840b57cec5SDimitry Andric return true; 12850b57cec5SDimitry Andric } 12860b57cec5SDimitry Andric if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 12870b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 12880b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 12890b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || 12900b57cec5SDimitry Andric (Explicit && idx == MaxFunctionScopesIndex)) { 12910b57cec5SDimitry Andric // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first 12920b57cec5SDimitry Andric // iteration through can be an explicit capture, all enclosing closures, 12930b57cec5SDimitry Andric // if any, must perform implicit captures. 12940b57cec5SDimitry Andric 12950b57cec5SDimitry Andric // This closure can capture 'this'; continue looking upwards. 12960b57cec5SDimitry Andric NumCapturingClosures++; 12970b57cec5SDimitry Andric continue; 12980b57cec5SDimitry Andric } 12990b57cec5SDimitry Andric // This context can't implicitly capture 'this'; fail out. 13000b57cec5SDimitry Andric if (BuildAndDiagnose) 13010b57cec5SDimitry Andric Diag(Loc, diag::err_this_capture) 13020b57cec5SDimitry Andric << (Explicit && idx == MaxFunctionScopesIndex); 13030b57cec5SDimitry Andric return true; 13040b57cec5SDimitry Andric } 13050b57cec5SDimitry Andric break; 13060b57cec5SDimitry Andric } 13070b57cec5SDimitry Andric if (!BuildAndDiagnose) return false; 13080b57cec5SDimitry Andric 13090b57cec5SDimitry Andric // If we got here, then the closure at MaxFunctionScopesIndex on the 13100b57cec5SDimitry Andric // FunctionScopes stack, can capture the *enclosing object*, so capture it 13110b57cec5SDimitry Andric // (including implicit by-reference captures in any enclosing closures). 13120b57cec5SDimitry Andric 13130b57cec5SDimitry Andric // In the loop below, respect the ByCopy flag only for the closure requesting 13140b57cec5SDimitry Andric // the capture (i.e. first iteration through the loop below). Ignore it for 13150b57cec5SDimitry Andric // all enclosing closure's up to NumCapturingClosures (since they must be 13160b57cec5SDimitry Andric // implicitly capturing the *enclosing object* by reference (see loop 13170b57cec5SDimitry Andric // above)). 13180b57cec5SDimitry Andric assert((!ByCopy || 13190b57cec5SDimitry Andric dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && 13200b57cec5SDimitry Andric "Only a lambda can capture the enclosing object (referred to by " 13210b57cec5SDimitry Andric "*this) by copy"); 13220b57cec5SDimitry Andric QualType ThisTy = getCurrentThisType(); 13230b57cec5SDimitry Andric for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; 13240b57cec5SDimitry Andric --idx, --NumCapturingClosures) { 13250b57cec5SDimitry Andric CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 13260b57cec5SDimitry Andric 13270b57cec5SDimitry Andric // The type of the corresponding data member (not a 'this' pointer if 'by 13280b57cec5SDimitry Andric // copy'). 13290b57cec5SDimitry Andric QualType CaptureType = ThisTy; 13300b57cec5SDimitry Andric if (ByCopy) { 13310b57cec5SDimitry Andric // If we are capturing the object referred to by '*this' by copy, ignore 13320b57cec5SDimitry Andric // any cv qualifiers inherited from the type of the member function for 13330b57cec5SDimitry Andric // the type of the closure-type's corresponding data member and any use 13340b57cec5SDimitry Andric // of 'this'. 13350b57cec5SDimitry Andric CaptureType = ThisTy->getPointeeType(); 13360b57cec5SDimitry Andric CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 13370b57cec5SDimitry Andric } 13380b57cec5SDimitry Andric 13390b57cec5SDimitry Andric bool isNested = NumCapturingClosures > 1; 13400b57cec5SDimitry Andric CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); 13410b57cec5SDimitry Andric } 13420b57cec5SDimitry Andric return false; 13430b57cec5SDimitry Andric } 13440b57cec5SDimitry Andric 13450b57cec5SDimitry Andric ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 13460b57cec5SDimitry Andric /// C++ 9.3.2: In the body of a non-static member function, the keyword this 13470b57cec5SDimitry Andric /// is a non-lvalue expression whose value is the address of the object for 13480b57cec5SDimitry Andric /// which the function is called. 13490b57cec5SDimitry Andric 13500b57cec5SDimitry Andric QualType ThisTy = getCurrentThisType(); 13510b57cec5SDimitry Andric if (ThisTy.isNull()) 13520b57cec5SDimitry Andric return Diag(Loc, diag::err_invalid_this_use); 13530b57cec5SDimitry Andric return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); 13540b57cec5SDimitry Andric } 13550b57cec5SDimitry Andric 13560b57cec5SDimitry Andric Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, 13570b57cec5SDimitry Andric bool IsImplicit) { 13580b57cec5SDimitry Andric auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); 13590b57cec5SDimitry Andric MarkThisReferenced(This); 13600b57cec5SDimitry Andric return This; 13610b57cec5SDimitry Andric } 13620b57cec5SDimitry Andric 13630b57cec5SDimitry Andric void Sema::MarkThisReferenced(CXXThisExpr *This) { 13640b57cec5SDimitry Andric CheckCXXThisCapture(This->getExprLoc()); 13650b57cec5SDimitry Andric } 13660b57cec5SDimitry Andric 13670b57cec5SDimitry Andric bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 13680b57cec5SDimitry Andric // If we're outside the body of a member function, then we'll have a specified 13690b57cec5SDimitry Andric // type for 'this'. 13700b57cec5SDimitry Andric if (CXXThisTypeOverride.isNull()) 13710b57cec5SDimitry Andric return false; 13720b57cec5SDimitry Andric 13730b57cec5SDimitry Andric // Determine whether we're looking into a class that's currently being 13740b57cec5SDimitry Andric // defined. 13750b57cec5SDimitry Andric CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 13760b57cec5SDimitry Andric return Class && Class->isBeingDefined(); 13770b57cec5SDimitry Andric } 13780b57cec5SDimitry Andric 13790b57cec5SDimitry Andric /// Parse construction of a specified type. 13800b57cec5SDimitry Andric /// Can be interpreted either as function-style casting ("int(x)") 13810b57cec5SDimitry Andric /// or class type construction ("ClassType(x,y,z)") 13820b57cec5SDimitry Andric /// or creation of a value-initialized type ("int()"). 13830b57cec5SDimitry Andric ExprResult 13840b57cec5SDimitry Andric Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 13850b57cec5SDimitry Andric SourceLocation LParenOrBraceLoc, 13860b57cec5SDimitry Andric MultiExprArg exprs, 13870b57cec5SDimitry Andric SourceLocation RParenOrBraceLoc, 13880b57cec5SDimitry Andric bool ListInitialization) { 13890b57cec5SDimitry Andric if (!TypeRep) 13900b57cec5SDimitry Andric return ExprError(); 13910b57cec5SDimitry Andric 13920b57cec5SDimitry Andric TypeSourceInfo *TInfo; 13930b57cec5SDimitry Andric QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 13940b57cec5SDimitry Andric if (!TInfo) 13950b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 13960b57cec5SDimitry Andric 13970b57cec5SDimitry Andric auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, 13980b57cec5SDimitry Andric RParenOrBraceLoc, ListInitialization); 13990b57cec5SDimitry Andric // Avoid creating a non-type-dependent expression that contains typos. 14000b57cec5SDimitry Andric // Non-type-dependent expressions are liable to be discarded without 14010b57cec5SDimitry Andric // checking for embedded typos. 14020b57cec5SDimitry Andric if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && 14030b57cec5SDimitry Andric !Result.get()->isTypeDependent()) 14040b57cec5SDimitry Andric Result = CorrectDelayedTyposInExpr(Result.get()); 1405e8d8bef9SDimitry Andric else if (Result.isInvalid()) 1406e8d8bef9SDimitry Andric Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), 1407e8d8bef9SDimitry Andric RParenOrBraceLoc, exprs, Ty); 14080b57cec5SDimitry Andric return Result; 14090b57cec5SDimitry Andric } 14100b57cec5SDimitry Andric 14110b57cec5SDimitry Andric ExprResult 14120b57cec5SDimitry Andric Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 14130b57cec5SDimitry Andric SourceLocation LParenOrBraceLoc, 14140b57cec5SDimitry Andric MultiExprArg Exprs, 14150b57cec5SDimitry Andric SourceLocation RParenOrBraceLoc, 14160b57cec5SDimitry Andric bool ListInitialization) { 14170b57cec5SDimitry Andric QualType Ty = TInfo->getType(); 14180b57cec5SDimitry Andric SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 14190b57cec5SDimitry Andric 14200b57cec5SDimitry Andric assert((!ListInitialization || 14210b57cec5SDimitry Andric (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && 14220b57cec5SDimitry Andric "List initialization must have initializer list as expression."); 14230b57cec5SDimitry Andric SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); 14240b57cec5SDimitry Andric 14250b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 14260b57cec5SDimitry Andric InitializationKind Kind = 14270b57cec5SDimitry Andric Exprs.size() 14280b57cec5SDimitry Andric ? ListInitialization 14290b57cec5SDimitry Andric ? InitializationKind::CreateDirectList( 14300b57cec5SDimitry Andric TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) 14310b57cec5SDimitry Andric : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, 14320b57cec5SDimitry Andric RParenOrBraceLoc) 14330b57cec5SDimitry Andric : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, 14340b57cec5SDimitry Andric RParenOrBraceLoc); 14350b57cec5SDimitry Andric 14360b57cec5SDimitry Andric // C++1z [expr.type.conv]p1: 14370b57cec5SDimitry Andric // If the type is a placeholder for a deduced class type, [...perform class 14380b57cec5SDimitry Andric // template argument deduction...] 14390b57cec5SDimitry Andric DeducedType *Deduced = Ty->getContainedDeducedType(); 14400b57cec5SDimitry Andric if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 14410b57cec5SDimitry Andric Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, 14420b57cec5SDimitry Andric Kind, Exprs); 14430b57cec5SDimitry Andric if (Ty.isNull()) 14440b57cec5SDimitry Andric return ExprError(); 14450b57cec5SDimitry Andric Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 14460b57cec5SDimitry Andric } 14470b57cec5SDimitry Andric 1448e8d8bef9SDimitry Andric if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { 1449e8d8bef9SDimitry Andric // FIXME: CXXUnresolvedConstructExpr does not model list-initialization 1450e8d8bef9SDimitry Andric // directly. We work around this by dropping the locations of the braces. 1451e8d8bef9SDimitry Andric SourceRange Locs = ListInitialization 1452e8d8bef9SDimitry Andric ? SourceRange() 1453e8d8bef9SDimitry Andric : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 1454e8d8bef9SDimitry Andric return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(), 1455e8d8bef9SDimitry Andric TInfo, Locs.getBegin(), Exprs, 1456e8d8bef9SDimitry Andric Locs.getEnd()); 1457e8d8bef9SDimitry Andric } 1458e8d8bef9SDimitry Andric 14590b57cec5SDimitry Andric // C++ [expr.type.conv]p1: 14600b57cec5SDimitry Andric // If the expression list is a parenthesized single expression, the type 14610b57cec5SDimitry Andric // conversion expression is equivalent (in definedness, and if defined in 14620b57cec5SDimitry Andric // meaning) to the corresponding cast expression. 14630b57cec5SDimitry Andric if (Exprs.size() == 1 && !ListInitialization && 14640b57cec5SDimitry Andric !isa<InitListExpr>(Exprs[0])) { 14650b57cec5SDimitry Andric Expr *Arg = Exprs[0]; 14660b57cec5SDimitry Andric return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, 14670b57cec5SDimitry Andric RParenOrBraceLoc); 14680b57cec5SDimitry Andric } 14690b57cec5SDimitry Andric 14700b57cec5SDimitry Andric // For an expression of the form T(), T shall not be an array type. 14710b57cec5SDimitry Andric QualType ElemTy = Ty; 14720b57cec5SDimitry Andric if (Ty->isArrayType()) { 14730b57cec5SDimitry Andric if (!ListInitialization) 14740b57cec5SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) 14750b57cec5SDimitry Andric << FullRange); 14760b57cec5SDimitry Andric ElemTy = Context.getBaseElementType(Ty); 14770b57cec5SDimitry Andric } 14780b57cec5SDimitry Andric 14790b57cec5SDimitry Andric // There doesn't seem to be an explicit rule against this but sanity demands 14800b57cec5SDimitry Andric // we only construct objects with object types. 14810b57cec5SDimitry Andric if (Ty->isFunctionType()) 14820b57cec5SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) 14830b57cec5SDimitry Andric << Ty << FullRange); 14840b57cec5SDimitry Andric 14850b57cec5SDimitry Andric // C++17 [expr.type.conv]p2: 14860b57cec5SDimitry Andric // If the type is cv void and the initializer is (), the expression is a 14870b57cec5SDimitry Andric // prvalue of the specified type that performs no initialization. 14880b57cec5SDimitry Andric if (!Ty->isVoidType() && 14890b57cec5SDimitry Andric RequireCompleteType(TyBeginLoc, ElemTy, 14900b57cec5SDimitry Andric diag::err_invalid_incomplete_type_use, FullRange)) 14910b57cec5SDimitry Andric return ExprError(); 14920b57cec5SDimitry Andric 14930b57cec5SDimitry Andric // Otherwise, the expression is a prvalue of the specified type whose 14940b57cec5SDimitry Andric // result object is direct-initialized (11.6) with the initializer. 14950b57cec5SDimitry Andric InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 14960b57cec5SDimitry Andric ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 14970b57cec5SDimitry Andric 14980b57cec5SDimitry Andric if (Result.isInvalid()) 14990b57cec5SDimitry Andric return Result; 15000b57cec5SDimitry Andric 15010b57cec5SDimitry Andric Expr *Inner = Result.get(); 15020b57cec5SDimitry Andric if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 15030b57cec5SDimitry Andric Inner = BTE->getSubExpr(); 15040b57cec5SDimitry Andric if (!isa<CXXTemporaryObjectExpr>(Inner) && 15050b57cec5SDimitry Andric !isa<CXXScalarValueInitExpr>(Inner)) { 15060b57cec5SDimitry Andric // If we created a CXXTemporaryObjectExpr, that node also represents the 15070b57cec5SDimitry Andric // functional cast. Otherwise, create an explicit cast to represent 15080b57cec5SDimitry Andric // the syntactic form of a functional-style cast that was used here. 15090b57cec5SDimitry Andric // 15100b57cec5SDimitry Andric // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr 15110b57cec5SDimitry Andric // would give a more consistent AST representation than using a 15120b57cec5SDimitry Andric // CXXTemporaryObjectExpr. It's also weird that the functional cast 15130b57cec5SDimitry Andric // is sometimes handled by initialization and sometimes not. 15140b57cec5SDimitry Andric QualType ResultType = Result.get()->getType(); 15150b57cec5SDimitry Andric SourceRange Locs = ListInitialization 15160b57cec5SDimitry Andric ? SourceRange() 15170b57cec5SDimitry Andric : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 15180b57cec5SDimitry Andric Result = CXXFunctionalCastExpr::Create( 15190b57cec5SDimitry Andric Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, 1520e8d8bef9SDimitry Andric Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), 1521e8d8bef9SDimitry Andric Locs.getBegin(), Locs.getEnd()); 15220b57cec5SDimitry Andric } 15230b57cec5SDimitry Andric 15240b57cec5SDimitry Andric return Result; 15250b57cec5SDimitry Andric } 15260b57cec5SDimitry Andric 15270b57cec5SDimitry Andric bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { 15280b57cec5SDimitry Andric // [CUDA] Ignore this function, if we can't call it. 15290b57cec5SDimitry Andric const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext); 1530e8d8bef9SDimitry Andric if (getLangOpts().CUDA) { 1531e8d8bef9SDimitry Andric auto CallPreference = IdentifyCUDAPreference(Caller, Method); 1532e8d8bef9SDimitry Andric // If it's not callable at all, it's not the right function. 1533e8d8bef9SDimitry Andric if (CallPreference < CFP_WrongSide) 15340b57cec5SDimitry Andric return false; 1535e8d8bef9SDimitry Andric if (CallPreference == CFP_WrongSide) { 1536e8d8bef9SDimitry Andric // Maybe. We have to check if there are better alternatives. 1537e8d8bef9SDimitry Andric DeclContext::lookup_result R = 1538e8d8bef9SDimitry Andric Method->getDeclContext()->lookup(Method->getDeclName()); 1539e8d8bef9SDimitry Andric for (const auto *D : R) { 1540e8d8bef9SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1541e8d8bef9SDimitry Andric if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide) 1542e8d8bef9SDimitry Andric return false; 1543e8d8bef9SDimitry Andric } 1544e8d8bef9SDimitry Andric } 1545e8d8bef9SDimitry Andric // We've found no better variants. 1546e8d8bef9SDimitry Andric } 1547e8d8bef9SDimitry Andric } 15480b57cec5SDimitry Andric 15490b57cec5SDimitry Andric SmallVector<const FunctionDecl*, 4> PreventedBy; 15500b57cec5SDimitry Andric bool Result = Method->isUsualDeallocationFunction(PreventedBy); 15510b57cec5SDimitry Andric 15520b57cec5SDimitry Andric if (Result || !getLangOpts().CUDA || PreventedBy.empty()) 15530b57cec5SDimitry Andric return Result; 15540b57cec5SDimitry Andric 15550b57cec5SDimitry Andric // In case of CUDA, return true if none of the 1-argument deallocator 15560b57cec5SDimitry Andric // functions are actually callable. 15570b57cec5SDimitry Andric return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { 15580b57cec5SDimitry Andric assert(FD->getNumParams() == 1 && 15590b57cec5SDimitry Andric "Only single-operand functions should be in PreventedBy"); 15600b57cec5SDimitry Andric return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; 15610b57cec5SDimitry Andric }); 15620b57cec5SDimitry Andric } 15630b57cec5SDimitry Andric 15640b57cec5SDimitry Andric /// Determine whether the given function is a non-placement 15650b57cec5SDimitry Andric /// deallocation function. 15660b57cec5SDimitry Andric static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 15670b57cec5SDimitry Andric if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 15680b57cec5SDimitry Andric return S.isUsualDeallocationFunction(Method); 15690b57cec5SDimitry Andric 15700b57cec5SDimitry Andric if (FD->getOverloadedOperator() != OO_Delete && 15710b57cec5SDimitry Andric FD->getOverloadedOperator() != OO_Array_Delete) 15720b57cec5SDimitry Andric return false; 15730b57cec5SDimitry Andric 15740b57cec5SDimitry Andric unsigned UsualParams = 1; 15750b57cec5SDimitry Andric 15760b57cec5SDimitry Andric if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && 15770b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 15780b57cec5SDimitry Andric FD->getParamDecl(UsualParams)->getType(), 15790b57cec5SDimitry Andric S.Context.getSizeType())) 15800b57cec5SDimitry Andric ++UsualParams; 15810b57cec5SDimitry Andric 15820b57cec5SDimitry Andric if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && 15830b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 15840b57cec5SDimitry Andric FD->getParamDecl(UsualParams)->getType(), 15850b57cec5SDimitry Andric S.Context.getTypeDeclType(S.getStdAlignValT()))) 15860b57cec5SDimitry Andric ++UsualParams; 15870b57cec5SDimitry Andric 15880b57cec5SDimitry Andric return UsualParams == FD->getNumParams(); 15890b57cec5SDimitry Andric } 15900b57cec5SDimitry Andric 15910b57cec5SDimitry Andric namespace { 15920b57cec5SDimitry Andric struct UsualDeallocFnInfo { 15930b57cec5SDimitry Andric UsualDeallocFnInfo() : Found(), FD(nullptr) {} 15940b57cec5SDimitry Andric UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) 15950b57cec5SDimitry Andric : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), 15960b57cec5SDimitry Andric Destroying(false), HasSizeT(false), HasAlignValT(false), 15970b57cec5SDimitry Andric CUDAPref(Sema::CFP_Native) { 15980b57cec5SDimitry Andric // A function template declaration is never a usual deallocation function. 15990b57cec5SDimitry Andric if (!FD) 16000b57cec5SDimitry Andric return; 16010b57cec5SDimitry Andric unsigned NumBaseParams = 1; 16020b57cec5SDimitry Andric if (FD->isDestroyingOperatorDelete()) { 16030b57cec5SDimitry Andric Destroying = true; 16040b57cec5SDimitry Andric ++NumBaseParams; 16050b57cec5SDimitry Andric } 16060b57cec5SDimitry Andric 16070b57cec5SDimitry Andric if (NumBaseParams < FD->getNumParams() && 16080b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 16090b57cec5SDimitry Andric FD->getParamDecl(NumBaseParams)->getType(), 16100b57cec5SDimitry Andric S.Context.getSizeType())) { 16110b57cec5SDimitry Andric ++NumBaseParams; 16120b57cec5SDimitry Andric HasSizeT = true; 16130b57cec5SDimitry Andric } 16140b57cec5SDimitry Andric 16150b57cec5SDimitry Andric if (NumBaseParams < FD->getNumParams() && 16160b57cec5SDimitry Andric FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { 16170b57cec5SDimitry Andric ++NumBaseParams; 16180b57cec5SDimitry Andric HasAlignValT = true; 16190b57cec5SDimitry Andric } 16200b57cec5SDimitry Andric 16210b57cec5SDimitry Andric // In CUDA, determine how much we'd like / dislike to call this. 16220b57cec5SDimitry Andric if (S.getLangOpts().CUDA) 16230b57cec5SDimitry Andric if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 16240b57cec5SDimitry Andric CUDAPref = S.IdentifyCUDAPreference(Caller, FD); 16250b57cec5SDimitry Andric } 16260b57cec5SDimitry Andric 16270b57cec5SDimitry Andric explicit operator bool() const { return FD; } 16280b57cec5SDimitry Andric 16290b57cec5SDimitry Andric bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, 16300b57cec5SDimitry Andric bool WantAlign) const { 16310b57cec5SDimitry Andric // C++ P0722: 16320b57cec5SDimitry Andric // A destroying operator delete is preferred over a non-destroying 16330b57cec5SDimitry Andric // operator delete. 16340b57cec5SDimitry Andric if (Destroying != Other.Destroying) 16350b57cec5SDimitry Andric return Destroying; 16360b57cec5SDimitry Andric 16370b57cec5SDimitry Andric // C++17 [expr.delete]p10: 16380b57cec5SDimitry Andric // If the type has new-extended alignment, a function with a parameter 16390b57cec5SDimitry Andric // of type std::align_val_t is preferred; otherwise a function without 16400b57cec5SDimitry Andric // such a parameter is preferred 16410b57cec5SDimitry Andric if (HasAlignValT != Other.HasAlignValT) 16420b57cec5SDimitry Andric return HasAlignValT == WantAlign; 16430b57cec5SDimitry Andric 16440b57cec5SDimitry Andric if (HasSizeT != Other.HasSizeT) 16450b57cec5SDimitry Andric return HasSizeT == WantSize; 16460b57cec5SDimitry Andric 16470b57cec5SDimitry Andric // Use CUDA call preference as a tiebreaker. 16480b57cec5SDimitry Andric return CUDAPref > Other.CUDAPref; 16490b57cec5SDimitry Andric } 16500b57cec5SDimitry Andric 16510b57cec5SDimitry Andric DeclAccessPair Found; 16520b57cec5SDimitry Andric FunctionDecl *FD; 16530b57cec5SDimitry Andric bool Destroying, HasSizeT, HasAlignValT; 16540b57cec5SDimitry Andric Sema::CUDAFunctionPreference CUDAPref; 16550b57cec5SDimitry Andric }; 16560b57cec5SDimitry Andric } 16570b57cec5SDimitry Andric 16580b57cec5SDimitry Andric /// Determine whether a type has new-extended alignment. This may be called when 16590b57cec5SDimitry Andric /// the type is incomplete (for a delete-expression with an incomplete pointee 16600b57cec5SDimitry Andric /// type), in which case it will conservatively return false if the alignment is 16610b57cec5SDimitry Andric /// not known. 16620b57cec5SDimitry Andric static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { 16630b57cec5SDimitry Andric return S.getLangOpts().AlignedAllocation && 16640b57cec5SDimitry Andric S.getASTContext().getTypeAlignIfKnown(AllocType) > 16650b57cec5SDimitry Andric S.getASTContext().getTargetInfo().getNewAlign(); 16660b57cec5SDimitry Andric } 16670b57cec5SDimitry Andric 16680b57cec5SDimitry Andric /// Select the correct "usual" deallocation function to use from a selection of 16690b57cec5SDimitry Andric /// deallocation functions (either global or class-scope). 16700b57cec5SDimitry Andric static UsualDeallocFnInfo resolveDeallocationOverload( 16710b57cec5SDimitry Andric Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 16720b57cec5SDimitry Andric llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { 16730b57cec5SDimitry Andric UsualDeallocFnInfo Best; 16740b57cec5SDimitry Andric 16750b57cec5SDimitry Andric for (auto I = R.begin(), E = R.end(); I != E; ++I) { 16760b57cec5SDimitry Andric UsualDeallocFnInfo Info(S, I.getPair()); 16770b57cec5SDimitry Andric if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || 16780b57cec5SDimitry Andric Info.CUDAPref == Sema::CFP_Never) 16790b57cec5SDimitry Andric continue; 16800b57cec5SDimitry Andric 16810b57cec5SDimitry Andric if (!Best) { 16820b57cec5SDimitry Andric Best = Info; 16830b57cec5SDimitry Andric if (BestFns) 16840b57cec5SDimitry Andric BestFns->push_back(Info); 16850b57cec5SDimitry Andric continue; 16860b57cec5SDimitry Andric } 16870b57cec5SDimitry Andric 16880b57cec5SDimitry Andric if (Best.isBetterThan(Info, WantSize, WantAlign)) 16890b57cec5SDimitry Andric continue; 16900b57cec5SDimitry Andric 16910b57cec5SDimitry Andric // If more than one preferred function is found, all non-preferred 16920b57cec5SDimitry Andric // functions are eliminated from further consideration. 16930b57cec5SDimitry Andric if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) 16940b57cec5SDimitry Andric BestFns->clear(); 16950b57cec5SDimitry Andric 16960b57cec5SDimitry Andric Best = Info; 16970b57cec5SDimitry Andric if (BestFns) 16980b57cec5SDimitry Andric BestFns->push_back(Info); 16990b57cec5SDimitry Andric } 17000b57cec5SDimitry Andric 17010b57cec5SDimitry Andric return Best; 17020b57cec5SDimitry Andric } 17030b57cec5SDimitry Andric 17040b57cec5SDimitry Andric /// Determine whether a given type is a class for which 'delete[]' would call 17050b57cec5SDimitry Andric /// a member 'operator delete[]' with a 'size_t' parameter. This implies that 17060b57cec5SDimitry Andric /// we need to store the array size (even if the type is 17070b57cec5SDimitry Andric /// trivially-destructible). 17080b57cec5SDimitry Andric static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 17090b57cec5SDimitry Andric QualType allocType) { 17100b57cec5SDimitry Andric const RecordType *record = 17110b57cec5SDimitry Andric allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 17120b57cec5SDimitry Andric if (!record) return false; 17130b57cec5SDimitry Andric 17140b57cec5SDimitry Andric // Try to find an operator delete[] in class scope. 17150b57cec5SDimitry Andric 17160b57cec5SDimitry Andric DeclarationName deleteName = 17170b57cec5SDimitry Andric S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 17180b57cec5SDimitry Andric LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 17190b57cec5SDimitry Andric S.LookupQualifiedName(ops, record->getDecl()); 17200b57cec5SDimitry Andric 17210b57cec5SDimitry Andric // We're just doing this for information. 17220b57cec5SDimitry Andric ops.suppressDiagnostics(); 17230b57cec5SDimitry Andric 17240b57cec5SDimitry Andric // Very likely: there's no operator delete[]. 17250b57cec5SDimitry Andric if (ops.empty()) return false; 17260b57cec5SDimitry Andric 17270b57cec5SDimitry Andric // If it's ambiguous, it should be illegal to call operator delete[] 17280b57cec5SDimitry Andric // on this thing, so it doesn't matter if we allocate extra space or not. 17290b57cec5SDimitry Andric if (ops.isAmbiguous()) return false; 17300b57cec5SDimitry Andric 17310b57cec5SDimitry Andric // C++17 [expr.delete]p10: 17320b57cec5SDimitry Andric // If the deallocation functions have class scope, the one without a 17330b57cec5SDimitry Andric // parameter of type std::size_t is selected. 17340b57cec5SDimitry Andric auto Best = resolveDeallocationOverload( 17350b57cec5SDimitry Andric S, ops, /*WantSize*/false, 17360b57cec5SDimitry Andric /*WantAlign*/hasNewExtendedAlignment(S, allocType)); 17370b57cec5SDimitry Andric return Best && Best.HasSizeT; 17380b57cec5SDimitry Andric } 17390b57cec5SDimitry Andric 17400b57cec5SDimitry Andric /// Parsed a C++ 'new' expression (C++ 5.3.4). 17410b57cec5SDimitry Andric /// 17420b57cec5SDimitry Andric /// E.g.: 17430b57cec5SDimitry Andric /// @code new (memory) int[size][4] @endcode 17440b57cec5SDimitry Andric /// or 17450b57cec5SDimitry Andric /// @code ::new Foo(23, "hello") @endcode 17460b57cec5SDimitry Andric /// 17470b57cec5SDimitry Andric /// \param StartLoc The first location of the expression. 17480b57cec5SDimitry Andric /// \param UseGlobal True if 'new' was prefixed with '::'. 17490b57cec5SDimitry Andric /// \param PlacementLParen Opening paren of the placement arguments. 17500b57cec5SDimitry Andric /// \param PlacementArgs Placement new arguments. 17510b57cec5SDimitry Andric /// \param PlacementRParen Closing paren of the placement arguments. 17520b57cec5SDimitry Andric /// \param TypeIdParens If the type is in parens, the source range. 17530b57cec5SDimitry Andric /// \param D The type to be allocated, as well as array dimensions. 17540b57cec5SDimitry Andric /// \param Initializer The initializing expression or initializer-list, or null 17550b57cec5SDimitry Andric /// if there is none. 17560b57cec5SDimitry Andric ExprResult 17570b57cec5SDimitry Andric Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 17580b57cec5SDimitry Andric SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 17590b57cec5SDimitry Andric SourceLocation PlacementRParen, SourceRange TypeIdParens, 17600b57cec5SDimitry Andric Declarator &D, Expr *Initializer) { 17610b57cec5SDimitry Andric Optional<Expr *> ArraySize; 17620b57cec5SDimitry Andric // If the specified type is an array, unwrap it and save the expression. 17630b57cec5SDimitry Andric if (D.getNumTypeObjects() > 0 && 17640b57cec5SDimitry Andric D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 17650b57cec5SDimitry Andric DeclaratorChunk &Chunk = D.getTypeObject(0); 17660b57cec5SDimitry Andric if (D.getDeclSpec().hasAutoTypeSpec()) 17670b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 17680b57cec5SDimitry Andric << D.getSourceRange()); 17690b57cec5SDimitry Andric if (Chunk.Arr.hasStatic) 17700b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 17710b57cec5SDimitry Andric << D.getSourceRange()); 17720b57cec5SDimitry Andric if (!Chunk.Arr.NumElts && !Initializer) 17730b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 17740b57cec5SDimitry Andric << D.getSourceRange()); 17750b57cec5SDimitry Andric 17760b57cec5SDimitry Andric ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 17770b57cec5SDimitry Andric D.DropFirstTypeObject(); 17780b57cec5SDimitry Andric } 17790b57cec5SDimitry Andric 17800b57cec5SDimitry Andric // Every dimension shall be of constant size. 17810b57cec5SDimitry Andric if (ArraySize) { 17820b57cec5SDimitry Andric for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 17830b57cec5SDimitry Andric if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 17840b57cec5SDimitry Andric break; 17850b57cec5SDimitry Andric 17860b57cec5SDimitry Andric DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 17870b57cec5SDimitry Andric if (Expr *NumElts = (Expr *)Array.NumElts) { 17880b57cec5SDimitry Andric if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 1789e8d8bef9SDimitry Andric // FIXME: GCC permits constant folding here. We should either do so consistently 1790e8d8bef9SDimitry Andric // or not do so at all, rather than changing behavior in C++14 onwards. 17910b57cec5SDimitry Andric if (getLangOpts().CPlusPlus14) { 17920b57cec5SDimitry Andric // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 17930b57cec5SDimitry Andric // shall be a converted constant expression (5.19) of type std::size_t 17940b57cec5SDimitry Andric // and shall evaluate to a strictly positive value. 1795e8d8bef9SDimitry Andric llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); 17960b57cec5SDimitry Andric Array.NumElts 17970b57cec5SDimitry Andric = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 1798e8d8bef9SDimitry Andric CCEK_ArrayBound) 17990b57cec5SDimitry Andric .get(); 18000b57cec5SDimitry Andric } else { 1801e8d8bef9SDimitry Andric Array.NumElts = 1802e8d8bef9SDimitry Andric VerifyIntegerConstantExpression( 1803e8d8bef9SDimitry Andric NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) 18040b57cec5SDimitry Andric .get(); 18050b57cec5SDimitry Andric } 18060b57cec5SDimitry Andric if (!Array.NumElts) 18070b57cec5SDimitry Andric return ExprError(); 18080b57cec5SDimitry Andric } 18090b57cec5SDimitry Andric } 18100b57cec5SDimitry Andric } 18110b57cec5SDimitry Andric } 18120b57cec5SDimitry Andric 18130b57cec5SDimitry Andric TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); 18140b57cec5SDimitry Andric QualType AllocType = TInfo->getType(); 18150b57cec5SDimitry Andric if (D.isInvalidType()) 18160b57cec5SDimitry Andric return ExprError(); 18170b57cec5SDimitry Andric 18180b57cec5SDimitry Andric SourceRange DirectInitRange; 18190b57cec5SDimitry Andric if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 18200b57cec5SDimitry Andric DirectInitRange = List->getSourceRange(); 18210b57cec5SDimitry Andric 18220b57cec5SDimitry Andric return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, 18230b57cec5SDimitry Andric PlacementLParen, PlacementArgs, PlacementRParen, 18240b57cec5SDimitry Andric TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, 18250b57cec5SDimitry Andric Initializer); 18260b57cec5SDimitry Andric } 18270b57cec5SDimitry Andric 18280b57cec5SDimitry Andric static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 18290b57cec5SDimitry Andric Expr *Init) { 18300b57cec5SDimitry Andric if (!Init) 18310b57cec5SDimitry Andric return true; 18320b57cec5SDimitry Andric if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 18330b57cec5SDimitry Andric return PLE->getNumExprs() == 0; 18340b57cec5SDimitry Andric if (isa<ImplicitValueInitExpr>(Init)) 18350b57cec5SDimitry Andric return true; 18360b57cec5SDimitry Andric else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 18370b57cec5SDimitry Andric return !CCE->isListInitialization() && 18380b57cec5SDimitry Andric CCE->getConstructor()->isDefaultConstructor(); 18390b57cec5SDimitry Andric else if (Style == CXXNewExpr::ListInit) { 18400b57cec5SDimitry Andric assert(isa<InitListExpr>(Init) && 18410b57cec5SDimitry Andric "Shouldn't create list CXXConstructExprs for arrays."); 18420b57cec5SDimitry Andric return true; 18430b57cec5SDimitry Andric } 18440b57cec5SDimitry Andric return false; 18450b57cec5SDimitry Andric } 18460b57cec5SDimitry Andric 18470b57cec5SDimitry Andric bool 18480b57cec5SDimitry Andric Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { 18490b57cec5SDimitry Andric if (!getLangOpts().AlignedAllocationUnavailable) 18500b57cec5SDimitry Andric return false; 18510b57cec5SDimitry Andric if (FD.isDefined()) 18520b57cec5SDimitry Andric return false; 18535ffd83dbSDimitry Andric Optional<unsigned> AlignmentParam; 18545ffd83dbSDimitry Andric if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && 18555ffd83dbSDimitry Andric AlignmentParam.hasValue()) 18560b57cec5SDimitry Andric return true; 18570b57cec5SDimitry Andric return false; 18580b57cec5SDimitry Andric } 18590b57cec5SDimitry Andric 18600b57cec5SDimitry Andric // Emit a diagnostic if an aligned allocation/deallocation function that is not 18610b57cec5SDimitry Andric // implemented in the standard library is selected. 18620b57cec5SDimitry Andric void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 18630b57cec5SDimitry Andric SourceLocation Loc) { 18640b57cec5SDimitry Andric if (isUnavailableAlignedAllocationFunction(FD)) { 18650b57cec5SDimitry Andric const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 18660b57cec5SDimitry Andric StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( 18670b57cec5SDimitry Andric getASTContext().getTargetInfo().getPlatformName()); 1868e8d8bef9SDimitry Andric VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); 18690b57cec5SDimitry Andric 18700b57cec5SDimitry Andric OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); 18710b57cec5SDimitry Andric bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; 18720b57cec5SDimitry Andric Diag(Loc, diag::err_aligned_allocation_unavailable) 18730b57cec5SDimitry Andric << IsDelete << FD.getType().getAsString() << OSName 1874e8d8bef9SDimitry Andric << OSVersion.getAsString() << OSVersion.empty(); 18750b57cec5SDimitry Andric Diag(Loc, diag::note_silence_aligned_allocation_unavailable); 18760b57cec5SDimitry Andric } 18770b57cec5SDimitry Andric } 18780b57cec5SDimitry Andric 18790b57cec5SDimitry Andric ExprResult 18800b57cec5SDimitry Andric Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 18810b57cec5SDimitry Andric SourceLocation PlacementLParen, 18820b57cec5SDimitry Andric MultiExprArg PlacementArgs, 18830b57cec5SDimitry Andric SourceLocation PlacementRParen, 18840b57cec5SDimitry Andric SourceRange TypeIdParens, 18850b57cec5SDimitry Andric QualType AllocType, 18860b57cec5SDimitry Andric TypeSourceInfo *AllocTypeInfo, 18870b57cec5SDimitry Andric Optional<Expr *> ArraySize, 18880b57cec5SDimitry Andric SourceRange DirectInitRange, 18890b57cec5SDimitry Andric Expr *Initializer) { 18900b57cec5SDimitry Andric SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 18910b57cec5SDimitry Andric SourceLocation StartLoc = Range.getBegin(); 18920b57cec5SDimitry Andric 18930b57cec5SDimitry Andric CXXNewExpr::InitializationStyle initStyle; 18940b57cec5SDimitry Andric if (DirectInitRange.isValid()) { 18950b57cec5SDimitry Andric assert(Initializer && "Have parens but no initializer."); 18960b57cec5SDimitry Andric initStyle = CXXNewExpr::CallInit; 18970b57cec5SDimitry Andric } else if (Initializer && isa<InitListExpr>(Initializer)) 18980b57cec5SDimitry Andric initStyle = CXXNewExpr::ListInit; 18990b57cec5SDimitry Andric else { 19000b57cec5SDimitry Andric assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 19010b57cec5SDimitry Andric isa<CXXConstructExpr>(Initializer)) && 19020b57cec5SDimitry Andric "Initializer expression that cannot have been implicitly created."); 19030b57cec5SDimitry Andric initStyle = CXXNewExpr::NoInit; 19040b57cec5SDimitry Andric } 19050b57cec5SDimitry Andric 19060b57cec5SDimitry Andric Expr **Inits = &Initializer; 19070b57cec5SDimitry Andric unsigned NumInits = Initializer ? 1 : 0; 19080b57cec5SDimitry Andric if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 19090b57cec5SDimitry Andric assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init"); 19100b57cec5SDimitry Andric Inits = List->getExprs(); 19110b57cec5SDimitry Andric NumInits = List->getNumExprs(); 19120b57cec5SDimitry Andric } 19130b57cec5SDimitry Andric 19140b57cec5SDimitry Andric // C++11 [expr.new]p15: 19150b57cec5SDimitry Andric // A new-expression that creates an object of type T initializes that 19160b57cec5SDimitry Andric // object as follows: 19170b57cec5SDimitry Andric InitializationKind Kind 19180b57cec5SDimitry Andric // - If the new-initializer is omitted, the object is default- 19190b57cec5SDimitry Andric // initialized (8.5); if no initialization is performed, 19200b57cec5SDimitry Andric // the object has indeterminate value 19210b57cec5SDimitry Andric = initStyle == CXXNewExpr::NoInit 19220b57cec5SDimitry Andric ? InitializationKind::CreateDefault(TypeRange.getBegin()) 19230b57cec5SDimitry Andric // - Otherwise, the new-initializer is interpreted according to 19240b57cec5SDimitry Andric // the 19250b57cec5SDimitry Andric // initialization rules of 8.5 for direct-initialization. 19260b57cec5SDimitry Andric : initStyle == CXXNewExpr::ListInit 19270b57cec5SDimitry Andric ? InitializationKind::CreateDirectList( 19280b57cec5SDimitry Andric TypeRange.getBegin(), Initializer->getBeginLoc(), 19290b57cec5SDimitry Andric Initializer->getEndLoc()) 19300b57cec5SDimitry Andric : InitializationKind::CreateDirect(TypeRange.getBegin(), 19310b57cec5SDimitry Andric DirectInitRange.getBegin(), 19320b57cec5SDimitry Andric DirectInitRange.getEnd()); 19330b57cec5SDimitry Andric 19340b57cec5SDimitry Andric // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. 19350b57cec5SDimitry Andric auto *Deduced = AllocType->getContainedDeducedType(); 19360b57cec5SDimitry Andric if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 19370b57cec5SDimitry Andric if (ArraySize) 19380b57cec5SDimitry Andric return ExprError( 19390b57cec5SDimitry Andric Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), 19400b57cec5SDimitry Andric diag::err_deduced_class_template_compound_type) 19410b57cec5SDimitry Andric << /*array*/ 2 19420b57cec5SDimitry Andric << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); 19430b57cec5SDimitry Andric 19440b57cec5SDimitry Andric InitializedEntity Entity 19450b57cec5SDimitry Andric = InitializedEntity::InitializeNew(StartLoc, AllocType); 19460b57cec5SDimitry Andric AllocType = DeduceTemplateSpecializationFromInitializer( 19470b57cec5SDimitry Andric AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits)); 19480b57cec5SDimitry Andric if (AllocType.isNull()) 19490b57cec5SDimitry Andric return ExprError(); 19500b57cec5SDimitry Andric } else if (Deduced) { 19510b57cec5SDimitry Andric bool Braced = (initStyle == CXXNewExpr::ListInit); 19520b57cec5SDimitry Andric if (NumInits == 1) { 19530b57cec5SDimitry Andric if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) { 19540b57cec5SDimitry Andric Inits = p->getInits(); 19550b57cec5SDimitry Andric NumInits = p->getNumInits(); 19560b57cec5SDimitry Andric Braced = true; 19570b57cec5SDimitry Andric } 19580b57cec5SDimitry Andric } 19590b57cec5SDimitry Andric 19600b57cec5SDimitry Andric if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 19610b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 19620b57cec5SDimitry Andric << AllocType << TypeRange); 19630b57cec5SDimitry Andric if (NumInits > 1) { 19640b57cec5SDimitry Andric Expr *FirstBad = Inits[1]; 19650b57cec5SDimitry Andric return ExprError(Diag(FirstBad->getBeginLoc(), 19660b57cec5SDimitry Andric diag::err_auto_new_ctor_multiple_expressions) 19670b57cec5SDimitry Andric << AllocType << TypeRange); 19680b57cec5SDimitry Andric } 19690b57cec5SDimitry Andric if (Braced && !getLangOpts().CPlusPlus17) 19700b57cec5SDimitry Andric Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) 19710b57cec5SDimitry Andric << AllocType << TypeRange; 19720b57cec5SDimitry Andric Expr *Deduce = Inits[0]; 19730b57cec5SDimitry Andric QualType DeducedType; 19740b57cec5SDimitry Andric if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 19750b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 19760b57cec5SDimitry Andric << AllocType << Deduce->getType() 19770b57cec5SDimitry Andric << TypeRange << Deduce->getSourceRange()); 19780b57cec5SDimitry Andric if (DeducedType.isNull()) 19790b57cec5SDimitry Andric return ExprError(); 19800b57cec5SDimitry Andric AllocType = DeducedType; 19810b57cec5SDimitry Andric } 19820b57cec5SDimitry Andric 19830b57cec5SDimitry Andric // Per C++0x [expr.new]p5, the type being constructed may be a 19840b57cec5SDimitry Andric // typedef of an array type. 19850b57cec5SDimitry Andric if (!ArraySize) { 19860b57cec5SDimitry Andric if (const ConstantArrayType *Array 19870b57cec5SDimitry Andric = Context.getAsConstantArrayType(AllocType)) { 19880b57cec5SDimitry Andric ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 19890b57cec5SDimitry Andric Context.getSizeType(), 19900b57cec5SDimitry Andric TypeRange.getEnd()); 19910b57cec5SDimitry Andric AllocType = Array->getElementType(); 19920b57cec5SDimitry Andric } 19930b57cec5SDimitry Andric } 19940b57cec5SDimitry Andric 19950b57cec5SDimitry Andric if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 19960b57cec5SDimitry Andric return ExprError(); 19970b57cec5SDimitry Andric 19980b57cec5SDimitry Andric // In ARC, infer 'retaining' for the allocated 19990b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 20000b57cec5SDimitry Andric AllocType.getObjCLifetime() == Qualifiers::OCL_None && 20010b57cec5SDimitry Andric AllocType->isObjCLifetimeType()) { 20020b57cec5SDimitry Andric AllocType = Context.getLifetimeQualifiedType(AllocType, 20030b57cec5SDimitry Andric AllocType->getObjCARCImplicitLifetime()); 20040b57cec5SDimitry Andric } 20050b57cec5SDimitry Andric 20060b57cec5SDimitry Andric QualType ResultType = Context.getPointerType(AllocType); 20070b57cec5SDimitry Andric 20080b57cec5SDimitry Andric if (ArraySize && *ArraySize && 20090b57cec5SDimitry Andric (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { 20100b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(*ArraySize); 20110b57cec5SDimitry Andric if (result.isInvalid()) return ExprError(); 20120b57cec5SDimitry Andric ArraySize = result.get(); 20130b57cec5SDimitry Andric } 20140b57cec5SDimitry Andric // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 20150b57cec5SDimitry Andric // integral or enumeration type with a non-negative value." 20160b57cec5SDimitry Andric // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 20170b57cec5SDimitry Andric // enumeration type, or a class type for which a single non-explicit 20180b57cec5SDimitry Andric // conversion function to integral or unscoped enumeration type exists. 20190b57cec5SDimitry Andric // C++1y [expr.new]p6: The expression [...] is implicitly converted to 20200b57cec5SDimitry Andric // std::size_t. 20210b57cec5SDimitry Andric llvm::Optional<uint64_t> KnownArraySize; 20220b57cec5SDimitry Andric if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { 20230b57cec5SDimitry Andric ExprResult ConvertedSize; 20240b57cec5SDimitry Andric if (getLangOpts().CPlusPlus14) { 20250b57cec5SDimitry Andric assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); 20260b57cec5SDimitry Andric 20270b57cec5SDimitry Andric ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), 20280b57cec5SDimitry Andric AA_Converting); 20290b57cec5SDimitry Andric 20300b57cec5SDimitry Andric if (!ConvertedSize.isInvalid() && 20310b57cec5SDimitry Andric (*ArraySize)->getType()->getAs<RecordType>()) 20320b57cec5SDimitry Andric // Diagnose the compatibility of this conversion. 20330b57cec5SDimitry Andric Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 20340b57cec5SDimitry Andric << (*ArraySize)->getType() << 0 << "'size_t'"; 20350b57cec5SDimitry Andric } else { 20360b57cec5SDimitry Andric class SizeConvertDiagnoser : public ICEConvertDiagnoser { 20370b57cec5SDimitry Andric protected: 20380b57cec5SDimitry Andric Expr *ArraySize; 20390b57cec5SDimitry Andric 20400b57cec5SDimitry Andric public: 20410b57cec5SDimitry Andric SizeConvertDiagnoser(Expr *ArraySize) 20420b57cec5SDimitry Andric : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 20430b57cec5SDimitry Andric ArraySize(ArraySize) {} 20440b57cec5SDimitry Andric 20450b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 20460b57cec5SDimitry Andric QualType T) override { 20470b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_not_integral) 20480b57cec5SDimitry Andric << S.getLangOpts().CPlusPlus11 << T; 20490b57cec5SDimitry Andric } 20500b57cec5SDimitry Andric 20510b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseIncomplete( 20520b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T) override { 20530b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_incomplete_type) 20540b57cec5SDimitry Andric << T << ArraySize->getSourceRange(); 20550b57cec5SDimitry Andric } 20560b57cec5SDimitry Andric 20570b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseExplicitConv( 20580b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 20590b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 20600b57cec5SDimitry Andric } 20610b57cec5SDimitry Andric 20620b57cec5SDimitry Andric SemaDiagnosticBuilder noteExplicitConv( 20630b57cec5SDimitry Andric Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 20640b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 20650b57cec5SDimitry Andric << ConvTy->isEnumeralType() << ConvTy; 20660b57cec5SDimitry Andric } 20670b57cec5SDimitry Andric 20680b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseAmbiguous( 20690b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T) override { 20700b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 20710b57cec5SDimitry Andric } 20720b57cec5SDimitry Andric 20730b57cec5SDimitry Andric SemaDiagnosticBuilder noteAmbiguous( 20740b57cec5SDimitry Andric Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 20750b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 20760b57cec5SDimitry Andric << ConvTy->isEnumeralType() << ConvTy; 20770b57cec5SDimitry Andric } 20780b57cec5SDimitry Andric 20790b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 20800b57cec5SDimitry Andric QualType T, 20810b57cec5SDimitry Andric QualType ConvTy) override { 20820b57cec5SDimitry Andric return S.Diag(Loc, 20830b57cec5SDimitry Andric S.getLangOpts().CPlusPlus11 20840b57cec5SDimitry Andric ? diag::warn_cxx98_compat_array_size_conversion 20850b57cec5SDimitry Andric : diag::ext_array_size_conversion) 20860b57cec5SDimitry Andric << T << ConvTy->isEnumeralType() << ConvTy; 20870b57cec5SDimitry Andric } 20880b57cec5SDimitry Andric } SizeDiagnoser(*ArraySize); 20890b57cec5SDimitry Andric 20900b57cec5SDimitry Andric ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, 20910b57cec5SDimitry Andric SizeDiagnoser); 20920b57cec5SDimitry Andric } 20930b57cec5SDimitry Andric if (ConvertedSize.isInvalid()) 20940b57cec5SDimitry Andric return ExprError(); 20950b57cec5SDimitry Andric 20960b57cec5SDimitry Andric ArraySize = ConvertedSize.get(); 20970b57cec5SDimitry Andric QualType SizeType = (*ArraySize)->getType(); 20980b57cec5SDimitry Andric 20990b57cec5SDimitry Andric if (!SizeType->isIntegralOrUnscopedEnumerationType()) 21000b57cec5SDimitry Andric return ExprError(); 21010b57cec5SDimitry Andric 21020b57cec5SDimitry Andric // C++98 [expr.new]p7: 21030b57cec5SDimitry Andric // The expression in a direct-new-declarator shall have integral type 21040b57cec5SDimitry Andric // with a non-negative value. 21050b57cec5SDimitry Andric // 21060b57cec5SDimitry Andric // Let's see if this is a constant < 0. If so, we reject it out of hand, 21070b57cec5SDimitry Andric // per CWG1464. Otherwise, if it's not a constant, we must have an 21080b57cec5SDimitry Andric // unparenthesized array type. 21090b57cec5SDimitry Andric if (!(*ArraySize)->isValueDependent()) { 21100b57cec5SDimitry Andric // We've already performed any required implicit conversion to integer or 21110b57cec5SDimitry Andric // unscoped enumeration type. 21120b57cec5SDimitry Andric // FIXME: Per CWG1464, we are required to check the value prior to 21130b57cec5SDimitry Andric // converting to size_t. This will never find a negative array size in 21140b57cec5SDimitry Andric // C++14 onwards, because Value is always unsigned here! 2115e8d8bef9SDimitry Andric if (Optional<llvm::APSInt> Value = 2116e8d8bef9SDimitry Andric (*ArraySize)->getIntegerConstantExpr(Context)) { 2117e8d8bef9SDimitry Andric if (Value->isSigned() && Value->isNegative()) { 21180b57cec5SDimitry Andric return ExprError(Diag((*ArraySize)->getBeginLoc(), 21190b57cec5SDimitry Andric diag::err_typecheck_negative_array_size) 21200b57cec5SDimitry Andric << (*ArraySize)->getSourceRange()); 21210b57cec5SDimitry Andric } 21220b57cec5SDimitry Andric 21230b57cec5SDimitry Andric if (!AllocType->isDependentType()) { 2124e8d8bef9SDimitry Andric unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits( 2125e8d8bef9SDimitry Andric Context, AllocType, *Value); 21260b57cec5SDimitry Andric if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 21270b57cec5SDimitry Andric return ExprError( 21280b57cec5SDimitry Andric Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) 2129e8d8bef9SDimitry Andric << Value->toString(10) << (*ArraySize)->getSourceRange()); 21300b57cec5SDimitry Andric } 21310b57cec5SDimitry Andric 2132e8d8bef9SDimitry Andric KnownArraySize = Value->getZExtValue(); 21330b57cec5SDimitry Andric } else if (TypeIdParens.isValid()) { 21340b57cec5SDimitry Andric // Can't have dynamic array size when the type-id is in parentheses. 21350b57cec5SDimitry Andric Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) 21360b57cec5SDimitry Andric << (*ArraySize)->getSourceRange() 21370b57cec5SDimitry Andric << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 21380b57cec5SDimitry Andric << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 21390b57cec5SDimitry Andric 21400b57cec5SDimitry Andric TypeIdParens = SourceRange(); 21410b57cec5SDimitry Andric } 21420b57cec5SDimitry Andric } 21430b57cec5SDimitry Andric 21440b57cec5SDimitry Andric // Note that we do *not* convert the argument in any way. It can 21450b57cec5SDimitry Andric // be signed, larger than size_t, whatever. 21460b57cec5SDimitry Andric } 21470b57cec5SDimitry Andric 21480b57cec5SDimitry Andric FunctionDecl *OperatorNew = nullptr; 21490b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 21500b57cec5SDimitry Andric unsigned Alignment = 21510b57cec5SDimitry Andric AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 21520b57cec5SDimitry Andric unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 21530b57cec5SDimitry Andric bool PassAlignment = getLangOpts().AlignedAllocation && 21540b57cec5SDimitry Andric Alignment > NewAlignment; 21550b57cec5SDimitry Andric 21560b57cec5SDimitry Andric AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; 21570b57cec5SDimitry Andric if (!AllocType->isDependentType() && 21580b57cec5SDimitry Andric !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 21590b57cec5SDimitry Andric FindAllocationFunctions( 21600b57cec5SDimitry Andric StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, 21610b57cec5SDimitry Andric AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs, 21620b57cec5SDimitry Andric OperatorNew, OperatorDelete)) 21630b57cec5SDimitry Andric return ExprError(); 21640b57cec5SDimitry Andric 21650b57cec5SDimitry Andric // If this is an array allocation, compute whether the usual array 21660b57cec5SDimitry Andric // deallocation function for the type has a size_t parameter. 21670b57cec5SDimitry Andric bool UsualArrayDeleteWantsSize = false; 21680b57cec5SDimitry Andric if (ArraySize && !AllocType->isDependentType()) 21690b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 21700b57cec5SDimitry Andric doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 21710b57cec5SDimitry Andric 21720b57cec5SDimitry Andric SmallVector<Expr *, 8> AllPlaceArgs; 21730b57cec5SDimitry Andric if (OperatorNew) { 21745ffd83dbSDimitry Andric auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 21750b57cec5SDimitry Andric VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 21760b57cec5SDimitry Andric : VariadicDoesNotApply; 21770b57cec5SDimitry Andric 21780b57cec5SDimitry Andric // We've already converted the placement args, just fill in any default 21790b57cec5SDimitry Andric // arguments. Skip the first parameter because we don't have a corresponding 21800b57cec5SDimitry Andric // argument. Skip the second parameter too if we're passing in the 21810b57cec5SDimitry Andric // alignment; we've already filled it in. 21825ffd83dbSDimitry Andric unsigned NumImplicitArgs = PassAlignment ? 2 : 1; 21830b57cec5SDimitry Andric if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 21845ffd83dbSDimitry Andric NumImplicitArgs, PlacementArgs, AllPlaceArgs, 21855ffd83dbSDimitry Andric CallType)) 21860b57cec5SDimitry Andric return ExprError(); 21870b57cec5SDimitry Andric 21880b57cec5SDimitry Andric if (!AllPlaceArgs.empty()) 21890b57cec5SDimitry Andric PlacementArgs = AllPlaceArgs; 21900b57cec5SDimitry Andric 21915ffd83dbSDimitry Andric // We would like to perform some checking on the given `operator new` call, 21925ffd83dbSDimitry Andric // but the PlacementArgs does not contain the implicit arguments, 21935ffd83dbSDimitry Andric // namely allocation size and maybe allocation alignment, 21945ffd83dbSDimitry Andric // so we need to conjure them. 21950b57cec5SDimitry Andric 21965ffd83dbSDimitry Andric QualType SizeTy = Context.getSizeType(); 21975ffd83dbSDimitry Andric unsigned SizeTyWidth = Context.getTypeSize(SizeTy); 21985ffd83dbSDimitry Andric 21995ffd83dbSDimitry Andric llvm::APInt SingleEltSize( 22005ffd83dbSDimitry Andric SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); 22015ffd83dbSDimitry Andric 22025ffd83dbSDimitry Andric // How many bytes do we want to allocate here? 22035ffd83dbSDimitry Andric llvm::Optional<llvm::APInt> AllocationSize; 22045ffd83dbSDimitry Andric if (!ArraySize.hasValue() && !AllocType->isDependentType()) { 22055ffd83dbSDimitry Andric // For non-array operator new, we only want to allocate one element. 22065ffd83dbSDimitry Andric AllocationSize = SingleEltSize; 22075ffd83dbSDimitry Andric } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) { 22085ffd83dbSDimitry Andric // For array operator new, only deal with static array size case. 22095ffd83dbSDimitry Andric bool Overflow; 22105ffd83dbSDimitry Andric AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) 22115ffd83dbSDimitry Andric .umul_ov(SingleEltSize, Overflow); 22125ffd83dbSDimitry Andric (void)Overflow; 22135ffd83dbSDimitry Andric assert( 22145ffd83dbSDimitry Andric !Overflow && 22155ffd83dbSDimitry Andric "Expected that all the overflows would have been handled already."); 22165ffd83dbSDimitry Andric } 22175ffd83dbSDimitry Andric 22185ffd83dbSDimitry Andric IntegerLiteral AllocationSizeLiteral( 22195ffd83dbSDimitry Andric Context, 22205ffd83dbSDimitry Andric AllocationSize.getValueOr(llvm::APInt::getNullValue(SizeTyWidth)), 22215ffd83dbSDimitry Andric SizeTy, SourceLocation()); 22225ffd83dbSDimitry Andric // Otherwise, if we failed to constant-fold the allocation size, we'll 22235ffd83dbSDimitry Andric // just give up and pass-in something opaque, that isn't a null pointer. 22245ffd83dbSDimitry Andric OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_RValue, 22255ffd83dbSDimitry Andric OK_Ordinary, /*SourceExpr=*/nullptr); 22265ffd83dbSDimitry Andric 22275ffd83dbSDimitry Andric // Let's synthesize the alignment argument in case we will need it. 22285ffd83dbSDimitry Andric // Since we *really* want to allocate these on stack, this is slightly ugly 22295ffd83dbSDimitry Andric // because there might not be a `std::align_val_t` type. 22305ffd83dbSDimitry Andric EnumDecl *StdAlignValT = getStdAlignValT(); 22315ffd83dbSDimitry Andric QualType AlignValT = 22325ffd83dbSDimitry Andric StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; 22335ffd83dbSDimitry Andric IntegerLiteral AlignmentLiteral( 22345ffd83dbSDimitry Andric Context, 22355ffd83dbSDimitry Andric llvm::APInt(Context.getTypeSize(SizeTy), 22365ffd83dbSDimitry Andric Alignment / Context.getCharWidth()), 22375ffd83dbSDimitry Andric SizeTy, SourceLocation()); 22385ffd83dbSDimitry Andric ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, 22395ffd83dbSDimitry Andric CK_IntegralCast, &AlignmentLiteral, 2240e8d8bef9SDimitry Andric VK_RValue, FPOptionsOverride()); 22415ffd83dbSDimitry Andric 22425ffd83dbSDimitry Andric // Adjust placement args by prepending conjured size and alignment exprs. 22435ffd83dbSDimitry Andric llvm::SmallVector<Expr *, 8> CallArgs; 22445ffd83dbSDimitry Andric CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); 22455ffd83dbSDimitry Andric CallArgs.emplace_back(AllocationSize.hasValue() 22465ffd83dbSDimitry Andric ? static_cast<Expr *>(&AllocationSizeLiteral) 22475ffd83dbSDimitry Andric : &OpaqueAllocationSize); 22485ffd83dbSDimitry Andric if (PassAlignment) 22495ffd83dbSDimitry Andric CallArgs.emplace_back(&DesiredAlignment); 22505ffd83dbSDimitry Andric CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end()); 22515ffd83dbSDimitry Andric 22525ffd83dbSDimitry Andric DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); 22535ffd83dbSDimitry Andric 22545ffd83dbSDimitry Andric checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, 22555ffd83dbSDimitry Andric /*IsMemberFunction=*/false, StartLoc, Range, CallType); 22560b57cec5SDimitry Andric 22570b57cec5SDimitry Andric // Warn if the type is over-aligned and is being allocated by (unaligned) 22580b57cec5SDimitry Andric // global operator new. 22590b57cec5SDimitry Andric if (PlacementArgs.empty() && !PassAlignment && 22600b57cec5SDimitry Andric (OperatorNew->isImplicit() || 22610b57cec5SDimitry Andric (OperatorNew->getBeginLoc().isValid() && 22620b57cec5SDimitry Andric getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { 22630b57cec5SDimitry Andric if (Alignment > NewAlignment) 22640b57cec5SDimitry Andric Diag(StartLoc, diag::warn_overaligned_type) 22650b57cec5SDimitry Andric << AllocType 22660b57cec5SDimitry Andric << unsigned(Alignment / Context.getCharWidth()) 22670b57cec5SDimitry Andric << unsigned(NewAlignment / Context.getCharWidth()); 22680b57cec5SDimitry Andric } 22690b57cec5SDimitry Andric } 22700b57cec5SDimitry Andric 22710b57cec5SDimitry Andric // Array 'new' can't have any initializers except empty parentheses. 22720b57cec5SDimitry Andric // Initializer lists are also allowed, in C++11. Rely on the parser for the 22730b57cec5SDimitry Andric // dialect distinction. 22740b57cec5SDimitry Andric if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { 22750b57cec5SDimitry Andric SourceRange InitRange(Inits[0]->getBeginLoc(), 22760b57cec5SDimitry Andric Inits[NumInits - 1]->getEndLoc()); 22770b57cec5SDimitry Andric Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 22780b57cec5SDimitry Andric return ExprError(); 22790b57cec5SDimitry Andric } 22800b57cec5SDimitry Andric 22810b57cec5SDimitry Andric // If we can perform the initialization, and we've not already done so, 22820b57cec5SDimitry Andric // do it now. 22830b57cec5SDimitry Andric if (!AllocType->isDependentType() && 22840b57cec5SDimitry Andric !Expr::hasAnyTypeDependentArguments( 22850b57cec5SDimitry Andric llvm::makeArrayRef(Inits, NumInits))) { 22860b57cec5SDimitry Andric // The type we initialize is the complete type, including the array bound. 22870b57cec5SDimitry Andric QualType InitType; 22880b57cec5SDimitry Andric if (KnownArraySize) 22890b57cec5SDimitry Andric InitType = Context.getConstantArrayType( 2290a7dea167SDimitry Andric AllocType, 2291a7dea167SDimitry Andric llvm::APInt(Context.getTypeSize(Context.getSizeType()), 22920b57cec5SDimitry Andric *KnownArraySize), 2293a7dea167SDimitry Andric *ArraySize, ArrayType::Normal, 0); 22940b57cec5SDimitry Andric else if (ArraySize) 22950b57cec5SDimitry Andric InitType = 22960b57cec5SDimitry Andric Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); 22970b57cec5SDimitry Andric else 22980b57cec5SDimitry Andric InitType = AllocType; 22990b57cec5SDimitry Andric 23000b57cec5SDimitry Andric InitializedEntity Entity 23010b57cec5SDimitry Andric = InitializedEntity::InitializeNew(StartLoc, InitType); 23020b57cec5SDimitry Andric InitializationSequence InitSeq(*this, Entity, Kind, 23030b57cec5SDimitry Andric MultiExprArg(Inits, NumInits)); 23040b57cec5SDimitry Andric ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 23050b57cec5SDimitry Andric MultiExprArg(Inits, NumInits)); 23060b57cec5SDimitry Andric if (FullInit.isInvalid()) 23070b57cec5SDimitry Andric return ExprError(); 23080b57cec5SDimitry Andric 23090b57cec5SDimitry Andric // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 23100b57cec5SDimitry Andric // we don't want the initialized object to be destructed. 23110b57cec5SDimitry Andric // FIXME: We should not create these in the first place. 23120b57cec5SDimitry Andric if (CXXBindTemporaryExpr *Binder = 23130b57cec5SDimitry Andric dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 23140b57cec5SDimitry Andric FullInit = Binder->getSubExpr(); 23150b57cec5SDimitry Andric 23160b57cec5SDimitry Andric Initializer = FullInit.get(); 23170b57cec5SDimitry Andric 23180b57cec5SDimitry Andric // FIXME: If we have a KnownArraySize, check that the array bound of the 23190b57cec5SDimitry Andric // initializer is no greater than that constant value. 23200b57cec5SDimitry Andric 23210b57cec5SDimitry Andric if (ArraySize && !*ArraySize) { 23220b57cec5SDimitry Andric auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); 23230b57cec5SDimitry Andric if (CAT) { 23240b57cec5SDimitry Andric // FIXME: Track that the array size was inferred rather than explicitly 23250b57cec5SDimitry Andric // specified. 23260b57cec5SDimitry Andric ArraySize = IntegerLiteral::Create( 23270b57cec5SDimitry Andric Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); 23280b57cec5SDimitry Andric } else { 23290b57cec5SDimitry Andric Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) 23300b57cec5SDimitry Andric << Initializer->getSourceRange(); 23310b57cec5SDimitry Andric } 23320b57cec5SDimitry Andric } 23330b57cec5SDimitry Andric } 23340b57cec5SDimitry Andric 23350b57cec5SDimitry Andric // Mark the new and delete operators as referenced. 23360b57cec5SDimitry Andric if (OperatorNew) { 23370b57cec5SDimitry Andric if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 23380b57cec5SDimitry Andric return ExprError(); 23390b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorNew); 23400b57cec5SDimitry Andric } 23410b57cec5SDimitry Andric if (OperatorDelete) { 23420b57cec5SDimitry Andric if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 23430b57cec5SDimitry Andric return ExprError(); 23440b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorDelete); 23450b57cec5SDimitry Andric } 23460b57cec5SDimitry Andric 23470b57cec5SDimitry Andric return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, 23480b57cec5SDimitry Andric PassAlignment, UsualArrayDeleteWantsSize, 23490b57cec5SDimitry Andric PlacementArgs, TypeIdParens, ArraySize, initStyle, 23500b57cec5SDimitry Andric Initializer, ResultType, AllocTypeInfo, Range, 23510b57cec5SDimitry Andric DirectInitRange); 23520b57cec5SDimitry Andric } 23530b57cec5SDimitry Andric 23540b57cec5SDimitry Andric /// Checks that a type is suitable as the allocated type 23550b57cec5SDimitry Andric /// in a new-expression. 23560b57cec5SDimitry Andric bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 23570b57cec5SDimitry Andric SourceRange R) { 23580b57cec5SDimitry Andric // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 23590b57cec5SDimitry Andric // abstract class type or array thereof. 23600b57cec5SDimitry Andric if (AllocType->isFunctionType()) 23610b57cec5SDimitry Andric return Diag(Loc, diag::err_bad_new_type) 23620b57cec5SDimitry Andric << AllocType << 0 << R; 23630b57cec5SDimitry Andric else if (AllocType->isReferenceType()) 23640b57cec5SDimitry Andric return Diag(Loc, diag::err_bad_new_type) 23650b57cec5SDimitry Andric << AllocType << 1 << R; 23660b57cec5SDimitry Andric else if (!AllocType->isDependentType() && 23675ffd83dbSDimitry Andric RequireCompleteSizedType( 23685ffd83dbSDimitry Andric Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) 23690b57cec5SDimitry Andric return true; 23700b57cec5SDimitry Andric else if (RequireNonAbstractType(Loc, AllocType, 23710b57cec5SDimitry Andric diag::err_allocation_of_abstract_type)) 23720b57cec5SDimitry Andric return true; 23730b57cec5SDimitry Andric else if (AllocType->isVariablyModifiedType()) 23740b57cec5SDimitry Andric return Diag(Loc, diag::err_variably_modified_new_type) 23750b57cec5SDimitry Andric << AllocType; 23760b57cec5SDimitry Andric else if (AllocType.getAddressSpace() != LangAS::Default && 23770b57cec5SDimitry Andric !getLangOpts().OpenCLCPlusPlus) 23780b57cec5SDimitry Andric return Diag(Loc, diag::err_address_space_qualified_new) 23790b57cec5SDimitry Andric << AllocType.getUnqualifiedType() 23800b57cec5SDimitry Andric << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); 23810b57cec5SDimitry Andric else if (getLangOpts().ObjCAutoRefCount) { 23820b57cec5SDimitry Andric if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 23830b57cec5SDimitry Andric QualType BaseAllocType = Context.getBaseElementType(AT); 23840b57cec5SDimitry Andric if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 23850b57cec5SDimitry Andric BaseAllocType->isObjCLifetimeType()) 23860b57cec5SDimitry Andric return Diag(Loc, diag::err_arc_new_array_without_ownership) 23870b57cec5SDimitry Andric << BaseAllocType; 23880b57cec5SDimitry Andric } 23890b57cec5SDimitry Andric } 23900b57cec5SDimitry Andric 23910b57cec5SDimitry Andric return false; 23920b57cec5SDimitry Andric } 23930b57cec5SDimitry Andric 23940b57cec5SDimitry Andric static bool resolveAllocationOverload( 23950b57cec5SDimitry Andric Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, 23960b57cec5SDimitry Andric bool &PassAlignment, FunctionDecl *&Operator, 23970b57cec5SDimitry Andric OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { 23980b57cec5SDimitry Andric OverloadCandidateSet Candidates(R.getNameLoc(), 23990b57cec5SDimitry Andric OverloadCandidateSet::CSK_Normal); 24000b57cec5SDimitry Andric for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 24010b57cec5SDimitry Andric Alloc != AllocEnd; ++Alloc) { 24020b57cec5SDimitry Andric // Even member operator new/delete are implicitly treated as 24030b57cec5SDimitry Andric // static, so don't use AddMemberCandidate. 24040b57cec5SDimitry Andric NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 24050b57cec5SDimitry Andric 24060b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 24070b57cec5SDimitry Andric S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 24080b57cec5SDimitry Andric /*ExplicitTemplateArgs=*/nullptr, Args, 24090b57cec5SDimitry Andric Candidates, 24100b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 24110b57cec5SDimitry Andric continue; 24120b57cec5SDimitry Andric } 24130b57cec5SDimitry Andric 24140b57cec5SDimitry Andric FunctionDecl *Fn = cast<FunctionDecl>(D); 24150b57cec5SDimitry Andric S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 24160b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 24170b57cec5SDimitry Andric } 24180b57cec5SDimitry Andric 24190b57cec5SDimitry Andric // Do the resolution. 24200b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 24210b57cec5SDimitry Andric switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 24220b57cec5SDimitry Andric case OR_Success: { 24230b57cec5SDimitry Andric // Got one! 24240b57cec5SDimitry Andric FunctionDecl *FnDecl = Best->Function; 24250b57cec5SDimitry Andric if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 24260b57cec5SDimitry Andric Best->FoundDecl) == Sema::AR_inaccessible) 24270b57cec5SDimitry Andric return true; 24280b57cec5SDimitry Andric 24290b57cec5SDimitry Andric Operator = FnDecl; 24300b57cec5SDimitry Andric return false; 24310b57cec5SDimitry Andric } 24320b57cec5SDimitry Andric 24330b57cec5SDimitry Andric case OR_No_Viable_Function: 24340b57cec5SDimitry Andric // C++17 [expr.new]p13: 24350b57cec5SDimitry Andric // If no matching function is found and the allocated object type has 24360b57cec5SDimitry Andric // new-extended alignment, the alignment argument is removed from the 24370b57cec5SDimitry Andric // argument list, and overload resolution is performed again. 24380b57cec5SDimitry Andric if (PassAlignment) { 24390b57cec5SDimitry Andric PassAlignment = false; 24400b57cec5SDimitry Andric AlignArg = Args[1]; 24410b57cec5SDimitry Andric Args.erase(Args.begin() + 1); 24420b57cec5SDimitry Andric return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 24430b57cec5SDimitry Andric Operator, &Candidates, AlignArg, 24440b57cec5SDimitry Andric Diagnose); 24450b57cec5SDimitry Andric } 24460b57cec5SDimitry Andric 24470b57cec5SDimitry Andric // MSVC will fall back on trying to find a matching global operator new 24480b57cec5SDimitry Andric // if operator new[] cannot be found. Also, MSVC will leak by not 24490b57cec5SDimitry Andric // generating a call to operator delete or operator delete[], but we 24500b57cec5SDimitry Andric // will not replicate that bug. 24510b57cec5SDimitry Andric // FIXME: Find out how this interacts with the std::align_val_t fallback 24520b57cec5SDimitry Andric // once MSVC implements it. 24530b57cec5SDimitry Andric if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 24540b57cec5SDimitry Andric S.Context.getLangOpts().MSVCCompat) { 24550b57cec5SDimitry Andric R.clear(); 24560b57cec5SDimitry Andric R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 24570b57cec5SDimitry Andric S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 24580b57cec5SDimitry Andric // FIXME: This will give bad diagnostics pointing at the wrong functions. 24590b57cec5SDimitry Andric return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 24600b57cec5SDimitry Andric Operator, /*Candidates=*/nullptr, 24610b57cec5SDimitry Andric /*AlignArg=*/nullptr, Diagnose); 24620b57cec5SDimitry Andric } 24630b57cec5SDimitry Andric 24640b57cec5SDimitry Andric if (Diagnose) { 24650b57cec5SDimitry Andric PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call) 24660b57cec5SDimitry Andric << R.getLookupName() << Range); 24670b57cec5SDimitry Andric 24680b57cec5SDimitry Andric // If we have aligned candidates, only note the align_val_t candidates 24690b57cec5SDimitry Andric // from AlignedCandidates and the non-align_val_t candidates from 24700b57cec5SDimitry Andric // Candidates. 24710b57cec5SDimitry Andric if (AlignedCandidates) { 24720b57cec5SDimitry Andric auto IsAligned = [](OverloadCandidate &C) { 24730b57cec5SDimitry Andric return C.Function->getNumParams() > 1 && 24740b57cec5SDimitry Andric C.Function->getParamDecl(1)->getType()->isAlignValT(); 24750b57cec5SDimitry Andric }; 24760b57cec5SDimitry Andric auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 24770b57cec5SDimitry Andric 24780b57cec5SDimitry Andric // This was an overaligned allocation, so list the aligned candidates 24790b57cec5SDimitry Andric // first. 24800b57cec5SDimitry Andric Args.insert(Args.begin() + 1, AlignArg); 24810b57cec5SDimitry Andric AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "", 24820b57cec5SDimitry Andric R.getNameLoc(), IsAligned); 24830b57cec5SDimitry Andric Args.erase(Args.begin() + 1); 24840b57cec5SDimitry Andric Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(), 24850b57cec5SDimitry Andric IsUnaligned); 24860b57cec5SDimitry Andric } else { 24870b57cec5SDimitry Andric Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args); 24880b57cec5SDimitry Andric } 24890b57cec5SDimitry Andric } 24900b57cec5SDimitry Andric return true; 24910b57cec5SDimitry Andric 24920b57cec5SDimitry Andric case OR_Ambiguous: 24930b57cec5SDimitry Andric if (Diagnose) { 24940b57cec5SDimitry Andric Candidates.NoteCandidates( 24950b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 24960b57cec5SDimitry Andric S.PDiag(diag::err_ovl_ambiguous_call) 24970b57cec5SDimitry Andric << R.getLookupName() << Range), 2498480093f4SDimitry Andric S, OCD_AmbiguousCandidates, Args); 24990b57cec5SDimitry Andric } 25000b57cec5SDimitry Andric return true; 25010b57cec5SDimitry Andric 25020b57cec5SDimitry Andric case OR_Deleted: { 25030b57cec5SDimitry Andric if (Diagnose) { 25040b57cec5SDimitry Andric Candidates.NoteCandidates( 25050b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 25060b57cec5SDimitry Andric S.PDiag(diag::err_ovl_deleted_call) 25070b57cec5SDimitry Andric << R.getLookupName() << Range), 25080b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 25090b57cec5SDimitry Andric } 25100b57cec5SDimitry Andric return true; 25110b57cec5SDimitry Andric } 25120b57cec5SDimitry Andric } 25130b57cec5SDimitry Andric llvm_unreachable("Unreachable, bad result from BestViableFunction"); 25140b57cec5SDimitry Andric } 25150b57cec5SDimitry Andric 25160b57cec5SDimitry Andric bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 25170b57cec5SDimitry Andric AllocationFunctionScope NewScope, 25180b57cec5SDimitry Andric AllocationFunctionScope DeleteScope, 25190b57cec5SDimitry Andric QualType AllocType, bool IsArray, 25200b57cec5SDimitry Andric bool &PassAlignment, MultiExprArg PlaceArgs, 25210b57cec5SDimitry Andric FunctionDecl *&OperatorNew, 25220b57cec5SDimitry Andric FunctionDecl *&OperatorDelete, 25230b57cec5SDimitry Andric bool Diagnose) { 25240b57cec5SDimitry Andric // --- Choosing an allocation function --- 25250b57cec5SDimitry Andric // C++ 5.3.4p8 - 14 & 18 25260b57cec5SDimitry Andric // 1) If looking in AFS_Global scope for allocation functions, only look in 25270b57cec5SDimitry Andric // the global scope. Else, if AFS_Class, only look in the scope of the 25280b57cec5SDimitry Andric // allocated class. If AFS_Both, look in both. 25290b57cec5SDimitry Andric // 2) If an array size is given, look for operator new[], else look for 25300b57cec5SDimitry Andric // operator new. 25310b57cec5SDimitry Andric // 3) The first argument is always size_t. Append the arguments from the 25320b57cec5SDimitry Andric // placement form. 25330b57cec5SDimitry Andric 25340b57cec5SDimitry Andric SmallVector<Expr*, 8> AllocArgs; 25350b57cec5SDimitry Andric AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 25360b57cec5SDimitry Andric 25370b57cec5SDimitry Andric // We don't care about the actual value of these arguments. 25380b57cec5SDimitry Andric // FIXME: Should the Sema create the expression and embed it in the syntax 25390b57cec5SDimitry Andric // tree? Or should the consumer just recalculate the value? 25400b57cec5SDimitry Andric // FIXME: Using a dummy value will interact poorly with attribute enable_if. 25410b57cec5SDimitry Andric IntegerLiteral Size(Context, llvm::APInt::getNullValue( 25420b57cec5SDimitry Andric Context.getTargetInfo().getPointerWidth(0)), 25430b57cec5SDimitry Andric Context.getSizeType(), 25440b57cec5SDimitry Andric SourceLocation()); 25450b57cec5SDimitry Andric AllocArgs.push_back(&Size); 25460b57cec5SDimitry Andric 25470b57cec5SDimitry Andric QualType AlignValT = Context.VoidTy; 25480b57cec5SDimitry Andric if (PassAlignment) { 25490b57cec5SDimitry Andric DeclareGlobalNewDelete(); 25500b57cec5SDimitry Andric AlignValT = Context.getTypeDeclType(getStdAlignValT()); 25510b57cec5SDimitry Andric } 25520b57cec5SDimitry Andric CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 25530b57cec5SDimitry Andric if (PassAlignment) 25540b57cec5SDimitry Andric AllocArgs.push_back(&Align); 25550b57cec5SDimitry Andric 25560b57cec5SDimitry Andric AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 25570b57cec5SDimitry Andric 25580b57cec5SDimitry Andric // C++ [expr.new]p8: 25590b57cec5SDimitry Andric // If the allocated type is a non-array type, the allocation 25600b57cec5SDimitry Andric // function's name is operator new and the deallocation function's 25610b57cec5SDimitry Andric // name is operator delete. If the allocated type is an array 25620b57cec5SDimitry Andric // type, the allocation function's name is operator new[] and the 25630b57cec5SDimitry Andric // deallocation function's name is operator delete[]. 25640b57cec5SDimitry Andric DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 25650b57cec5SDimitry Andric IsArray ? OO_Array_New : OO_New); 25660b57cec5SDimitry Andric 25670b57cec5SDimitry Andric QualType AllocElemType = Context.getBaseElementType(AllocType); 25680b57cec5SDimitry Andric 25690b57cec5SDimitry Andric // Find the allocation function. 25700b57cec5SDimitry Andric { 25710b57cec5SDimitry Andric LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 25720b57cec5SDimitry Andric 25730b57cec5SDimitry Andric // C++1z [expr.new]p9: 25740b57cec5SDimitry Andric // If the new-expression begins with a unary :: operator, the allocation 25750b57cec5SDimitry Andric // function's name is looked up in the global scope. Otherwise, if the 25760b57cec5SDimitry Andric // allocated type is a class type T or array thereof, the allocation 25770b57cec5SDimitry Andric // function's name is looked up in the scope of T. 25780b57cec5SDimitry Andric if (AllocElemType->isRecordType() && NewScope != AFS_Global) 25790b57cec5SDimitry Andric LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 25800b57cec5SDimitry Andric 25810b57cec5SDimitry Andric // We can see ambiguity here if the allocation function is found in 25820b57cec5SDimitry Andric // multiple base classes. 25830b57cec5SDimitry Andric if (R.isAmbiguous()) 25840b57cec5SDimitry Andric return true; 25850b57cec5SDimitry Andric 25860b57cec5SDimitry Andric // If this lookup fails to find the name, or if the allocated type is not 25870b57cec5SDimitry Andric // a class type, the allocation function's name is looked up in the 25880b57cec5SDimitry Andric // global scope. 25890b57cec5SDimitry Andric if (R.empty()) { 25900b57cec5SDimitry Andric if (NewScope == AFS_Class) 25910b57cec5SDimitry Andric return true; 25920b57cec5SDimitry Andric 25930b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 25940b57cec5SDimitry Andric } 25950b57cec5SDimitry Andric 25960b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus && R.empty()) { 25970b57cec5SDimitry Andric if (PlaceArgs.empty()) { 25980b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; 25990b57cec5SDimitry Andric } else { 26000b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_placement_new); 26010b57cec5SDimitry Andric } 26020b57cec5SDimitry Andric return true; 26030b57cec5SDimitry Andric } 26040b57cec5SDimitry Andric 26050b57cec5SDimitry Andric assert(!R.empty() && "implicitly declared allocation functions not found"); 26060b57cec5SDimitry Andric assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 26070b57cec5SDimitry Andric 26080b57cec5SDimitry Andric // We do our own custom access checks below. 26090b57cec5SDimitry Andric R.suppressDiagnostics(); 26100b57cec5SDimitry Andric 26110b57cec5SDimitry Andric if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 26120b57cec5SDimitry Andric OperatorNew, /*Candidates=*/nullptr, 26130b57cec5SDimitry Andric /*AlignArg=*/nullptr, Diagnose)) 26140b57cec5SDimitry Andric return true; 26150b57cec5SDimitry Andric } 26160b57cec5SDimitry Andric 26170b57cec5SDimitry Andric // We don't need an operator delete if we're running under -fno-exceptions. 26180b57cec5SDimitry Andric if (!getLangOpts().Exceptions) { 26190b57cec5SDimitry Andric OperatorDelete = nullptr; 26200b57cec5SDimitry Andric return false; 26210b57cec5SDimitry Andric } 26220b57cec5SDimitry Andric 26230b57cec5SDimitry Andric // Note, the name of OperatorNew might have been changed from array to 26240b57cec5SDimitry Andric // non-array by resolveAllocationOverload. 26250b57cec5SDimitry Andric DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 26260b57cec5SDimitry Andric OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 26270b57cec5SDimitry Andric ? OO_Array_Delete 26280b57cec5SDimitry Andric : OO_Delete); 26290b57cec5SDimitry Andric 26300b57cec5SDimitry Andric // C++ [expr.new]p19: 26310b57cec5SDimitry Andric // 26320b57cec5SDimitry Andric // If the new-expression begins with a unary :: operator, the 26330b57cec5SDimitry Andric // deallocation function's name is looked up in the global 26340b57cec5SDimitry Andric // scope. Otherwise, if the allocated type is a class type T or an 26350b57cec5SDimitry Andric // array thereof, the deallocation function's name is looked up in 26360b57cec5SDimitry Andric // the scope of T. If this lookup fails to find the name, or if 26370b57cec5SDimitry Andric // the allocated type is not a class type or array thereof, the 26380b57cec5SDimitry Andric // deallocation function's name is looked up in the global scope. 26390b57cec5SDimitry Andric LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 26400b57cec5SDimitry Andric if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { 2641a7dea167SDimitry Andric auto *RD = 2642a7dea167SDimitry Andric cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); 26430b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, RD); 26440b57cec5SDimitry Andric } 26450b57cec5SDimitry Andric if (FoundDelete.isAmbiguous()) 26460b57cec5SDimitry Andric return true; // FIXME: clean up expressions? 26470b57cec5SDimitry Andric 2648e8d8bef9SDimitry Andric // Filter out any destroying operator deletes. We can't possibly call such a 2649e8d8bef9SDimitry Andric // function in this context, because we're handling the case where the object 2650e8d8bef9SDimitry Andric // was not successfully constructed. 2651e8d8bef9SDimitry Andric // FIXME: This is not covered by the language rules yet. 2652e8d8bef9SDimitry Andric { 2653e8d8bef9SDimitry Andric LookupResult::Filter Filter = FoundDelete.makeFilter(); 2654e8d8bef9SDimitry Andric while (Filter.hasNext()) { 2655e8d8bef9SDimitry Andric auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); 2656e8d8bef9SDimitry Andric if (FD && FD->isDestroyingOperatorDelete()) 2657e8d8bef9SDimitry Andric Filter.erase(); 2658e8d8bef9SDimitry Andric } 2659e8d8bef9SDimitry Andric Filter.done(); 2660e8d8bef9SDimitry Andric } 2661e8d8bef9SDimitry Andric 26620b57cec5SDimitry Andric bool FoundGlobalDelete = FoundDelete.empty(); 26630b57cec5SDimitry Andric if (FoundDelete.empty()) { 2664e8d8bef9SDimitry Andric FoundDelete.clear(LookupOrdinaryName); 2665e8d8bef9SDimitry Andric 26660b57cec5SDimitry Andric if (DeleteScope == AFS_Class) 26670b57cec5SDimitry Andric return true; 26680b57cec5SDimitry Andric 26690b57cec5SDimitry Andric DeclareGlobalNewDelete(); 26700b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 26710b57cec5SDimitry Andric } 26720b57cec5SDimitry Andric 26730b57cec5SDimitry Andric FoundDelete.suppressDiagnostics(); 26740b57cec5SDimitry Andric 26750b57cec5SDimitry Andric SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 26760b57cec5SDimitry Andric 26770b57cec5SDimitry Andric // Whether we're looking for a placement operator delete is dictated 26780b57cec5SDimitry Andric // by whether we selected a placement operator new, not by whether 26790b57cec5SDimitry Andric // we had explicit placement arguments. This matters for things like 26800b57cec5SDimitry Andric // struct A { void *operator new(size_t, int = 0); ... }; 26810b57cec5SDimitry Andric // A *a = new A() 26820b57cec5SDimitry Andric // 26830b57cec5SDimitry Andric // We don't have any definition for what a "placement allocation function" 26840b57cec5SDimitry Andric // is, but we assume it's any allocation function whose 26850b57cec5SDimitry Andric // parameter-declaration-clause is anything other than (size_t). 26860b57cec5SDimitry Andric // 26870b57cec5SDimitry Andric // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 26880b57cec5SDimitry Andric // This affects whether an exception from the constructor of an overaligned 26890b57cec5SDimitry Andric // type uses the sized or non-sized form of aligned operator delete. 26900b57cec5SDimitry Andric bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 26910b57cec5SDimitry Andric OperatorNew->isVariadic(); 26920b57cec5SDimitry Andric 26930b57cec5SDimitry Andric if (isPlacementNew) { 26940b57cec5SDimitry Andric // C++ [expr.new]p20: 26950b57cec5SDimitry Andric // A declaration of a placement deallocation function matches the 26960b57cec5SDimitry Andric // declaration of a placement allocation function if it has the 26970b57cec5SDimitry Andric // same number of parameters and, after parameter transformations 26980b57cec5SDimitry Andric // (8.3.5), all parameter types except the first are 26990b57cec5SDimitry Andric // identical. [...] 27000b57cec5SDimitry Andric // 27010b57cec5SDimitry Andric // To perform this comparison, we compute the function type that 27020b57cec5SDimitry Andric // the deallocation function should have, and use that type both 27030b57cec5SDimitry Andric // for template argument deduction and for comparison purposes. 27040b57cec5SDimitry Andric QualType ExpectedFunctionType; 27050b57cec5SDimitry Andric { 27065ffd83dbSDimitry Andric auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 27070b57cec5SDimitry Andric 27080b57cec5SDimitry Andric SmallVector<QualType, 4> ArgTypes; 27090b57cec5SDimitry Andric ArgTypes.push_back(Context.VoidPtrTy); 27100b57cec5SDimitry Andric for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 27110b57cec5SDimitry Andric ArgTypes.push_back(Proto->getParamType(I)); 27120b57cec5SDimitry Andric 27130b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI; 27140b57cec5SDimitry Andric // FIXME: This is not part of the standard's rule. 27150b57cec5SDimitry Andric EPI.Variadic = Proto->isVariadic(); 27160b57cec5SDimitry Andric 27170b57cec5SDimitry Andric ExpectedFunctionType 27180b57cec5SDimitry Andric = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 27190b57cec5SDimitry Andric } 27200b57cec5SDimitry Andric 27210b57cec5SDimitry Andric for (LookupResult::iterator D = FoundDelete.begin(), 27220b57cec5SDimitry Andric DEnd = FoundDelete.end(); 27230b57cec5SDimitry Andric D != DEnd; ++D) { 27240b57cec5SDimitry Andric FunctionDecl *Fn = nullptr; 27250b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTmpl = 27260b57cec5SDimitry Andric dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 27270b57cec5SDimitry Andric // Perform template argument deduction to try to match the 27280b57cec5SDimitry Andric // expected function type. 27290b57cec5SDimitry Andric TemplateDeductionInfo Info(StartLoc); 27300b57cec5SDimitry Andric if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 27310b57cec5SDimitry Andric Info)) 27320b57cec5SDimitry Andric continue; 27330b57cec5SDimitry Andric } else 27340b57cec5SDimitry Andric Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 27350b57cec5SDimitry Andric 27360b57cec5SDimitry Andric if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), 27370b57cec5SDimitry Andric ExpectedFunctionType, 27380b57cec5SDimitry Andric /*AdjustExcpetionSpec*/true), 27390b57cec5SDimitry Andric ExpectedFunctionType)) 27400b57cec5SDimitry Andric Matches.push_back(std::make_pair(D.getPair(), Fn)); 27410b57cec5SDimitry Andric } 27420b57cec5SDimitry Andric 27430b57cec5SDimitry Andric if (getLangOpts().CUDA) 27440b57cec5SDimitry Andric EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); 27450b57cec5SDimitry Andric } else { 27460b57cec5SDimitry Andric // C++1y [expr.new]p22: 27470b57cec5SDimitry Andric // For a non-placement allocation function, the normal deallocation 27480b57cec5SDimitry Andric // function lookup is used 27490b57cec5SDimitry Andric // 27500b57cec5SDimitry Andric // Per [expr.delete]p10, this lookup prefers a member operator delete 27510b57cec5SDimitry Andric // without a size_t argument, but prefers a non-member operator delete 27520b57cec5SDimitry Andric // with a size_t where possible (which it always is in this case). 27530b57cec5SDimitry Andric llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 27540b57cec5SDimitry Andric UsualDeallocFnInfo Selected = resolveDeallocationOverload( 27550b57cec5SDimitry Andric *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 27560b57cec5SDimitry Andric /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 27570b57cec5SDimitry Andric &BestDeallocFns); 27580b57cec5SDimitry Andric if (Selected) 27590b57cec5SDimitry Andric Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 27600b57cec5SDimitry Andric else { 27610b57cec5SDimitry Andric // If we failed to select an operator, all remaining functions are viable 27620b57cec5SDimitry Andric // but ambiguous. 27630b57cec5SDimitry Andric for (auto Fn : BestDeallocFns) 27640b57cec5SDimitry Andric Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 27650b57cec5SDimitry Andric } 27660b57cec5SDimitry Andric } 27670b57cec5SDimitry Andric 27680b57cec5SDimitry Andric // C++ [expr.new]p20: 27690b57cec5SDimitry Andric // [...] If the lookup finds a single matching deallocation 27700b57cec5SDimitry Andric // function, that function will be called; otherwise, no 27710b57cec5SDimitry Andric // deallocation function will be called. 27720b57cec5SDimitry Andric if (Matches.size() == 1) { 27730b57cec5SDimitry Andric OperatorDelete = Matches[0].second; 27740b57cec5SDimitry Andric 27750b57cec5SDimitry Andric // C++1z [expr.new]p23: 27760b57cec5SDimitry Andric // If the lookup finds a usual deallocation function (3.7.4.2) 27770b57cec5SDimitry Andric // with a parameter of type std::size_t and that function, considered 27780b57cec5SDimitry Andric // as a placement deallocation function, would have been 27790b57cec5SDimitry Andric // selected as a match for the allocation function, the program 27800b57cec5SDimitry Andric // is ill-formed. 27810b57cec5SDimitry Andric if (getLangOpts().CPlusPlus11 && isPlacementNew && 27820b57cec5SDimitry Andric isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 27830b57cec5SDimitry Andric UsualDeallocFnInfo Info(*this, 27840b57cec5SDimitry Andric DeclAccessPair::make(OperatorDelete, AS_public)); 27850b57cec5SDimitry Andric // Core issue, per mail to core reflector, 2016-10-09: 27860b57cec5SDimitry Andric // If this is a member operator delete, and there is a corresponding 27870b57cec5SDimitry Andric // non-sized member operator delete, this isn't /really/ a sized 27880b57cec5SDimitry Andric // deallocation function, it just happens to have a size_t parameter. 27890b57cec5SDimitry Andric bool IsSizedDelete = Info.HasSizeT; 27900b57cec5SDimitry Andric if (IsSizedDelete && !FoundGlobalDelete) { 27910b57cec5SDimitry Andric auto NonSizedDelete = 27920b57cec5SDimitry Andric resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 27930b57cec5SDimitry Andric /*WantAlign*/Info.HasAlignValT); 27940b57cec5SDimitry Andric if (NonSizedDelete && !NonSizedDelete.HasSizeT && 27950b57cec5SDimitry Andric NonSizedDelete.HasAlignValT == Info.HasAlignValT) 27960b57cec5SDimitry Andric IsSizedDelete = false; 27970b57cec5SDimitry Andric } 27980b57cec5SDimitry Andric 27990b57cec5SDimitry Andric if (IsSizedDelete) { 28000b57cec5SDimitry Andric SourceRange R = PlaceArgs.empty() 28010b57cec5SDimitry Andric ? SourceRange() 28020b57cec5SDimitry Andric : SourceRange(PlaceArgs.front()->getBeginLoc(), 28030b57cec5SDimitry Andric PlaceArgs.back()->getEndLoc()); 28040b57cec5SDimitry Andric Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 28050b57cec5SDimitry Andric if (!OperatorDelete->isImplicit()) 28060b57cec5SDimitry Andric Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 28070b57cec5SDimitry Andric << DeleteName; 28080b57cec5SDimitry Andric } 28090b57cec5SDimitry Andric } 28100b57cec5SDimitry Andric 28110b57cec5SDimitry Andric CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 28120b57cec5SDimitry Andric Matches[0].first); 28130b57cec5SDimitry Andric } else if (!Matches.empty()) { 28140b57cec5SDimitry Andric // We found multiple suitable operators. Per [expr.new]p20, that means we 28150b57cec5SDimitry Andric // call no 'operator delete' function, but we should at least warn the user. 28160b57cec5SDimitry Andric // FIXME: Suppress this warning if the construction cannot throw. 28170b57cec5SDimitry Andric Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 28180b57cec5SDimitry Andric << DeleteName << AllocElemType; 28190b57cec5SDimitry Andric 28200b57cec5SDimitry Andric for (auto &Match : Matches) 28210b57cec5SDimitry Andric Diag(Match.second->getLocation(), 28220b57cec5SDimitry Andric diag::note_member_declared_here) << DeleteName; 28230b57cec5SDimitry Andric } 28240b57cec5SDimitry Andric 28250b57cec5SDimitry Andric return false; 28260b57cec5SDimitry Andric } 28270b57cec5SDimitry Andric 28280b57cec5SDimitry Andric /// DeclareGlobalNewDelete - Declare the global forms of operator new and 28290b57cec5SDimitry Andric /// delete. These are: 28300b57cec5SDimitry Andric /// @code 28310b57cec5SDimitry Andric /// // C++03: 28320b57cec5SDimitry Andric /// void* operator new(std::size_t) throw(std::bad_alloc); 28330b57cec5SDimitry Andric /// void* operator new[](std::size_t) throw(std::bad_alloc); 28340b57cec5SDimitry Andric /// void operator delete(void *) throw(); 28350b57cec5SDimitry Andric /// void operator delete[](void *) throw(); 28360b57cec5SDimitry Andric /// // C++11: 28370b57cec5SDimitry Andric /// void* operator new(std::size_t); 28380b57cec5SDimitry Andric /// void* operator new[](std::size_t); 28390b57cec5SDimitry Andric /// void operator delete(void *) noexcept; 28400b57cec5SDimitry Andric /// void operator delete[](void *) noexcept; 28410b57cec5SDimitry Andric /// // C++1y: 28420b57cec5SDimitry Andric /// void* operator new(std::size_t); 28430b57cec5SDimitry Andric /// void* operator new[](std::size_t); 28440b57cec5SDimitry Andric /// void operator delete(void *) noexcept; 28450b57cec5SDimitry Andric /// void operator delete[](void *) noexcept; 28460b57cec5SDimitry Andric /// void operator delete(void *, std::size_t) noexcept; 28470b57cec5SDimitry Andric /// void operator delete[](void *, std::size_t) noexcept; 28480b57cec5SDimitry Andric /// @endcode 28490b57cec5SDimitry Andric /// Note that the placement and nothrow forms of new are *not* implicitly 28500b57cec5SDimitry Andric /// declared. Their use requires including \<new\>. 28510b57cec5SDimitry Andric void Sema::DeclareGlobalNewDelete() { 28520b57cec5SDimitry Andric if (GlobalNewDeleteDeclared) 28530b57cec5SDimitry Andric return; 28540b57cec5SDimitry Andric 28550b57cec5SDimitry Andric // The implicitly declared new and delete operators 28560b57cec5SDimitry Andric // are not supported in OpenCL. 28570b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) 28580b57cec5SDimitry Andric return; 28590b57cec5SDimitry Andric 28600b57cec5SDimitry Andric // C++ [basic.std.dynamic]p2: 28610b57cec5SDimitry Andric // [...] The following allocation and deallocation functions (18.4) are 28620b57cec5SDimitry Andric // implicitly declared in global scope in each translation unit of a 28630b57cec5SDimitry Andric // program 28640b57cec5SDimitry Andric // 28650b57cec5SDimitry Andric // C++03: 28660b57cec5SDimitry Andric // void* operator new(std::size_t) throw(std::bad_alloc); 28670b57cec5SDimitry Andric // void* operator new[](std::size_t) throw(std::bad_alloc); 28680b57cec5SDimitry Andric // void operator delete(void*) throw(); 28690b57cec5SDimitry Andric // void operator delete[](void*) throw(); 28700b57cec5SDimitry Andric // C++11: 28710b57cec5SDimitry Andric // void* operator new(std::size_t); 28720b57cec5SDimitry Andric // void* operator new[](std::size_t); 28730b57cec5SDimitry Andric // void operator delete(void*) noexcept; 28740b57cec5SDimitry Andric // void operator delete[](void*) noexcept; 28750b57cec5SDimitry Andric // C++1y: 28760b57cec5SDimitry Andric // void* operator new(std::size_t); 28770b57cec5SDimitry Andric // void* operator new[](std::size_t); 28780b57cec5SDimitry Andric // void operator delete(void*) noexcept; 28790b57cec5SDimitry Andric // void operator delete[](void*) noexcept; 28800b57cec5SDimitry Andric // void operator delete(void*, std::size_t) noexcept; 28810b57cec5SDimitry Andric // void operator delete[](void*, std::size_t) noexcept; 28820b57cec5SDimitry Andric // 28830b57cec5SDimitry Andric // These implicit declarations introduce only the function names operator 28840b57cec5SDimitry Andric // new, operator new[], operator delete, operator delete[]. 28850b57cec5SDimitry Andric // 28860b57cec5SDimitry Andric // Here, we need to refer to std::bad_alloc, so we will implicitly declare 28870b57cec5SDimitry Andric // "std" or "bad_alloc" as necessary to form the exception specification. 28880b57cec5SDimitry Andric // However, we do not make these implicit declarations visible to name 28890b57cec5SDimitry Andric // lookup. 28900b57cec5SDimitry Andric if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 28910b57cec5SDimitry Andric // The "std::bad_alloc" class has not yet been declared, so build it 28920b57cec5SDimitry Andric // implicitly. 28930b57cec5SDimitry Andric StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 28940b57cec5SDimitry Andric getOrCreateStdNamespace(), 28950b57cec5SDimitry Andric SourceLocation(), SourceLocation(), 28960b57cec5SDimitry Andric &PP.getIdentifierTable().get("bad_alloc"), 28970b57cec5SDimitry Andric nullptr); 28980b57cec5SDimitry Andric getStdBadAlloc()->setImplicit(true); 28990b57cec5SDimitry Andric } 29000b57cec5SDimitry Andric if (!StdAlignValT && getLangOpts().AlignedAllocation) { 29010b57cec5SDimitry Andric // The "std::align_val_t" enum class has not yet been declared, so build it 29020b57cec5SDimitry Andric // implicitly. 29030b57cec5SDimitry Andric auto *AlignValT = EnumDecl::Create( 29040b57cec5SDimitry Andric Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 29050b57cec5SDimitry Andric &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 29060b57cec5SDimitry Andric AlignValT->setIntegerType(Context.getSizeType()); 29070b57cec5SDimitry Andric AlignValT->setPromotionType(Context.getSizeType()); 29080b57cec5SDimitry Andric AlignValT->setImplicit(true); 29090b57cec5SDimitry Andric StdAlignValT = AlignValT; 29100b57cec5SDimitry Andric } 29110b57cec5SDimitry Andric 29120b57cec5SDimitry Andric GlobalNewDeleteDeclared = true; 29130b57cec5SDimitry Andric 29140b57cec5SDimitry Andric QualType VoidPtr = Context.getPointerType(Context.VoidTy); 29150b57cec5SDimitry Andric QualType SizeT = Context.getSizeType(); 29160b57cec5SDimitry Andric 29170b57cec5SDimitry Andric auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 29180b57cec5SDimitry Andric QualType Return, QualType Param) { 29190b57cec5SDimitry Andric llvm::SmallVector<QualType, 3> Params; 29200b57cec5SDimitry Andric Params.push_back(Param); 29210b57cec5SDimitry Andric 29220b57cec5SDimitry Andric // Create up to four variants of the function (sized/aligned). 29230b57cec5SDimitry Andric bool HasSizedVariant = getLangOpts().SizedDeallocation && 29240b57cec5SDimitry Andric (Kind == OO_Delete || Kind == OO_Array_Delete); 29250b57cec5SDimitry Andric bool HasAlignedVariant = getLangOpts().AlignedAllocation; 29260b57cec5SDimitry Andric 29270b57cec5SDimitry Andric int NumSizeVariants = (HasSizedVariant ? 2 : 1); 29280b57cec5SDimitry Andric int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 29290b57cec5SDimitry Andric for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 29300b57cec5SDimitry Andric if (Sized) 29310b57cec5SDimitry Andric Params.push_back(SizeT); 29320b57cec5SDimitry Andric 29330b57cec5SDimitry Andric for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 29340b57cec5SDimitry Andric if (Aligned) 29350b57cec5SDimitry Andric Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 29360b57cec5SDimitry Andric 29370b57cec5SDimitry Andric DeclareGlobalAllocationFunction( 29380b57cec5SDimitry Andric Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 29390b57cec5SDimitry Andric 29400b57cec5SDimitry Andric if (Aligned) 29410b57cec5SDimitry Andric Params.pop_back(); 29420b57cec5SDimitry Andric } 29430b57cec5SDimitry Andric } 29440b57cec5SDimitry Andric }; 29450b57cec5SDimitry Andric 29460b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 29470b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 29480b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 29490b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 29500b57cec5SDimitry Andric } 29510b57cec5SDimitry Andric 29520b57cec5SDimitry Andric /// DeclareGlobalAllocationFunction - Declares a single implicit global 29530b57cec5SDimitry Andric /// allocation function if it doesn't already exist. 29540b57cec5SDimitry Andric void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 29550b57cec5SDimitry Andric QualType Return, 29560b57cec5SDimitry Andric ArrayRef<QualType> Params) { 29570b57cec5SDimitry Andric DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 29580b57cec5SDimitry Andric 29590b57cec5SDimitry Andric // Check if this function is already declared. 29600b57cec5SDimitry Andric DeclContext::lookup_result R = GlobalCtx->lookup(Name); 29610b57cec5SDimitry Andric for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 29620b57cec5SDimitry Andric Alloc != AllocEnd; ++Alloc) { 29630b57cec5SDimitry Andric // Only look at non-template functions, as it is the predefined, 29640b57cec5SDimitry Andric // non-templated allocation function we are trying to declare here. 29650b57cec5SDimitry Andric if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 29660b57cec5SDimitry Andric if (Func->getNumParams() == Params.size()) { 29670b57cec5SDimitry Andric llvm::SmallVector<QualType, 3> FuncParams; 29680b57cec5SDimitry Andric for (auto *P : Func->parameters()) 29690b57cec5SDimitry Andric FuncParams.push_back( 29700b57cec5SDimitry Andric Context.getCanonicalType(P->getType().getUnqualifiedType())); 29710b57cec5SDimitry Andric if (llvm::makeArrayRef(FuncParams) == Params) { 29720b57cec5SDimitry Andric // Make the function visible to name lookup, even if we found it in 29730b57cec5SDimitry Andric // an unimported module. It either is an implicitly-declared global 29740b57cec5SDimitry Andric // allocation function, or is suppressing that function. 29750b57cec5SDimitry Andric Func->setVisibleDespiteOwningModule(); 29760b57cec5SDimitry Andric return; 29770b57cec5SDimitry Andric } 29780b57cec5SDimitry Andric } 29790b57cec5SDimitry Andric } 29800b57cec5SDimitry Andric } 29810b57cec5SDimitry Andric 29820b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 29830b57cec5SDimitry Andric /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 29840b57cec5SDimitry Andric 29850b57cec5SDimitry Andric QualType BadAllocType; 29860b57cec5SDimitry Andric bool HasBadAllocExceptionSpec 29870b57cec5SDimitry Andric = (Name.getCXXOverloadedOperator() == OO_New || 29880b57cec5SDimitry Andric Name.getCXXOverloadedOperator() == OO_Array_New); 29890b57cec5SDimitry Andric if (HasBadAllocExceptionSpec) { 29900b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus11) { 29910b57cec5SDimitry Andric BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 29920b57cec5SDimitry Andric assert(StdBadAlloc && "Must have std::bad_alloc declared"); 29930b57cec5SDimitry Andric EPI.ExceptionSpec.Type = EST_Dynamic; 29940b57cec5SDimitry Andric EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); 29950b57cec5SDimitry Andric } 29960b57cec5SDimitry Andric } else { 29970b57cec5SDimitry Andric EPI.ExceptionSpec = 29980b57cec5SDimitry Andric getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 29990b57cec5SDimitry Andric } 30000b57cec5SDimitry Andric 30010b57cec5SDimitry Andric auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 30020b57cec5SDimitry Andric QualType FnType = Context.getFunctionType(Return, Params, EPI); 30030b57cec5SDimitry Andric FunctionDecl *Alloc = FunctionDecl::Create( 30040b57cec5SDimitry Andric Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, 30050b57cec5SDimitry Andric FnType, /*TInfo=*/nullptr, SC_None, false, true); 30060b57cec5SDimitry Andric Alloc->setImplicit(); 30070b57cec5SDimitry Andric // Global allocation functions should always be visible. 30080b57cec5SDimitry Andric Alloc->setVisibleDespiteOwningModule(); 30090b57cec5SDimitry Andric 30100b57cec5SDimitry Andric Alloc->addAttr(VisibilityAttr::CreateImplicit( 30110b57cec5SDimitry Andric Context, LangOpts.GlobalAllocationFunctionVisibilityHidden 30120b57cec5SDimitry Andric ? VisibilityAttr::Hidden 30130b57cec5SDimitry Andric : VisibilityAttr::Default)); 30140b57cec5SDimitry Andric 30150b57cec5SDimitry Andric llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 30160b57cec5SDimitry Andric for (QualType T : Params) { 30170b57cec5SDimitry Andric ParamDecls.push_back(ParmVarDecl::Create( 30180b57cec5SDimitry Andric Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 30190b57cec5SDimitry Andric /*TInfo=*/nullptr, SC_None, nullptr)); 30200b57cec5SDimitry Andric ParamDecls.back()->setImplicit(); 30210b57cec5SDimitry Andric } 30220b57cec5SDimitry Andric Alloc->setParams(ParamDecls); 30230b57cec5SDimitry Andric if (ExtraAttr) 30240b57cec5SDimitry Andric Alloc->addAttr(ExtraAttr); 30255ffd83dbSDimitry Andric AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); 30260b57cec5SDimitry Andric Context.getTranslationUnitDecl()->addDecl(Alloc); 30270b57cec5SDimitry Andric IdResolver.tryAddTopLevelDecl(Alloc, Name); 30280b57cec5SDimitry Andric }; 30290b57cec5SDimitry Andric 30300b57cec5SDimitry Andric if (!LangOpts.CUDA) 30310b57cec5SDimitry Andric CreateAllocationFunctionDecl(nullptr); 30320b57cec5SDimitry Andric else { 30330b57cec5SDimitry Andric // Host and device get their own declaration so each can be 30340b57cec5SDimitry Andric // defined or re-declared independently. 30350b57cec5SDimitry Andric CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 30360b57cec5SDimitry Andric CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 30370b57cec5SDimitry Andric } 30380b57cec5SDimitry Andric } 30390b57cec5SDimitry Andric 30400b57cec5SDimitry Andric FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 30410b57cec5SDimitry Andric bool CanProvideSize, 30420b57cec5SDimitry Andric bool Overaligned, 30430b57cec5SDimitry Andric DeclarationName Name) { 30440b57cec5SDimitry Andric DeclareGlobalNewDelete(); 30450b57cec5SDimitry Andric 30460b57cec5SDimitry Andric LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 30470b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 30480b57cec5SDimitry Andric 30490b57cec5SDimitry Andric // FIXME: It's possible for this to result in ambiguity, through a 30500b57cec5SDimitry Andric // user-declared variadic operator delete or the enable_if attribute. We 30510b57cec5SDimitry Andric // should probably not consider those cases to be usual deallocation 30520b57cec5SDimitry Andric // functions. But for now we just make an arbitrary choice in that case. 30530b57cec5SDimitry Andric auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 30540b57cec5SDimitry Andric Overaligned); 30550b57cec5SDimitry Andric assert(Result.FD && "operator delete missing from global scope?"); 30560b57cec5SDimitry Andric return Result.FD; 30570b57cec5SDimitry Andric } 30580b57cec5SDimitry Andric 30590b57cec5SDimitry Andric FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 30600b57cec5SDimitry Andric CXXRecordDecl *RD) { 30610b57cec5SDimitry Andric DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 30620b57cec5SDimitry Andric 30630b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 30640b57cec5SDimitry Andric if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 30650b57cec5SDimitry Andric return nullptr; 30660b57cec5SDimitry Andric if (OperatorDelete) 30670b57cec5SDimitry Andric return OperatorDelete; 30680b57cec5SDimitry Andric 30690b57cec5SDimitry Andric // If there's no class-specific operator delete, look up the global 30700b57cec5SDimitry Andric // non-array delete. 30710b57cec5SDimitry Andric return FindUsualDeallocationFunction( 30720b57cec5SDimitry Andric Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 30730b57cec5SDimitry Andric Name); 30740b57cec5SDimitry Andric } 30750b57cec5SDimitry Andric 30760b57cec5SDimitry Andric bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 30770b57cec5SDimitry Andric DeclarationName Name, 30780b57cec5SDimitry Andric FunctionDecl *&Operator, bool Diagnose) { 30790b57cec5SDimitry Andric LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 30800b57cec5SDimitry Andric // Try to find operator delete/operator delete[] in class scope. 30810b57cec5SDimitry Andric LookupQualifiedName(Found, RD); 30820b57cec5SDimitry Andric 30830b57cec5SDimitry Andric if (Found.isAmbiguous()) 30840b57cec5SDimitry Andric return true; 30850b57cec5SDimitry Andric 30860b57cec5SDimitry Andric Found.suppressDiagnostics(); 30870b57cec5SDimitry Andric 30880b57cec5SDimitry Andric bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 30890b57cec5SDimitry Andric 30900b57cec5SDimitry Andric // C++17 [expr.delete]p10: 30910b57cec5SDimitry Andric // If the deallocation functions have class scope, the one without a 30920b57cec5SDimitry Andric // parameter of type std::size_t is selected. 30930b57cec5SDimitry Andric llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 30940b57cec5SDimitry Andric resolveDeallocationOverload(*this, Found, /*WantSize*/ false, 30950b57cec5SDimitry Andric /*WantAlign*/ Overaligned, &Matches); 30960b57cec5SDimitry Andric 30970b57cec5SDimitry Andric // If we could find an overload, use it. 30980b57cec5SDimitry Andric if (Matches.size() == 1) { 30990b57cec5SDimitry Andric Operator = cast<CXXMethodDecl>(Matches[0].FD); 31000b57cec5SDimitry Andric 31010b57cec5SDimitry Andric // FIXME: DiagnoseUseOfDecl? 31020b57cec5SDimitry Andric if (Operator->isDeleted()) { 31030b57cec5SDimitry Andric if (Diagnose) { 31040b57cec5SDimitry Andric Diag(StartLoc, diag::err_deleted_function_use); 31050b57cec5SDimitry Andric NoteDeletedFunction(Operator); 31060b57cec5SDimitry Andric } 31070b57cec5SDimitry Andric return true; 31080b57cec5SDimitry Andric } 31090b57cec5SDimitry Andric 31100b57cec5SDimitry Andric if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 31110b57cec5SDimitry Andric Matches[0].Found, Diagnose) == AR_inaccessible) 31120b57cec5SDimitry Andric return true; 31130b57cec5SDimitry Andric 31140b57cec5SDimitry Andric return false; 31150b57cec5SDimitry Andric } 31160b57cec5SDimitry Andric 31170b57cec5SDimitry Andric // We found multiple suitable operators; complain about the ambiguity. 31180b57cec5SDimitry Andric // FIXME: The standard doesn't say to do this; it appears that the intent 31190b57cec5SDimitry Andric // is that this should never happen. 31200b57cec5SDimitry Andric if (!Matches.empty()) { 31210b57cec5SDimitry Andric if (Diagnose) { 31220b57cec5SDimitry Andric Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 31230b57cec5SDimitry Andric << Name << RD; 31240b57cec5SDimitry Andric for (auto &Match : Matches) 31250b57cec5SDimitry Andric Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 31260b57cec5SDimitry Andric } 31270b57cec5SDimitry Andric return true; 31280b57cec5SDimitry Andric } 31290b57cec5SDimitry Andric 31300b57cec5SDimitry Andric // We did find operator delete/operator delete[] declarations, but 31310b57cec5SDimitry Andric // none of them were suitable. 31320b57cec5SDimitry Andric if (!Found.empty()) { 31330b57cec5SDimitry Andric if (Diagnose) { 31340b57cec5SDimitry Andric Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 31350b57cec5SDimitry Andric << Name << RD; 31360b57cec5SDimitry Andric 31370b57cec5SDimitry Andric for (NamedDecl *D : Found) 31380b57cec5SDimitry Andric Diag(D->getUnderlyingDecl()->getLocation(), 31390b57cec5SDimitry Andric diag::note_member_declared_here) << Name; 31400b57cec5SDimitry Andric } 31410b57cec5SDimitry Andric return true; 31420b57cec5SDimitry Andric } 31430b57cec5SDimitry Andric 31440b57cec5SDimitry Andric Operator = nullptr; 31450b57cec5SDimitry Andric return false; 31460b57cec5SDimitry Andric } 31470b57cec5SDimitry Andric 31480b57cec5SDimitry Andric namespace { 31490b57cec5SDimitry Andric /// Checks whether delete-expression, and new-expression used for 31500b57cec5SDimitry Andric /// initializing deletee have the same array form. 31510b57cec5SDimitry Andric class MismatchingNewDeleteDetector { 31520b57cec5SDimitry Andric public: 31530b57cec5SDimitry Andric enum MismatchResult { 31540b57cec5SDimitry Andric /// Indicates that there is no mismatch or a mismatch cannot be proven. 31550b57cec5SDimitry Andric NoMismatch, 31560b57cec5SDimitry Andric /// Indicates that variable is initialized with mismatching form of \a new. 31570b57cec5SDimitry Andric VarInitMismatches, 31580b57cec5SDimitry Andric /// Indicates that member is initialized with mismatching form of \a new. 31590b57cec5SDimitry Andric MemberInitMismatches, 31600b57cec5SDimitry Andric /// Indicates that 1 or more constructors' definitions could not been 31610b57cec5SDimitry Andric /// analyzed, and they will be checked again at the end of translation unit. 31620b57cec5SDimitry Andric AnalyzeLater 31630b57cec5SDimitry Andric }; 31640b57cec5SDimitry Andric 31650b57cec5SDimitry Andric /// \param EndOfTU True, if this is the final analysis at the end of 31660b57cec5SDimitry Andric /// translation unit. False, if this is the initial analysis at the point 31670b57cec5SDimitry Andric /// delete-expression was encountered. 31680b57cec5SDimitry Andric explicit MismatchingNewDeleteDetector(bool EndOfTU) 31690b57cec5SDimitry Andric : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 31700b57cec5SDimitry Andric HasUndefinedConstructors(false) {} 31710b57cec5SDimitry Andric 31720b57cec5SDimitry Andric /// Checks whether pointee of a delete-expression is initialized with 31730b57cec5SDimitry Andric /// matching form of new-expression. 31740b57cec5SDimitry Andric /// 31750b57cec5SDimitry Andric /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 31760b57cec5SDimitry Andric /// point where delete-expression is encountered, then a warning will be 31770b57cec5SDimitry Andric /// issued immediately. If return value is \c AnalyzeLater at the point where 31780b57cec5SDimitry Andric /// delete-expression is seen, then member will be analyzed at the end of 31790b57cec5SDimitry Andric /// translation unit. \c AnalyzeLater is returned iff at least one constructor 31800b57cec5SDimitry Andric /// couldn't be analyzed. If at least one constructor initializes the member 31810b57cec5SDimitry Andric /// with matching type of new, the return value is \c NoMismatch. 31820b57cec5SDimitry Andric MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 31830b57cec5SDimitry Andric /// Analyzes a class member. 31840b57cec5SDimitry Andric /// \param Field Class member to analyze. 31850b57cec5SDimitry Andric /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 31860b57cec5SDimitry Andric /// for deleting the \p Field. 31870b57cec5SDimitry Andric MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 31880b57cec5SDimitry Andric FieldDecl *Field; 31890b57cec5SDimitry Andric /// List of mismatching new-expressions used for initialization of the pointee 31900b57cec5SDimitry Andric llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 31910b57cec5SDimitry Andric /// Indicates whether delete-expression was in array form. 31920b57cec5SDimitry Andric bool IsArrayForm; 31930b57cec5SDimitry Andric 31940b57cec5SDimitry Andric private: 31950b57cec5SDimitry Andric const bool EndOfTU; 31960b57cec5SDimitry Andric /// Indicates that there is at least one constructor without body. 31970b57cec5SDimitry Andric bool HasUndefinedConstructors; 31980b57cec5SDimitry Andric /// Returns \c CXXNewExpr from given initialization expression. 31990b57cec5SDimitry Andric /// \param E Expression used for initializing pointee in delete-expression. 32000b57cec5SDimitry Andric /// E can be a single-element \c InitListExpr consisting of new-expression. 32010b57cec5SDimitry Andric const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 32020b57cec5SDimitry Andric /// Returns whether member is initialized with mismatching form of 32030b57cec5SDimitry Andric /// \c new either by the member initializer or in-class initialization. 32040b57cec5SDimitry Andric /// 32050b57cec5SDimitry Andric /// If bodies of all constructors are not visible at the end of translation 32060b57cec5SDimitry Andric /// unit or at least one constructor initializes member with the matching 32070b57cec5SDimitry Andric /// form of \c new, mismatch cannot be proven, and this function will return 32080b57cec5SDimitry Andric /// \c NoMismatch. 32090b57cec5SDimitry Andric MismatchResult analyzeMemberExpr(const MemberExpr *ME); 32100b57cec5SDimitry Andric /// Returns whether variable is initialized with mismatching form of 32110b57cec5SDimitry Andric /// \c new. 32120b57cec5SDimitry Andric /// 32130b57cec5SDimitry Andric /// If variable is initialized with matching form of \c new or variable is not 32140b57cec5SDimitry Andric /// initialized with a \c new expression, this function will return true. 32150b57cec5SDimitry Andric /// If variable is initialized with mismatching form of \c new, returns false. 32160b57cec5SDimitry Andric /// \param D Variable to analyze. 32170b57cec5SDimitry Andric bool hasMatchingVarInit(const DeclRefExpr *D); 32180b57cec5SDimitry Andric /// Checks whether the constructor initializes pointee with mismatching 32190b57cec5SDimitry Andric /// form of \c new. 32200b57cec5SDimitry Andric /// 32210b57cec5SDimitry Andric /// Returns true, if member is initialized with matching form of \c new in 32220b57cec5SDimitry Andric /// member initializer list. Returns false, if member is initialized with the 32230b57cec5SDimitry Andric /// matching form of \c new in this constructor's initializer or given 32240b57cec5SDimitry Andric /// constructor isn't defined at the point where delete-expression is seen, or 32250b57cec5SDimitry Andric /// member isn't initialized by the constructor. 32260b57cec5SDimitry Andric bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 32270b57cec5SDimitry Andric /// Checks whether member is initialized with matching form of 32280b57cec5SDimitry Andric /// \c new in member initializer list. 32290b57cec5SDimitry Andric bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 32300b57cec5SDimitry Andric /// Checks whether member is initialized with mismatching form of \c new by 32310b57cec5SDimitry Andric /// in-class initializer. 32320b57cec5SDimitry Andric MismatchResult analyzeInClassInitializer(); 32330b57cec5SDimitry Andric }; 32340b57cec5SDimitry Andric } 32350b57cec5SDimitry Andric 32360b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 32370b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 32380b57cec5SDimitry Andric NewExprs.clear(); 32390b57cec5SDimitry Andric assert(DE && "Expected delete-expression"); 32400b57cec5SDimitry Andric IsArrayForm = DE->isArrayForm(); 32410b57cec5SDimitry Andric const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 32420b57cec5SDimitry Andric if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 32430b57cec5SDimitry Andric return analyzeMemberExpr(ME); 32440b57cec5SDimitry Andric } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 32450b57cec5SDimitry Andric if (!hasMatchingVarInit(D)) 32460b57cec5SDimitry Andric return VarInitMismatches; 32470b57cec5SDimitry Andric } 32480b57cec5SDimitry Andric return NoMismatch; 32490b57cec5SDimitry Andric } 32500b57cec5SDimitry Andric 32510b57cec5SDimitry Andric const CXXNewExpr * 32520b57cec5SDimitry Andric MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 32530b57cec5SDimitry Andric assert(E != nullptr && "Expected a valid initializer expression"); 32540b57cec5SDimitry Andric E = E->IgnoreParenImpCasts(); 32550b57cec5SDimitry Andric if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 32560b57cec5SDimitry Andric if (ILE->getNumInits() == 1) 32570b57cec5SDimitry Andric E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 32580b57cec5SDimitry Andric } 32590b57cec5SDimitry Andric 32600b57cec5SDimitry Andric return dyn_cast_or_null<const CXXNewExpr>(E); 32610b57cec5SDimitry Andric } 32620b57cec5SDimitry Andric 32630b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 32640b57cec5SDimitry Andric const CXXCtorInitializer *CI) { 32650b57cec5SDimitry Andric const CXXNewExpr *NE = nullptr; 32660b57cec5SDimitry Andric if (Field == CI->getMember() && 32670b57cec5SDimitry Andric (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 32680b57cec5SDimitry Andric if (NE->isArray() == IsArrayForm) 32690b57cec5SDimitry Andric return true; 32700b57cec5SDimitry Andric else 32710b57cec5SDimitry Andric NewExprs.push_back(NE); 32720b57cec5SDimitry Andric } 32730b57cec5SDimitry Andric return false; 32740b57cec5SDimitry Andric } 32750b57cec5SDimitry Andric 32760b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 32770b57cec5SDimitry Andric const CXXConstructorDecl *CD) { 32780b57cec5SDimitry Andric if (CD->isImplicit()) 32790b57cec5SDimitry Andric return false; 32800b57cec5SDimitry Andric const FunctionDecl *Definition = CD; 32810b57cec5SDimitry Andric if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 32820b57cec5SDimitry Andric HasUndefinedConstructors = true; 32830b57cec5SDimitry Andric return EndOfTU; 32840b57cec5SDimitry Andric } 32850b57cec5SDimitry Andric for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 32860b57cec5SDimitry Andric if (hasMatchingNewInCtorInit(CI)) 32870b57cec5SDimitry Andric return true; 32880b57cec5SDimitry Andric } 32890b57cec5SDimitry Andric return false; 32900b57cec5SDimitry Andric } 32910b57cec5SDimitry Andric 32920b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 32930b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeInClassInitializer() { 32940b57cec5SDimitry Andric assert(Field != nullptr && "This should be called only for members"); 32950b57cec5SDimitry Andric const Expr *InitExpr = Field->getInClassInitializer(); 32960b57cec5SDimitry Andric if (!InitExpr) 32970b57cec5SDimitry Andric return EndOfTU ? NoMismatch : AnalyzeLater; 32980b57cec5SDimitry Andric if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 32990b57cec5SDimitry Andric if (NE->isArray() != IsArrayForm) { 33000b57cec5SDimitry Andric NewExprs.push_back(NE); 33010b57cec5SDimitry Andric return MemberInitMismatches; 33020b57cec5SDimitry Andric } 33030b57cec5SDimitry Andric } 33040b57cec5SDimitry Andric return NoMismatch; 33050b57cec5SDimitry Andric } 33060b57cec5SDimitry Andric 33070b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 33080b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 33090b57cec5SDimitry Andric bool DeleteWasArrayForm) { 33100b57cec5SDimitry Andric assert(Field != nullptr && "Analysis requires a valid class member."); 33110b57cec5SDimitry Andric this->Field = Field; 33120b57cec5SDimitry Andric IsArrayForm = DeleteWasArrayForm; 33130b57cec5SDimitry Andric const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 33140b57cec5SDimitry Andric for (const auto *CD : RD->ctors()) { 33150b57cec5SDimitry Andric if (hasMatchingNewInCtor(CD)) 33160b57cec5SDimitry Andric return NoMismatch; 33170b57cec5SDimitry Andric } 33180b57cec5SDimitry Andric if (HasUndefinedConstructors) 33190b57cec5SDimitry Andric return EndOfTU ? NoMismatch : AnalyzeLater; 33200b57cec5SDimitry Andric if (!NewExprs.empty()) 33210b57cec5SDimitry Andric return MemberInitMismatches; 33220b57cec5SDimitry Andric return Field->hasInClassInitializer() ? analyzeInClassInitializer() 33230b57cec5SDimitry Andric : NoMismatch; 33240b57cec5SDimitry Andric } 33250b57cec5SDimitry Andric 33260b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 33270b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 33280b57cec5SDimitry Andric assert(ME != nullptr && "Expected a member expression"); 33290b57cec5SDimitry Andric if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 33300b57cec5SDimitry Andric return analyzeField(F, IsArrayForm); 33310b57cec5SDimitry Andric return NoMismatch; 33320b57cec5SDimitry Andric } 33330b57cec5SDimitry Andric 33340b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 33350b57cec5SDimitry Andric const CXXNewExpr *NE = nullptr; 33360b57cec5SDimitry Andric if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 33370b57cec5SDimitry Andric if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 33380b57cec5SDimitry Andric NE->isArray() != IsArrayForm) { 33390b57cec5SDimitry Andric NewExprs.push_back(NE); 33400b57cec5SDimitry Andric } 33410b57cec5SDimitry Andric } 33420b57cec5SDimitry Andric return NewExprs.empty(); 33430b57cec5SDimitry Andric } 33440b57cec5SDimitry Andric 33450b57cec5SDimitry Andric static void 33460b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 33470b57cec5SDimitry Andric const MismatchingNewDeleteDetector &Detector) { 33480b57cec5SDimitry Andric SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 33490b57cec5SDimitry Andric FixItHint H; 33500b57cec5SDimitry Andric if (!Detector.IsArrayForm) 33510b57cec5SDimitry Andric H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 33520b57cec5SDimitry Andric else { 33530b57cec5SDimitry Andric SourceLocation RSquare = Lexer::findLocationAfterToken( 33540b57cec5SDimitry Andric DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 33550b57cec5SDimitry Andric SemaRef.getLangOpts(), true); 33560b57cec5SDimitry Andric if (RSquare.isValid()) 33570b57cec5SDimitry Andric H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 33580b57cec5SDimitry Andric } 33590b57cec5SDimitry Andric SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 33600b57cec5SDimitry Andric << Detector.IsArrayForm << H; 33610b57cec5SDimitry Andric 33620b57cec5SDimitry Andric for (const auto *NE : Detector.NewExprs) 33630b57cec5SDimitry Andric SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 33640b57cec5SDimitry Andric << Detector.IsArrayForm; 33650b57cec5SDimitry Andric } 33660b57cec5SDimitry Andric 33670b57cec5SDimitry Andric void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 33680b57cec5SDimitry Andric if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 33690b57cec5SDimitry Andric return; 33700b57cec5SDimitry Andric MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 33710b57cec5SDimitry Andric switch (Detector.analyzeDeleteExpr(DE)) { 33720b57cec5SDimitry Andric case MismatchingNewDeleteDetector::VarInitMismatches: 33730b57cec5SDimitry Andric case MismatchingNewDeleteDetector::MemberInitMismatches: { 33740b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); 33750b57cec5SDimitry Andric break; 33760b57cec5SDimitry Andric } 33770b57cec5SDimitry Andric case MismatchingNewDeleteDetector::AnalyzeLater: { 33780b57cec5SDimitry Andric DeleteExprs[Detector.Field].push_back( 33790b57cec5SDimitry Andric std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); 33800b57cec5SDimitry Andric break; 33810b57cec5SDimitry Andric } 33820b57cec5SDimitry Andric case MismatchingNewDeleteDetector::NoMismatch: 33830b57cec5SDimitry Andric break; 33840b57cec5SDimitry Andric } 33850b57cec5SDimitry Andric } 33860b57cec5SDimitry Andric 33870b57cec5SDimitry Andric void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 33880b57cec5SDimitry Andric bool DeleteWasArrayForm) { 33890b57cec5SDimitry Andric MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 33900b57cec5SDimitry Andric switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 33910b57cec5SDimitry Andric case MismatchingNewDeleteDetector::VarInitMismatches: 33920b57cec5SDimitry Andric llvm_unreachable("This analysis should have been done for class members."); 33930b57cec5SDimitry Andric case MismatchingNewDeleteDetector::AnalyzeLater: 33940b57cec5SDimitry Andric llvm_unreachable("Analysis cannot be postponed any point beyond end of " 33950b57cec5SDimitry Andric "translation unit."); 33960b57cec5SDimitry Andric case MismatchingNewDeleteDetector::MemberInitMismatches: 33970b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 33980b57cec5SDimitry Andric break; 33990b57cec5SDimitry Andric case MismatchingNewDeleteDetector::NoMismatch: 34000b57cec5SDimitry Andric break; 34010b57cec5SDimitry Andric } 34020b57cec5SDimitry Andric } 34030b57cec5SDimitry Andric 34040b57cec5SDimitry Andric /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 34050b57cec5SDimitry Andric /// @code ::delete ptr; @endcode 34060b57cec5SDimitry Andric /// or 34070b57cec5SDimitry Andric /// @code delete [] ptr; @endcode 34080b57cec5SDimitry Andric ExprResult 34090b57cec5SDimitry Andric Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 34100b57cec5SDimitry Andric bool ArrayForm, Expr *ExE) { 34110b57cec5SDimitry Andric // C++ [expr.delete]p1: 34120b57cec5SDimitry Andric // The operand shall have a pointer type, or a class type having a single 34130b57cec5SDimitry Andric // non-explicit conversion function to a pointer type. The result has type 34140b57cec5SDimitry Andric // void. 34150b57cec5SDimitry Andric // 34160b57cec5SDimitry Andric // DR599 amends "pointer type" to "pointer to object type" in both cases. 34170b57cec5SDimitry Andric 34180b57cec5SDimitry Andric ExprResult Ex = ExE; 34190b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 34200b57cec5SDimitry Andric bool ArrayFormAsWritten = ArrayForm; 34210b57cec5SDimitry Andric bool UsualArrayDeleteWantsSize = false; 34220b57cec5SDimitry Andric 34230b57cec5SDimitry Andric if (!Ex.get()->isTypeDependent()) { 34240b57cec5SDimitry Andric // Perform lvalue-to-rvalue cast, if needed. 34250b57cec5SDimitry Andric Ex = DefaultLvalueConversion(Ex.get()); 34260b57cec5SDimitry Andric if (Ex.isInvalid()) 34270b57cec5SDimitry Andric return ExprError(); 34280b57cec5SDimitry Andric 34290b57cec5SDimitry Andric QualType Type = Ex.get()->getType(); 34300b57cec5SDimitry Andric 34310b57cec5SDimitry Andric class DeleteConverter : public ContextualImplicitConverter { 34320b57cec5SDimitry Andric public: 34330b57cec5SDimitry Andric DeleteConverter() : ContextualImplicitConverter(false, true) {} 34340b57cec5SDimitry Andric 34350b57cec5SDimitry Andric bool match(QualType ConvType) override { 34360b57cec5SDimitry Andric // FIXME: If we have an operator T* and an operator void*, we must pick 34370b57cec5SDimitry Andric // the operator T*. 34380b57cec5SDimitry Andric if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 34390b57cec5SDimitry Andric if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 34400b57cec5SDimitry Andric return true; 34410b57cec5SDimitry Andric return false; 34420b57cec5SDimitry Andric } 34430b57cec5SDimitry Andric 34440b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 34450b57cec5SDimitry Andric QualType T) override { 34460b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_operand) << T; 34470b57cec5SDimitry Andric } 34480b57cec5SDimitry Andric 34490b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 34500b57cec5SDimitry Andric QualType T) override { 34510b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 34520b57cec5SDimitry Andric } 34530b57cec5SDimitry Andric 34540b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 34550b57cec5SDimitry Andric QualType T, 34560b57cec5SDimitry Andric QualType ConvTy) override { 34570b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 34580b57cec5SDimitry Andric } 34590b57cec5SDimitry Andric 34600b57cec5SDimitry Andric SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 34610b57cec5SDimitry Andric QualType ConvTy) override { 34620b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 34630b57cec5SDimitry Andric << ConvTy; 34640b57cec5SDimitry Andric } 34650b57cec5SDimitry Andric 34660b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 34670b57cec5SDimitry Andric QualType T) override { 34680b57cec5SDimitry Andric return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 34690b57cec5SDimitry Andric } 34700b57cec5SDimitry Andric 34710b57cec5SDimitry Andric SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 34720b57cec5SDimitry Andric QualType ConvTy) override { 34730b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 34740b57cec5SDimitry Andric << ConvTy; 34750b57cec5SDimitry Andric } 34760b57cec5SDimitry Andric 34770b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 34780b57cec5SDimitry Andric QualType T, 34790b57cec5SDimitry Andric QualType ConvTy) override { 34800b57cec5SDimitry Andric llvm_unreachable("conversion functions are permitted"); 34810b57cec5SDimitry Andric } 34820b57cec5SDimitry Andric } Converter; 34830b57cec5SDimitry Andric 34840b57cec5SDimitry Andric Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 34850b57cec5SDimitry Andric if (Ex.isInvalid()) 34860b57cec5SDimitry Andric return ExprError(); 34870b57cec5SDimitry Andric Type = Ex.get()->getType(); 34880b57cec5SDimitry Andric if (!Converter.match(Type)) 34890b57cec5SDimitry Andric // FIXME: PerformContextualImplicitConversion should return ExprError 34900b57cec5SDimitry Andric // itself in this case. 34910b57cec5SDimitry Andric return ExprError(); 34920b57cec5SDimitry Andric 3493a7dea167SDimitry Andric QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); 34940b57cec5SDimitry Andric QualType PointeeElem = Context.getBaseElementType(Pointee); 34950b57cec5SDimitry Andric 34960b57cec5SDimitry Andric if (Pointee.getAddressSpace() != LangAS::Default && 34970b57cec5SDimitry Andric !getLangOpts().OpenCLCPlusPlus) 34980b57cec5SDimitry Andric return Diag(Ex.get()->getBeginLoc(), 34990b57cec5SDimitry Andric diag::err_address_space_qualified_delete) 35000b57cec5SDimitry Andric << Pointee.getUnqualifiedType() 35010b57cec5SDimitry Andric << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); 35020b57cec5SDimitry Andric 35030b57cec5SDimitry Andric CXXRecordDecl *PointeeRD = nullptr; 35040b57cec5SDimitry Andric if (Pointee->isVoidType() && !isSFINAEContext()) { 35050b57cec5SDimitry Andric // The C++ standard bans deleting a pointer to a non-object type, which 35060b57cec5SDimitry Andric // effectively bans deletion of "void*". However, most compilers support 35070b57cec5SDimitry Andric // this, so we treat it as a warning unless we're in a SFINAE context. 35080b57cec5SDimitry Andric Diag(StartLoc, diag::ext_delete_void_ptr_operand) 35090b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange(); 35105ffd83dbSDimitry Andric } else if (Pointee->isFunctionType() || Pointee->isVoidType() || 35115ffd83dbSDimitry Andric Pointee->isSizelessType()) { 35120b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_delete_operand) 35130b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange()); 35140b57cec5SDimitry Andric } else if (!Pointee->isDependentType()) { 35150b57cec5SDimitry Andric // FIXME: This can result in errors if the definition was imported from a 35160b57cec5SDimitry Andric // module but is hidden. 35170b57cec5SDimitry Andric if (!RequireCompleteType(StartLoc, Pointee, 35180b57cec5SDimitry Andric diag::warn_delete_incomplete, Ex.get())) { 35190b57cec5SDimitry Andric if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 35200b57cec5SDimitry Andric PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 35210b57cec5SDimitry Andric } 35220b57cec5SDimitry Andric } 35230b57cec5SDimitry Andric 35240b57cec5SDimitry Andric if (Pointee->isArrayType() && !ArrayForm) { 35250b57cec5SDimitry Andric Diag(StartLoc, diag::warn_delete_array_type) 35260b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange() 35270b57cec5SDimitry Andric << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 35280b57cec5SDimitry Andric ArrayForm = true; 35290b57cec5SDimitry Andric } 35300b57cec5SDimitry Andric 35310b57cec5SDimitry Andric DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 35320b57cec5SDimitry Andric ArrayForm ? OO_Array_Delete : OO_Delete); 35330b57cec5SDimitry Andric 35340b57cec5SDimitry Andric if (PointeeRD) { 35350b57cec5SDimitry Andric if (!UseGlobal && 35360b57cec5SDimitry Andric FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 35370b57cec5SDimitry Andric OperatorDelete)) 35380b57cec5SDimitry Andric return ExprError(); 35390b57cec5SDimitry Andric 35400b57cec5SDimitry Andric // If we're allocating an array of records, check whether the 35410b57cec5SDimitry Andric // usual operator delete[] has a size_t parameter. 35420b57cec5SDimitry Andric if (ArrayForm) { 35430b57cec5SDimitry Andric // If the user specifically asked to use the global allocator, 35440b57cec5SDimitry Andric // we'll need to do the lookup into the class. 35450b57cec5SDimitry Andric if (UseGlobal) 35460b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 35470b57cec5SDimitry Andric doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 35480b57cec5SDimitry Andric 35490b57cec5SDimitry Andric // Otherwise, the usual operator delete[] should be the 35500b57cec5SDimitry Andric // function we just found. 35510b57cec5SDimitry Andric else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 35520b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 35530b57cec5SDimitry Andric UsualDeallocFnInfo(*this, 35540b57cec5SDimitry Andric DeclAccessPair::make(OperatorDelete, AS_public)) 35550b57cec5SDimitry Andric .HasSizeT; 35560b57cec5SDimitry Andric } 35570b57cec5SDimitry Andric 35580b57cec5SDimitry Andric if (!PointeeRD->hasIrrelevantDestructor()) 35590b57cec5SDimitry Andric if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 35600b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, 35610b57cec5SDimitry Andric const_cast<CXXDestructorDecl*>(Dtor)); 35620b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Dtor, StartLoc)) 35630b57cec5SDimitry Andric return ExprError(); 35640b57cec5SDimitry Andric } 35650b57cec5SDimitry Andric 35660b57cec5SDimitry Andric CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 35670b57cec5SDimitry Andric /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 35680b57cec5SDimitry Andric /*WarnOnNonAbstractTypes=*/!ArrayForm, 35690b57cec5SDimitry Andric SourceLocation()); 35700b57cec5SDimitry Andric } 35710b57cec5SDimitry Andric 35720b57cec5SDimitry Andric if (!OperatorDelete) { 35730b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) { 35740b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; 35750b57cec5SDimitry Andric return ExprError(); 35760b57cec5SDimitry Andric } 35770b57cec5SDimitry Andric 35780b57cec5SDimitry Andric bool IsComplete = isCompleteType(StartLoc, Pointee); 35790b57cec5SDimitry Andric bool CanProvideSize = 35800b57cec5SDimitry Andric IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 35810b57cec5SDimitry Andric Pointee.isDestructedType()); 35820b57cec5SDimitry Andric bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 35830b57cec5SDimitry Andric 35840b57cec5SDimitry Andric // Look for a global declaration. 35850b57cec5SDimitry Andric OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 35860b57cec5SDimitry Andric Overaligned, DeleteName); 35870b57cec5SDimitry Andric } 35880b57cec5SDimitry Andric 35890b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorDelete); 35900b57cec5SDimitry Andric 35910b57cec5SDimitry Andric // Check access and ambiguity of destructor if we're going to call it. 35920b57cec5SDimitry Andric // Note that this is required even for a virtual delete. 35930b57cec5SDimitry Andric bool IsVirtualDelete = false; 35940b57cec5SDimitry Andric if (PointeeRD) { 35950b57cec5SDimitry Andric if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 35960b57cec5SDimitry Andric CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 35970b57cec5SDimitry Andric PDiag(diag::err_access_dtor) << PointeeElem); 35980b57cec5SDimitry Andric IsVirtualDelete = Dtor->isVirtual(); 35990b57cec5SDimitry Andric } 36000b57cec5SDimitry Andric } 36010b57cec5SDimitry Andric 36020b57cec5SDimitry Andric DiagnoseUseOfDecl(OperatorDelete, StartLoc); 36030b57cec5SDimitry Andric 36040b57cec5SDimitry Andric // Convert the operand to the type of the first parameter of operator 36050b57cec5SDimitry Andric // delete. This is only necessary if we selected a destroying operator 36060b57cec5SDimitry Andric // delete that we are going to call (non-virtually); converting to void* 36070b57cec5SDimitry Andric // is trivial and left to AST consumers to handle. 36080b57cec5SDimitry Andric QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 36090b57cec5SDimitry Andric if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { 36100b57cec5SDimitry Andric Qualifiers Qs = Pointee.getQualifiers(); 36110b57cec5SDimitry Andric if (Qs.hasCVRQualifiers()) { 36120b57cec5SDimitry Andric // Qualifiers are irrelevant to this conversion; we're only looking 36130b57cec5SDimitry Andric // for access and ambiguity. 36140b57cec5SDimitry Andric Qs.removeCVRQualifiers(); 36150b57cec5SDimitry Andric QualType Unqual = Context.getPointerType( 36160b57cec5SDimitry Andric Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); 36170b57cec5SDimitry Andric Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); 36180b57cec5SDimitry Andric } 36190b57cec5SDimitry Andric Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); 36200b57cec5SDimitry Andric if (Ex.isInvalid()) 36210b57cec5SDimitry Andric return ExprError(); 36220b57cec5SDimitry Andric } 36230b57cec5SDimitry Andric } 36240b57cec5SDimitry Andric 36250b57cec5SDimitry Andric CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 36260b57cec5SDimitry Andric Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 36270b57cec5SDimitry Andric UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 36280b57cec5SDimitry Andric AnalyzeDeleteExprMismatch(Result); 36290b57cec5SDimitry Andric return Result; 36300b57cec5SDimitry Andric } 36310b57cec5SDimitry Andric 36320b57cec5SDimitry Andric static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, 36330b57cec5SDimitry Andric bool IsDelete, 36340b57cec5SDimitry Andric FunctionDecl *&Operator) { 36350b57cec5SDimitry Andric 36360b57cec5SDimitry Andric DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( 36370b57cec5SDimitry Andric IsDelete ? OO_Delete : OO_New); 36380b57cec5SDimitry Andric 36390b57cec5SDimitry Andric LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); 36400b57cec5SDimitry Andric S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 36410b57cec5SDimitry Andric assert(!R.empty() && "implicitly declared allocation functions not found"); 36420b57cec5SDimitry Andric assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 36430b57cec5SDimitry Andric 36440b57cec5SDimitry Andric // We do our own custom access checks below. 36450b57cec5SDimitry Andric R.suppressDiagnostics(); 36460b57cec5SDimitry Andric 36470b57cec5SDimitry Andric SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end()); 36480b57cec5SDimitry Andric OverloadCandidateSet Candidates(R.getNameLoc(), 36490b57cec5SDimitry Andric OverloadCandidateSet::CSK_Normal); 36500b57cec5SDimitry Andric for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); 36510b57cec5SDimitry Andric FnOvl != FnOvlEnd; ++FnOvl) { 36520b57cec5SDimitry Andric // Even member operator new/delete are implicitly treated as 36530b57cec5SDimitry Andric // static, so don't use AddMemberCandidate. 36540b57cec5SDimitry Andric NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); 36550b57cec5SDimitry Andric 36560b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 36570b57cec5SDimitry Andric S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), 36580b57cec5SDimitry Andric /*ExplicitTemplateArgs=*/nullptr, Args, 36590b57cec5SDimitry Andric Candidates, 36600b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 36610b57cec5SDimitry Andric continue; 36620b57cec5SDimitry Andric } 36630b57cec5SDimitry Andric 36640b57cec5SDimitry Andric FunctionDecl *Fn = cast<FunctionDecl>(D); 36650b57cec5SDimitry Andric S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, 36660b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 36670b57cec5SDimitry Andric } 36680b57cec5SDimitry Andric 36690b57cec5SDimitry Andric SourceRange Range = TheCall->getSourceRange(); 36700b57cec5SDimitry Andric 36710b57cec5SDimitry Andric // Do the resolution. 36720b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 36730b57cec5SDimitry Andric switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 36740b57cec5SDimitry Andric case OR_Success: { 36750b57cec5SDimitry Andric // Got one! 36760b57cec5SDimitry Andric FunctionDecl *FnDecl = Best->Function; 36770b57cec5SDimitry Andric assert(R.getNamingClass() == nullptr && 36780b57cec5SDimitry Andric "class members should not be considered"); 36790b57cec5SDimitry Andric 36800b57cec5SDimitry Andric if (!FnDecl->isReplaceableGlobalAllocationFunction()) { 36810b57cec5SDimitry Andric S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) 36820b57cec5SDimitry Andric << (IsDelete ? 1 : 0) << Range; 36830b57cec5SDimitry Andric S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) 36840b57cec5SDimitry Andric << R.getLookupName() << FnDecl->getSourceRange(); 36850b57cec5SDimitry Andric return true; 36860b57cec5SDimitry Andric } 36870b57cec5SDimitry Andric 36880b57cec5SDimitry Andric Operator = FnDecl; 36890b57cec5SDimitry Andric return false; 36900b57cec5SDimitry Andric } 36910b57cec5SDimitry Andric 36920b57cec5SDimitry Andric case OR_No_Viable_Function: 36930b57cec5SDimitry Andric Candidates.NoteCandidates( 36940b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 36950b57cec5SDimitry Andric S.PDiag(diag::err_ovl_no_viable_function_in_call) 36960b57cec5SDimitry Andric << R.getLookupName() << Range), 36970b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 36980b57cec5SDimitry Andric return true; 36990b57cec5SDimitry Andric 37000b57cec5SDimitry Andric case OR_Ambiguous: 37010b57cec5SDimitry Andric Candidates.NoteCandidates( 37020b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 37030b57cec5SDimitry Andric S.PDiag(diag::err_ovl_ambiguous_call) 37040b57cec5SDimitry Andric << R.getLookupName() << Range), 3705480093f4SDimitry Andric S, OCD_AmbiguousCandidates, Args); 37060b57cec5SDimitry Andric return true; 37070b57cec5SDimitry Andric 37080b57cec5SDimitry Andric case OR_Deleted: { 37090b57cec5SDimitry Andric Candidates.NoteCandidates( 37100b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) 37110b57cec5SDimitry Andric << R.getLookupName() << Range), 37120b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 37130b57cec5SDimitry Andric return true; 37140b57cec5SDimitry Andric } 37150b57cec5SDimitry Andric } 37160b57cec5SDimitry Andric llvm_unreachable("Unreachable, bad result from BestViableFunction"); 37170b57cec5SDimitry Andric } 37180b57cec5SDimitry Andric 37190b57cec5SDimitry Andric ExprResult 37200b57cec5SDimitry Andric Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 37210b57cec5SDimitry Andric bool IsDelete) { 37220b57cec5SDimitry Andric CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 37230b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) { 37240b57cec5SDimitry Andric Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 37250b57cec5SDimitry Andric << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") 37260b57cec5SDimitry Andric << "C++"; 37270b57cec5SDimitry Andric return ExprError(); 37280b57cec5SDimitry Andric } 37290b57cec5SDimitry Andric // CodeGen assumes it can find the global new and delete to call, 37300b57cec5SDimitry Andric // so ensure that they are declared. 37310b57cec5SDimitry Andric DeclareGlobalNewDelete(); 37320b57cec5SDimitry Andric 37330b57cec5SDimitry Andric FunctionDecl *OperatorNewOrDelete = nullptr; 37340b57cec5SDimitry Andric if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, 37350b57cec5SDimitry Andric OperatorNewOrDelete)) 37360b57cec5SDimitry Andric return ExprError(); 37370b57cec5SDimitry Andric assert(OperatorNewOrDelete && "should be found"); 37380b57cec5SDimitry Andric 37390b57cec5SDimitry Andric DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); 37400b57cec5SDimitry Andric MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); 37410b57cec5SDimitry Andric 37420b57cec5SDimitry Andric TheCall->setType(OperatorNewOrDelete->getReturnType()); 37430b57cec5SDimitry Andric for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 37440b57cec5SDimitry Andric QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); 37450b57cec5SDimitry Andric InitializedEntity Entity = 37460b57cec5SDimitry Andric InitializedEntity::InitializeParameter(Context, ParamTy, false); 37470b57cec5SDimitry Andric ExprResult Arg = PerformCopyInitialization( 37480b57cec5SDimitry Andric Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); 37490b57cec5SDimitry Andric if (Arg.isInvalid()) 37500b57cec5SDimitry Andric return ExprError(); 37510b57cec5SDimitry Andric TheCall->setArg(i, Arg.get()); 37520b57cec5SDimitry Andric } 37530b57cec5SDimitry Andric auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); 37540b57cec5SDimitry Andric assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && 37550b57cec5SDimitry Andric "Callee expected to be implicit cast to a builtin function pointer"); 37560b57cec5SDimitry Andric Callee->setType(OperatorNewOrDelete->getType()); 37570b57cec5SDimitry Andric 37580b57cec5SDimitry Andric return TheCallResult; 37590b57cec5SDimitry Andric } 37600b57cec5SDimitry Andric 37610b57cec5SDimitry Andric void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 37620b57cec5SDimitry Andric bool IsDelete, bool CallCanBeVirtual, 37630b57cec5SDimitry Andric bool WarnOnNonAbstractTypes, 37640b57cec5SDimitry Andric SourceLocation DtorLoc) { 37650b57cec5SDimitry Andric if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) 37660b57cec5SDimitry Andric return; 37670b57cec5SDimitry Andric 37680b57cec5SDimitry Andric // C++ [expr.delete]p3: 37690b57cec5SDimitry Andric // In the first alternative (delete object), if the static type of the 37700b57cec5SDimitry Andric // object to be deleted is different from its dynamic type, the static 37710b57cec5SDimitry Andric // type shall be a base class of the dynamic type of the object to be 37720b57cec5SDimitry Andric // deleted and the static type shall have a virtual destructor or the 37730b57cec5SDimitry Andric // behavior is undefined. 37740b57cec5SDimitry Andric // 37750b57cec5SDimitry Andric const CXXRecordDecl *PointeeRD = dtor->getParent(); 37760b57cec5SDimitry Andric // Note: a final class cannot be derived from, no issue there 37770b57cec5SDimitry Andric if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 37780b57cec5SDimitry Andric return; 37790b57cec5SDimitry Andric 37800b57cec5SDimitry Andric // If the superclass is in a system header, there's nothing that can be done. 37810b57cec5SDimitry Andric // The `delete` (where we emit the warning) can be in a system header, 37820b57cec5SDimitry Andric // what matters for this warning is where the deleted type is defined. 37830b57cec5SDimitry Andric if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) 37840b57cec5SDimitry Andric return; 37850b57cec5SDimitry Andric 37860b57cec5SDimitry Andric QualType ClassType = dtor->getThisType()->getPointeeType(); 37870b57cec5SDimitry Andric if (PointeeRD->isAbstract()) { 37880b57cec5SDimitry Andric // If the class is abstract, we warn by default, because we're 37890b57cec5SDimitry Andric // sure the code has undefined behavior. 37900b57cec5SDimitry Andric Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 37910b57cec5SDimitry Andric << ClassType; 37920b57cec5SDimitry Andric } else if (WarnOnNonAbstractTypes) { 37930b57cec5SDimitry Andric // Otherwise, if this is not an array delete, it's a bit suspect, 37940b57cec5SDimitry Andric // but not necessarily wrong. 37950b57cec5SDimitry Andric Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 37960b57cec5SDimitry Andric << ClassType; 37970b57cec5SDimitry Andric } 37980b57cec5SDimitry Andric if (!IsDelete) { 37990b57cec5SDimitry Andric std::string TypeStr; 38000b57cec5SDimitry Andric ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 38010b57cec5SDimitry Andric Diag(DtorLoc, diag::note_delete_non_virtual) 38020b57cec5SDimitry Andric << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 38030b57cec5SDimitry Andric } 38040b57cec5SDimitry Andric } 38050b57cec5SDimitry Andric 38060b57cec5SDimitry Andric Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 38070b57cec5SDimitry Andric SourceLocation StmtLoc, 38080b57cec5SDimitry Andric ConditionKind CK) { 38090b57cec5SDimitry Andric ExprResult E = 38100b57cec5SDimitry Andric CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 38110b57cec5SDimitry Andric if (E.isInvalid()) 38120b57cec5SDimitry Andric return ConditionError(); 38130b57cec5SDimitry Andric return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 38140b57cec5SDimitry Andric CK == ConditionKind::ConstexprIf); 38150b57cec5SDimitry Andric } 38160b57cec5SDimitry Andric 38170b57cec5SDimitry Andric /// Check the use of the given variable as a C++ condition in an if, 38180b57cec5SDimitry Andric /// while, do-while, or switch statement. 38190b57cec5SDimitry Andric ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 38200b57cec5SDimitry Andric SourceLocation StmtLoc, 38210b57cec5SDimitry Andric ConditionKind CK) { 38220b57cec5SDimitry Andric if (ConditionVar->isInvalidDecl()) 38230b57cec5SDimitry Andric return ExprError(); 38240b57cec5SDimitry Andric 38250b57cec5SDimitry Andric QualType T = ConditionVar->getType(); 38260b57cec5SDimitry Andric 38270b57cec5SDimitry Andric // C++ [stmt.select]p2: 38280b57cec5SDimitry Andric // The declarator shall not specify a function or an array. 38290b57cec5SDimitry Andric if (T->isFunctionType()) 38300b57cec5SDimitry Andric return ExprError(Diag(ConditionVar->getLocation(), 38310b57cec5SDimitry Andric diag::err_invalid_use_of_function_type) 38320b57cec5SDimitry Andric << ConditionVar->getSourceRange()); 38330b57cec5SDimitry Andric else if (T->isArrayType()) 38340b57cec5SDimitry Andric return ExprError(Diag(ConditionVar->getLocation(), 38350b57cec5SDimitry Andric diag::err_invalid_use_of_array_type) 38360b57cec5SDimitry Andric << ConditionVar->getSourceRange()); 38370b57cec5SDimitry Andric 38380b57cec5SDimitry Andric ExprResult Condition = BuildDeclRefExpr( 38390b57cec5SDimitry Andric ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, 38400b57cec5SDimitry Andric ConditionVar->getLocation()); 38410b57cec5SDimitry Andric 38420b57cec5SDimitry Andric switch (CK) { 38430b57cec5SDimitry Andric case ConditionKind::Boolean: 38440b57cec5SDimitry Andric return CheckBooleanCondition(StmtLoc, Condition.get()); 38450b57cec5SDimitry Andric 38460b57cec5SDimitry Andric case ConditionKind::ConstexprIf: 38470b57cec5SDimitry Andric return CheckBooleanCondition(StmtLoc, Condition.get(), true); 38480b57cec5SDimitry Andric 38490b57cec5SDimitry Andric case ConditionKind::Switch: 38500b57cec5SDimitry Andric return CheckSwitchCondition(StmtLoc, Condition.get()); 38510b57cec5SDimitry Andric } 38520b57cec5SDimitry Andric 38530b57cec5SDimitry Andric llvm_unreachable("unexpected condition kind"); 38540b57cec5SDimitry Andric } 38550b57cec5SDimitry Andric 38560b57cec5SDimitry Andric /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 38570b57cec5SDimitry Andric ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 38580b57cec5SDimitry Andric // C++ 6.4p4: 38590b57cec5SDimitry Andric // The value of a condition that is an initialized declaration in a statement 38600b57cec5SDimitry Andric // other than a switch statement is the value of the declared variable 38610b57cec5SDimitry Andric // implicitly converted to type bool. If that conversion is ill-formed, the 38620b57cec5SDimitry Andric // program is ill-formed. 38630b57cec5SDimitry Andric // The value of a condition that is an expression is the value of the 38640b57cec5SDimitry Andric // expression, implicitly converted to bool. 38650b57cec5SDimitry Andric // 38660b57cec5SDimitry Andric // FIXME: Return this value to the caller so they don't need to recompute it. 38670b57cec5SDimitry Andric llvm::APSInt Value(/*BitWidth*/1); 38680b57cec5SDimitry Andric return (IsConstexpr && !CondExpr->isValueDependent()) 38690b57cec5SDimitry Andric ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value, 38700b57cec5SDimitry Andric CCEK_ConstexprIf) 38710b57cec5SDimitry Andric : PerformContextuallyConvertToBool(CondExpr); 38720b57cec5SDimitry Andric } 38730b57cec5SDimitry Andric 38740b57cec5SDimitry Andric /// Helper function to determine whether this is the (deprecated) C++ 38750b57cec5SDimitry Andric /// conversion from a string literal to a pointer to non-const char or 38760b57cec5SDimitry Andric /// non-const wchar_t (for narrow and wide string literals, 38770b57cec5SDimitry Andric /// respectively). 38780b57cec5SDimitry Andric bool 38790b57cec5SDimitry Andric Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 38800b57cec5SDimitry Andric // Look inside the implicit cast, if it exists. 38810b57cec5SDimitry Andric if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 38820b57cec5SDimitry Andric From = Cast->getSubExpr(); 38830b57cec5SDimitry Andric 38840b57cec5SDimitry Andric // A string literal (2.13.4) that is not a wide string literal can 38850b57cec5SDimitry Andric // be converted to an rvalue of type "pointer to char"; a wide 38860b57cec5SDimitry Andric // string literal can be converted to an rvalue of type "pointer 38870b57cec5SDimitry Andric // to wchar_t" (C++ 4.2p2). 38880b57cec5SDimitry Andric if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 38890b57cec5SDimitry Andric if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 38900b57cec5SDimitry Andric if (const BuiltinType *ToPointeeType 38910b57cec5SDimitry Andric = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 38920b57cec5SDimitry Andric // This conversion is considered only when there is an 38930b57cec5SDimitry Andric // explicit appropriate pointer target type (C++ 4.2p2). 38940b57cec5SDimitry Andric if (!ToPtrType->getPointeeType().hasQualifiers()) { 38950b57cec5SDimitry Andric switch (StrLit->getKind()) { 38960b57cec5SDimitry Andric case StringLiteral::UTF8: 38970b57cec5SDimitry Andric case StringLiteral::UTF16: 38980b57cec5SDimitry Andric case StringLiteral::UTF32: 38990b57cec5SDimitry Andric // We don't allow UTF literals to be implicitly converted 39000b57cec5SDimitry Andric break; 39010b57cec5SDimitry Andric case StringLiteral::Ascii: 39020b57cec5SDimitry Andric return (ToPointeeType->getKind() == BuiltinType::Char_U || 39030b57cec5SDimitry Andric ToPointeeType->getKind() == BuiltinType::Char_S); 39040b57cec5SDimitry Andric case StringLiteral::Wide: 39050b57cec5SDimitry Andric return Context.typesAreCompatible(Context.getWideCharType(), 39060b57cec5SDimitry Andric QualType(ToPointeeType, 0)); 39070b57cec5SDimitry Andric } 39080b57cec5SDimitry Andric } 39090b57cec5SDimitry Andric } 39100b57cec5SDimitry Andric 39110b57cec5SDimitry Andric return false; 39120b57cec5SDimitry Andric } 39130b57cec5SDimitry Andric 39140b57cec5SDimitry Andric static ExprResult BuildCXXCastArgument(Sema &S, 39150b57cec5SDimitry Andric SourceLocation CastLoc, 39160b57cec5SDimitry Andric QualType Ty, 39170b57cec5SDimitry Andric CastKind Kind, 39180b57cec5SDimitry Andric CXXMethodDecl *Method, 39190b57cec5SDimitry Andric DeclAccessPair FoundDecl, 39200b57cec5SDimitry Andric bool HadMultipleCandidates, 39210b57cec5SDimitry Andric Expr *From) { 39220b57cec5SDimitry Andric switch (Kind) { 39230b57cec5SDimitry Andric default: llvm_unreachable("Unhandled cast kind!"); 39240b57cec5SDimitry Andric case CK_ConstructorConversion: { 39250b57cec5SDimitry Andric CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 39260b57cec5SDimitry Andric SmallVector<Expr*, 8> ConstructorArgs; 39270b57cec5SDimitry Andric 39280b57cec5SDimitry Andric if (S.RequireNonAbstractType(CastLoc, Ty, 39290b57cec5SDimitry Andric diag::err_allocation_of_abstract_type)) 39300b57cec5SDimitry Andric return ExprError(); 39310b57cec5SDimitry Andric 39320b57cec5SDimitry Andric if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs)) 39330b57cec5SDimitry Andric return ExprError(); 39340b57cec5SDimitry Andric 39350b57cec5SDimitry Andric S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 39360b57cec5SDimitry Andric InitializedEntity::InitializeTemporary(Ty)); 39370b57cec5SDimitry Andric if (S.DiagnoseUseOfDecl(Method, CastLoc)) 39380b57cec5SDimitry Andric return ExprError(); 39390b57cec5SDimitry Andric 39400b57cec5SDimitry Andric ExprResult Result = S.BuildCXXConstructExpr( 39410b57cec5SDimitry Andric CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 39420b57cec5SDimitry Andric ConstructorArgs, HadMultipleCandidates, 39430b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 39440b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 39450b57cec5SDimitry Andric if (Result.isInvalid()) 39460b57cec5SDimitry Andric return ExprError(); 39470b57cec5SDimitry Andric 39480b57cec5SDimitry Andric return S.MaybeBindToTemporary(Result.getAs<Expr>()); 39490b57cec5SDimitry Andric } 39500b57cec5SDimitry Andric 39510b57cec5SDimitry Andric case CK_UserDefinedConversion: { 39520b57cec5SDimitry Andric assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 39530b57cec5SDimitry Andric 39540b57cec5SDimitry Andric S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 39550b57cec5SDimitry Andric if (S.DiagnoseUseOfDecl(Method, CastLoc)) 39560b57cec5SDimitry Andric return ExprError(); 39570b57cec5SDimitry Andric 39580b57cec5SDimitry Andric // Create an implicit call expr that calls it. 39590b57cec5SDimitry Andric CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 39600b57cec5SDimitry Andric ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 39610b57cec5SDimitry Andric HadMultipleCandidates); 39620b57cec5SDimitry Andric if (Result.isInvalid()) 39630b57cec5SDimitry Andric return ExprError(); 39640b57cec5SDimitry Andric // Record usage of conversion in an implicit cast. 39650b57cec5SDimitry Andric Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 39660b57cec5SDimitry Andric CK_UserDefinedConversion, Result.get(), 3967e8d8bef9SDimitry Andric nullptr, Result.get()->getValueKind(), 3968e8d8bef9SDimitry Andric S.CurFPFeatureOverrides()); 39690b57cec5SDimitry Andric 39700b57cec5SDimitry Andric return S.MaybeBindToTemporary(Result.get()); 39710b57cec5SDimitry Andric } 39720b57cec5SDimitry Andric } 39730b57cec5SDimitry Andric } 39740b57cec5SDimitry Andric 39750b57cec5SDimitry Andric /// PerformImplicitConversion - Perform an implicit conversion of the 39760b57cec5SDimitry Andric /// expression From to the type ToType using the pre-computed implicit 39770b57cec5SDimitry Andric /// conversion sequence ICS. Returns the converted 39780b57cec5SDimitry Andric /// expression. Action is the kind of conversion we're performing, 39790b57cec5SDimitry Andric /// used in the error message. 39800b57cec5SDimitry Andric ExprResult 39810b57cec5SDimitry Andric Sema::PerformImplicitConversion(Expr *From, QualType ToType, 39820b57cec5SDimitry Andric const ImplicitConversionSequence &ICS, 39830b57cec5SDimitry Andric AssignmentAction Action, 39840b57cec5SDimitry Andric CheckedConversionKind CCK) { 39850b57cec5SDimitry Andric // C++ [over.match.oper]p7: [...] operands of class type are converted [...] 39860b57cec5SDimitry Andric if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) 39870b57cec5SDimitry Andric return From; 39880b57cec5SDimitry Andric 39890b57cec5SDimitry Andric switch (ICS.getKind()) { 39900b57cec5SDimitry Andric case ImplicitConversionSequence::StandardConversion: { 39910b57cec5SDimitry Andric ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 39920b57cec5SDimitry Andric Action, CCK); 39930b57cec5SDimitry Andric if (Res.isInvalid()) 39940b57cec5SDimitry Andric return ExprError(); 39950b57cec5SDimitry Andric From = Res.get(); 39960b57cec5SDimitry Andric break; 39970b57cec5SDimitry Andric } 39980b57cec5SDimitry Andric 39990b57cec5SDimitry Andric case ImplicitConversionSequence::UserDefinedConversion: { 40000b57cec5SDimitry Andric 40010b57cec5SDimitry Andric FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 40020b57cec5SDimitry Andric CastKind CastKind; 40030b57cec5SDimitry Andric QualType BeforeToType; 40040b57cec5SDimitry Andric assert(FD && "no conversion function for user-defined conversion seq"); 40050b57cec5SDimitry Andric if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 40060b57cec5SDimitry Andric CastKind = CK_UserDefinedConversion; 40070b57cec5SDimitry Andric 40080b57cec5SDimitry Andric // If the user-defined conversion is specified by a conversion function, 40090b57cec5SDimitry Andric // the initial standard conversion sequence converts the source type to 40100b57cec5SDimitry Andric // the implicit object parameter of the conversion function. 40110b57cec5SDimitry Andric BeforeToType = Context.getTagDeclType(Conv->getParent()); 40120b57cec5SDimitry Andric } else { 40130b57cec5SDimitry Andric const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 40140b57cec5SDimitry Andric CastKind = CK_ConstructorConversion; 40150b57cec5SDimitry Andric // Do no conversion if dealing with ... for the first conversion. 40160b57cec5SDimitry Andric if (!ICS.UserDefined.EllipsisConversion) { 40170b57cec5SDimitry Andric // If the user-defined conversion is specified by a constructor, the 40180b57cec5SDimitry Andric // initial standard conversion sequence converts the source type to 40190b57cec5SDimitry Andric // the type required by the argument of the constructor 40200b57cec5SDimitry Andric BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 40210b57cec5SDimitry Andric } 40220b57cec5SDimitry Andric } 40230b57cec5SDimitry Andric // Watch out for ellipsis conversion. 40240b57cec5SDimitry Andric if (!ICS.UserDefined.EllipsisConversion) { 40250b57cec5SDimitry Andric ExprResult Res = 40260b57cec5SDimitry Andric PerformImplicitConversion(From, BeforeToType, 40270b57cec5SDimitry Andric ICS.UserDefined.Before, AA_Converting, 40280b57cec5SDimitry Andric CCK); 40290b57cec5SDimitry Andric if (Res.isInvalid()) 40300b57cec5SDimitry Andric return ExprError(); 40310b57cec5SDimitry Andric From = Res.get(); 40320b57cec5SDimitry Andric } 40330b57cec5SDimitry Andric 40340b57cec5SDimitry Andric ExprResult CastArg = BuildCXXCastArgument( 40350b57cec5SDimitry Andric *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, 40360b57cec5SDimitry Andric cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, 40370b57cec5SDimitry Andric ICS.UserDefined.HadMultipleCandidates, From); 40380b57cec5SDimitry Andric 40390b57cec5SDimitry Andric if (CastArg.isInvalid()) 40400b57cec5SDimitry Andric return ExprError(); 40410b57cec5SDimitry Andric 40420b57cec5SDimitry Andric From = CastArg.get(); 40430b57cec5SDimitry Andric 40440b57cec5SDimitry Andric // C++ [over.match.oper]p7: 40450b57cec5SDimitry Andric // [...] the second standard conversion sequence of a user-defined 40460b57cec5SDimitry Andric // conversion sequence is not applied. 40470b57cec5SDimitry Andric if (CCK == CCK_ForBuiltinOverloadedOp) 40480b57cec5SDimitry Andric return From; 40490b57cec5SDimitry Andric 40500b57cec5SDimitry Andric return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 40510b57cec5SDimitry Andric AA_Converting, CCK); 40520b57cec5SDimitry Andric } 40530b57cec5SDimitry Andric 40540b57cec5SDimitry Andric case ImplicitConversionSequence::AmbiguousConversion: 40550b57cec5SDimitry Andric ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 40560b57cec5SDimitry Andric PDiag(diag::err_typecheck_ambiguous_condition) 40570b57cec5SDimitry Andric << From->getSourceRange()); 40580b57cec5SDimitry Andric return ExprError(); 40590b57cec5SDimitry Andric 40600b57cec5SDimitry Andric case ImplicitConversionSequence::EllipsisConversion: 40610b57cec5SDimitry Andric llvm_unreachable("Cannot perform an ellipsis conversion"); 40620b57cec5SDimitry Andric 40630b57cec5SDimitry Andric case ImplicitConversionSequence::BadConversion: 40645ffd83dbSDimitry Andric Sema::AssignConvertType ConvTy = 40655ffd83dbSDimitry Andric CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); 40665ffd83dbSDimitry Andric bool Diagnosed = DiagnoseAssignmentResult( 40675ffd83dbSDimitry Andric ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(), 40685ffd83dbSDimitry Andric ToType, From->getType(), From, Action); 40690b57cec5SDimitry Andric assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; 40700b57cec5SDimitry Andric return ExprError(); 40710b57cec5SDimitry Andric } 40720b57cec5SDimitry Andric 40730b57cec5SDimitry Andric // Everything went well. 40740b57cec5SDimitry Andric return From; 40750b57cec5SDimitry Andric } 40760b57cec5SDimitry Andric 40770b57cec5SDimitry Andric /// PerformImplicitConversion - Perform an implicit conversion of the 40780b57cec5SDimitry Andric /// expression From to the type ToType by following the standard 40790b57cec5SDimitry Andric /// conversion sequence SCS. Returns the converted 40800b57cec5SDimitry Andric /// expression. Flavor is the context in which we're performing this 40810b57cec5SDimitry Andric /// conversion, for use in error messages. 40820b57cec5SDimitry Andric ExprResult 40830b57cec5SDimitry Andric Sema::PerformImplicitConversion(Expr *From, QualType ToType, 40840b57cec5SDimitry Andric const StandardConversionSequence& SCS, 40850b57cec5SDimitry Andric AssignmentAction Action, 40860b57cec5SDimitry Andric CheckedConversionKind CCK) { 40870b57cec5SDimitry Andric bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 40880b57cec5SDimitry Andric 40890b57cec5SDimitry Andric // Overall FIXME: we are recomputing too many types here and doing far too 40900b57cec5SDimitry Andric // much extra work. What this means is that we need to keep track of more 40910b57cec5SDimitry Andric // information that is computed when we try the implicit conversion initially, 40920b57cec5SDimitry Andric // so that we don't need to recompute anything here. 40930b57cec5SDimitry Andric QualType FromType = From->getType(); 40940b57cec5SDimitry Andric 40950b57cec5SDimitry Andric if (SCS.CopyConstructor) { 40960b57cec5SDimitry Andric // FIXME: When can ToType be a reference type? 40970b57cec5SDimitry Andric assert(!ToType->isReferenceType()); 40980b57cec5SDimitry Andric if (SCS.Second == ICK_Derived_To_Base) { 40990b57cec5SDimitry Andric SmallVector<Expr*, 8> ConstructorArgs; 41000b57cec5SDimitry Andric if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 41010b57cec5SDimitry Andric From, /*FIXME:ConstructLoc*/SourceLocation(), 41020b57cec5SDimitry Andric ConstructorArgs)) 41030b57cec5SDimitry Andric return ExprError(); 41040b57cec5SDimitry Andric return BuildCXXConstructExpr( 41050b57cec5SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 41060b57cec5SDimitry Andric SCS.FoundCopyConstructor, SCS.CopyConstructor, 41070b57cec5SDimitry Andric ConstructorArgs, /*HadMultipleCandidates*/ false, 41080b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 41090b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 41100b57cec5SDimitry Andric } 41110b57cec5SDimitry Andric return BuildCXXConstructExpr( 41120b57cec5SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 41130b57cec5SDimitry Andric SCS.FoundCopyConstructor, SCS.CopyConstructor, 41140b57cec5SDimitry Andric From, /*HadMultipleCandidates*/ false, 41150b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 41160b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 41170b57cec5SDimitry Andric } 41180b57cec5SDimitry Andric 41190b57cec5SDimitry Andric // Resolve overloaded function references. 41200b57cec5SDimitry Andric if (Context.hasSameType(FromType, Context.OverloadTy)) { 41210b57cec5SDimitry Andric DeclAccessPair Found; 41220b57cec5SDimitry Andric FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 41230b57cec5SDimitry Andric true, Found); 41240b57cec5SDimitry Andric if (!Fn) 41250b57cec5SDimitry Andric return ExprError(); 41260b57cec5SDimitry Andric 41270b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) 41280b57cec5SDimitry Andric return ExprError(); 41290b57cec5SDimitry Andric 41300b57cec5SDimitry Andric From = FixOverloadedFunctionReference(From, Found, Fn); 41310b57cec5SDimitry Andric FromType = From->getType(); 41320b57cec5SDimitry Andric } 41330b57cec5SDimitry Andric 41340b57cec5SDimitry Andric // If we're converting to an atomic type, first convert to the corresponding 41350b57cec5SDimitry Andric // non-atomic type. 41360b57cec5SDimitry Andric QualType ToAtomicType; 41370b57cec5SDimitry Andric if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 41380b57cec5SDimitry Andric ToAtomicType = ToType; 41390b57cec5SDimitry Andric ToType = ToAtomic->getValueType(); 41400b57cec5SDimitry Andric } 41410b57cec5SDimitry Andric 41420b57cec5SDimitry Andric QualType InitialFromType = FromType; 41430b57cec5SDimitry Andric // Perform the first implicit conversion. 41440b57cec5SDimitry Andric switch (SCS.First) { 41450b57cec5SDimitry Andric case ICK_Identity: 41460b57cec5SDimitry Andric if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 41470b57cec5SDimitry Andric FromType = FromAtomic->getValueType().getUnqualifiedType(); 41480b57cec5SDimitry Andric From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 4149e8d8bef9SDimitry Andric From, /*BasePath=*/nullptr, VK_RValue, 4150e8d8bef9SDimitry Andric FPOptionsOverride()); 41510b57cec5SDimitry Andric } 41520b57cec5SDimitry Andric break; 41530b57cec5SDimitry Andric 41540b57cec5SDimitry Andric case ICK_Lvalue_To_Rvalue: { 41550b57cec5SDimitry Andric assert(From->getObjectKind() != OK_ObjCProperty); 41560b57cec5SDimitry Andric ExprResult FromRes = DefaultLvalueConversion(From); 41570b57cec5SDimitry Andric assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!"); 41580b57cec5SDimitry Andric From = FromRes.get(); 41590b57cec5SDimitry Andric FromType = From->getType(); 41600b57cec5SDimitry Andric break; 41610b57cec5SDimitry Andric } 41620b57cec5SDimitry Andric 41630b57cec5SDimitry Andric case ICK_Array_To_Pointer: 41640b57cec5SDimitry Andric FromType = Context.getArrayDecayedType(FromType); 41650b57cec5SDimitry Andric From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 41660b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 41670b57cec5SDimitry Andric break; 41680b57cec5SDimitry Andric 41690b57cec5SDimitry Andric case ICK_Function_To_Pointer: 41700b57cec5SDimitry Andric FromType = Context.getPointerType(FromType); 41710b57cec5SDimitry Andric From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 41720b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 41730b57cec5SDimitry Andric break; 41740b57cec5SDimitry Andric 41750b57cec5SDimitry Andric default: 41760b57cec5SDimitry Andric llvm_unreachable("Improper first standard conversion"); 41770b57cec5SDimitry Andric } 41780b57cec5SDimitry Andric 41790b57cec5SDimitry Andric // Perform the second implicit conversion 41800b57cec5SDimitry Andric switch (SCS.Second) { 41810b57cec5SDimitry Andric case ICK_Identity: 41820b57cec5SDimitry Andric // C++ [except.spec]p5: 41830b57cec5SDimitry Andric // [For] assignment to and initialization of pointers to functions, 41840b57cec5SDimitry Andric // pointers to member functions, and references to functions: the 41850b57cec5SDimitry Andric // target entity shall allow at least the exceptions allowed by the 41860b57cec5SDimitry Andric // source value in the assignment or initialization. 41870b57cec5SDimitry Andric switch (Action) { 41880b57cec5SDimitry Andric case AA_Assigning: 41890b57cec5SDimitry Andric case AA_Initializing: 41900b57cec5SDimitry Andric // Note, function argument passing and returning are initialization. 41910b57cec5SDimitry Andric case AA_Passing: 41920b57cec5SDimitry Andric case AA_Returning: 41930b57cec5SDimitry Andric case AA_Sending: 41940b57cec5SDimitry Andric case AA_Passing_CFAudited: 41950b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 41960b57cec5SDimitry Andric return ExprError(); 41970b57cec5SDimitry Andric break; 41980b57cec5SDimitry Andric 41990b57cec5SDimitry Andric case AA_Casting: 42000b57cec5SDimitry Andric case AA_Converting: 42010b57cec5SDimitry Andric // Casts and implicit conversions are not initialization, so are not 42020b57cec5SDimitry Andric // checked for exception specification mismatches. 42030b57cec5SDimitry Andric break; 42040b57cec5SDimitry Andric } 42050b57cec5SDimitry Andric // Nothing else to do. 42060b57cec5SDimitry Andric break; 42070b57cec5SDimitry Andric 42080b57cec5SDimitry Andric case ICK_Integral_Promotion: 42090b57cec5SDimitry Andric case ICK_Integral_Conversion: 42100b57cec5SDimitry Andric if (ToType->isBooleanType()) { 42110b57cec5SDimitry Andric assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 42120b57cec5SDimitry Andric SCS.Second == ICK_Integral_Promotion && 42130b57cec5SDimitry Andric "only enums with fixed underlying type can promote to bool"); 42140b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, 42150b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42160b57cec5SDimitry Andric } else { 42170b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralCast, 42180b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42190b57cec5SDimitry Andric } 42200b57cec5SDimitry Andric break; 42210b57cec5SDimitry Andric 42220b57cec5SDimitry Andric case ICK_Floating_Promotion: 42230b57cec5SDimitry Andric case ICK_Floating_Conversion: 42240b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_FloatingCast, 42250b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42260b57cec5SDimitry Andric break; 42270b57cec5SDimitry Andric 42280b57cec5SDimitry Andric case ICK_Complex_Promotion: 42290b57cec5SDimitry Andric case ICK_Complex_Conversion: { 4230a7dea167SDimitry Andric QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); 4231a7dea167SDimitry Andric QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); 42320b57cec5SDimitry Andric CastKind CK; 42330b57cec5SDimitry Andric if (FromEl->isRealFloatingType()) { 42340b57cec5SDimitry Andric if (ToEl->isRealFloatingType()) 42350b57cec5SDimitry Andric CK = CK_FloatingComplexCast; 42360b57cec5SDimitry Andric else 42370b57cec5SDimitry Andric CK = CK_FloatingComplexToIntegralComplex; 42380b57cec5SDimitry Andric } else if (ToEl->isRealFloatingType()) { 42390b57cec5SDimitry Andric CK = CK_IntegralComplexToFloatingComplex; 42400b57cec5SDimitry Andric } else { 42410b57cec5SDimitry Andric CK = CK_IntegralComplexCast; 42420b57cec5SDimitry Andric } 42430b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK, 42440b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42450b57cec5SDimitry Andric break; 42460b57cec5SDimitry Andric } 42470b57cec5SDimitry Andric 42480b57cec5SDimitry Andric case ICK_Floating_Integral: 42490b57cec5SDimitry Andric if (ToType->isRealFloatingType()) 42500b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 42510b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42520b57cec5SDimitry Andric else 42530b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 42540b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42550b57cec5SDimitry Andric break; 42560b57cec5SDimitry Andric 42570b57cec5SDimitry Andric case ICK_Compatible_Conversion: 4258f13e6193SDimitry Andric From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), 4259f13e6193SDimitry Andric /*BasePath=*/nullptr, CCK).get(); 42600b57cec5SDimitry Andric break; 42610b57cec5SDimitry Andric 42620b57cec5SDimitry Andric case ICK_Writeback_Conversion: 42630b57cec5SDimitry Andric case ICK_Pointer_Conversion: { 42640b57cec5SDimitry Andric if (SCS.IncompatibleObjC && Action != AA_Casting) { 42650b57cec5SDimitry Andric // Diagnose incompatible Objective-C conversions 42660b57cec5SDimitry Andric if (Action == AA_Initializing || Action == AA_Assigning) 42670b57cec5SDimitry Andric Diag(From->getBeginLoc(), 42680b57cec5SDimitry Andric diag::ext_typecheck_convert_incompatible_pointer) 42690b57cec5SDimitry Andric << ToType << From->getType() << Action << From->getSourceRange() 42700b57cec5SDimitry Andric << 0; 42710b57cec5SDimitry Andric else 42720b57cec5SDimitry Andric Diag(From->getBeginLoc(), 42730b57cec5SDimitry Andric diag::ext_typecheck_convert_incompatible_pointer) 42740b57cec5SDimitry Andric << From->getType() << ToType << Action << From->getSourceRange() 42750b57cec5SDimitry Andric << 0; 42760b57cec5SDimitry Andric 42770b57cec5SDimitry Andric if (From->getType()->isObjCObjectPointerType() && 42780b57cec5SDimitry Andric ToType->isObjCObjectPointerType()) 42790b57cec5SDimitry Andric EmitRelatedResultTypeNote(From); 42800b57cec5SDimitry Andric } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 42810b57cec5SDimitry Andric !CheckObjCARCUnavailableWeakConversion(ToType, 42820b57cec5SDimitry Andric From->getType())) { 42830b57cec5SDimitry Andric if (Action == AA_Initializing) 42840b57cec5SDimitry Andric Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); 42850b57cec5SDimitry Andric else 42860b57cec5SDimitry Andric Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) 42870b57cec5SDimitry Andric << (Action == AA_Casting) << From->getType() << ToType 42880b57cec5SDimitry Andric << From->getSourceRange(); 42890b57cec5SDimitry Andric } 42900b57cec5SDimitry Andric 4291480093f4SDimitry Andric // Defer address space conversion to the third conversion. 4292480093f4SDimitry Andric QualType FromPteeType = From->getType()->getPointeeType(); 4293480093f4SDimitry Andric QualType ToPteeType = ToType->getPointeeType(); 4294480093f4SDimitry Andric QualType NewToType = ToType; 4295480093f4SDimitry Andric if (!FromPteeType.isNull() && !ToPteeType.isNull() && 4296480093f4SDimitry Andric FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { 4297480093f4SDimitry Andric NewToType = Context.removeAddrSpaceQualType(ToPteeType); 4298480093f4SDimitry Andric NewToType = Context.getAddrSpaceQualType(NewToType, 4299480093f4SDimitry Andric FromPteeType.getAddressSpace()); 4300480093f4SDimitry Andric if (ToType->isObjCObjectPointerType()) 4301480093f4SDimitry Andric NewToType = Context.getObjCObjectPointerType(NewToType); 4302480093f4SDimitry Andric else if (ToType->isBlockPointerType()) 4303480093f4SDimitry Andric NewToType = Context.getBlockPointerType(NewToType); 4304480093f4SDimitry Andric else 4305480093f4SDimitry Andric NewToType = Context.getPointerType(NewToType); 4306480093f4SDimitry Andric } 4307480093f4SDimitry Andric 43080b57cec5SDimitry Andric CastKind Kind; 43090b57cec5SDimitry Andric CXXCastPath BasePath; 4310480093f4SDimitry Andric if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) 43110b57cec5SDimitry Andric return ExprError(); 43120b57cec5SDimitry Andric 43130b57cec5SDimitry Andric // Make sure we extend blocks if necessary. 43140b57cec5SDimitry Andric // FIXME: doing this here is really ugly. 43150b57cec5SDimitry Andric if (Kind == CK_BlockPointerToObjCPointerCast) { 43160b57cec5SDimitry Andric ExprResult E = From; 43170b57cec5SDimitry Andric (void) PrepareCastToObjCObjectPointer(E); 43180b57cec5SDimitry Andric From = E.get(); 43190b57cec5SDimitry Andric } 43200b57cec5SDimitry Andric if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 4321480093f4SDimitry Andric CheckObjCConversion(SourceRange(), NewToType, From, CCK); 4322480093f4SDimitry Andric From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK) 43230b57cec5SDimitry Andric .get(); 43240b57cec5SDimitry Andric break; 43250b57cec5SDimitry Andric } 43260b57cec5SDimitry Andric 43270b57cec5SDimitry Andric case ICK_Pointer_Member: { 43280b57cec5SDimitry Andric CastKind Kind; 43290b57cec5SDimitry Andric CXXCastPath BasePath; 43300b57cec5SDimitry Andric if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 43310b57cec5SDimitry Andric return ExprError(); 43320b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 43330b57cec5SDimitry Andric return ExprError(); 43340b57cec5SDimitry Andric 43350b57cec5SDimitry Andric // We may not have been able to figure out what this member pointer resolved 43360b57cec5SDimitry Andric // to up until this exact point. Attempt to lock-in it's inheritance model. 43370b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 43380b57cec5SDimitry Andric (void)isCompleteType(From->getExprLoc(), From->getType()); 43390b57cec5SDimitry Andric (void)isCompleteType(From->getExprLoc(), ToType); 43400b57cec5SDimitry Andric } 43410b57cec5SDimitry Andric 43420b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 43430b57cec5SDimitry Andric .get(); 43440b57cec5SDimitry Andric break; 43450b57cec5SDimitry Andric } 43460b57cec5SDimitry Andric 43470b57cec5SDimitry Andric case ICK_Boolean_Conversion: 43480b57cec5SDimitry Andric // Perform half-to-boolean conversion via float. 43490b57cec5SDimitry Andric if (From->getType()->isHalfType()) { 43500b57cec5SDimitry Andric From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 43510b57cec5SDimitry Andric FromType = Context.FloatTy; 43520b57cec5SDimitry Andric } 43530b57cec5SDimitry Andric 43540b57cec5SDimitry Andric From = ImpCastExprToType(From, Context.BoolTy, 43550b57cec5SDimitry Andric ScalarTypeToBooleanCastKind(FromType), 43560b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 43570b57cec5SDimitry Andric break; 43580b57cec5SDimitry Andric 43590b57cec5SDimitry Andric case ICK_Derived_To_Base: { 43600b57cec5SDimitry Andric CXXCastPath BasePath; 43610b57cec5SDimitry Andric if (CheckDerivedToBaseConversion( 43620b57cec5SDimitry Andric From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), 43630b57cec5SDimitry Andric From->getSourceRange(), &BasePath, CStyle)) 43640b57cec5SDimitry Andric return ExprError(); 43650b57cec5SDimitry Andric 43660b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getNonReferenceType(), 43670b57cec5SDimitry Andric CK_DerivedToBase, From->getValueKind(), 43680b57cec5SDimitry Andric &BasePath, CCK).get(); 43690b57cec5SDimitry Andric break; 43700b57cec5SDimitry Andric } 43710b57cec5SDimitry Andric 43720b57cec5SDimitry Andric case ICK_Vector_Conversion: 43730b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_BitCast, 43740b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 43750b57cec5SDimitry Andric break; 43760b57cec5SDimitry Andric 4377e8d8bef9SDimitry Andric case ICK_SVE_Vector_Conversion: 4378e8d8bef9SDimitry Andric From = ImpCastExprToType(From, ToType, CK_BitCast, VK_RValue, 4379e8d8bef9SDimitry Andric /*BasePath=*/nullptr, CCK) 4380e8d8bef9SDimitry Andric .get(); 4381e8d8bef9SDimitry Andric break; 4382e8d8bef9SDimitry Andric 43830b57cec5SDimitry Andric case ICK_Vector_Splat: { 43840b57cec5SDimitry Andric // Vector splat from any arithmetic type to a vector. 43850b57cec5SDimitry Andric Expr *Elem = prepareVectorSplat(ToType, From).get(); 43860b57cec5SDimitry Andric From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue, 43870b57cec5SDimitry Andric /*BasePath=*/nullptr, CCK).get(); 43880b57cec5SDimitry Andric break; 43890b57cec5SDimitry Andric } 43900b57cec5SDimitry Andric 43910b57cec5SDimitry Andric case ICK_Complex_Real: 43920b57cec5SDimitry Andric // Case 1. x -> _Complex y 43930b57cec5SDimitry Andric if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 43940b57cec5SDimitry Andric QualType ElType = ToComplex->getElementType(); 43950b57cec5SDimitry Andric bool isFloatingComplex = ElType->isRealFloatingType(); 43960b57cec5SDimitry Andric 43970b57cec5SDimitry Andric // x -> y 43980b57cec5SDimitry Andric if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 43990b57cec5SDimitry Andric // do nothing 44000b57cec5SDimitry Andric } else if (From->getType()->isRealFloatingType()) { 44010b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 44020b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 44030b57cec5SDimitry Andric } else { 44040b57cec5SDimitry Andric assert(From->getType()->isIntegerType()); 44050b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 44060b57cec5SDimitry Andric isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 44070b57cec5SDimitry Andric } 44080b57cec5SDimitry Andric // y -> _Complex y 44090b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 44100b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingRealToComplex 44110b57cec5SDimitry Andric : CK_IntegralRealToComplex).get(); 44120b57cec5SDimitry Andric 44130b57cec5SDimitry Andric // Case 2. _Complex x -> y 44140b57cec5SDimitry Andric } else { 44155ffd83dbSDimitry Andric auto *FromComplex = From->getType()->castAs<ComplexType>(); 44160b57cec5SDimitry Andric QualType ElType = FromComplex->getElementType(); 44170b57cec5SDimitry Andric bool isFloatingComplex = ElType->isRealFloatingType(); 44180b57cec5SDimitry Andric 44190b57cec5SDimitry Andric // _Complex x -> x 44200b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 44210b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingComplexToReal 44220b57cec5SDimitry Andric : CK_IntegralComplexToReal, 44230b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 44240b57cec5SDimitry Andric 44250b57cec5SDimitry Andric // x -> y 44260b57cec5SDimitry Andric if (Context.hasSameUnqualifiedType(ElType, ToType)) { 44270b57cec5SDimitry Andric // do nothing 44280b57cec5SDimitry Andric } else if (ToType->isRealFloatingType()) { 44290b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 44300b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 44310b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 44320b57cec5SDimitry Andric } else { 44330b57cec5SDimitry Andric assert(ToType->isIntegerType()); 44340b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 44350b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 44360b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 44370b57cec5SDimitry Andric } 44380b57cec5SDimitry Andric } 44390b57cec5SDimitry Andric break; 44400b57cec5SDimitry Andric 44410b57cec5SDimitry Andric case ICK_Block_Pointer_Conversion: { 44420b57cec5SDimitry Andric LangAS AddrSpaceL = 44430b57cec5SDimitry Andric ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 44440b57cec5SDimitry Andric LangAS AddrSpaceR = 44450b57cec5SDimitry Andric FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 44460b57cec5SDimitry Andric assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && 44470b57cec5SDimitry Andric "Invalid cast"); 44480b57cec5SDimitry Andric CastKind Kind = 44490b57cec5SDimitry Andric AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 44500b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, 44510b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 44520b57cec5SDimitry Andric break; 44530b57cec5SDimitry Andric } 44540b57cec5SDimitry Andric 44550b57cec5SDimitry Andric case ICK_TransparentUnionConversion: { 44560b57cec5SDimitry Andric ExprResult FromRes = From; 44570b57cec5SDimitry Andric Sema::AssignConvertType ConvTy = 44580b57cec5SDimitry Andric CheckTransparentUnionArgumentConstraints(ToType, FromRes); 44590b57cec5SDimitry Andric if (FromRes.isInvalid()) 44600b57cec5SDimitry Andric return ExprError(); 44610b57cec5SDimitry Andric From = FromRes.get(); 44620b57cec5SDimitry Andric assert ((ConvTy == Sema::Compatible) && 44630b57cec5SDimitry Andric "Improper transparent union conversion"); 44640b57cec5SDimitry Andric (void)ConvTy; 44650b57cec5SDimitry Andric break; 44660b57cec5SDimitry Andric } 44670b57cec5SDimitry Andric 44680b57cec5SDimitry Andric case ICK_Zero_Event_Conversion: 44690b57cec5SDimitry Andric case ICK_Zero_Queue_Conversion: 44700b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 44710b57cec5SDimitry Andric CK_ZeroToOCLOpaqueType, 44720b57cec5SDimitry Andric From->getValueKind()).get(); 44730b57cec5SDimitry Andric break; 44740b57cec5SDimitry Andric 44750b57cec5SDimitry Andric case ICK_Lvalue_To_Rvalue: 44760b57cec5SDimitry Andric case ICK_Array_To_Pointer: 44770b57cec5SDimitry Andric case ICK_Function_To_Pointer: 44780b57cec5SDimitry Andric case ICK_Function_Conversion: 44790b57cec5SDimitry Andric case ICK_Qualification: 44800b57cec5SDimitry Andric case ICK_Num_Conversion_Kinds: 44810b57cec5SDimitry Andric case ICK_C_Only_Conversion: 44820b57cec5SDimitry Andric case ICK_Incompatible_Pointer_Conversion: 44830b57cec5SDimitry Andric llvm_unreachable("Improper second standard conversion"); 44840b57cec5SDimitry Andric } 44850b57cec5SDimitry Andric 44860b57cec5SDimitry Andric switch (SCS.Third) { 44870b57cec5SDimitry Andric case ICK_Identity: 44880b57cec5SDimitry Andric // Nothing to do. 44890b57cec5SDimitry Andric break; 44900b57cec5SDimitry Andric 44910b57cec5SDimitry Andric case ICK_Function_Conversion: 44920b57cec5SDimitry Andric // If both sides are functions (or pointers/references to them), there could 44930b57cec5SDimitry Andric // be incompatible exception declarations. 44940b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 44950b57cec5SDimitry Andric return ExprError(); 44960b57cec5SDimitry Andric 44970b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_NoOp, 44980b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 44990b57cec5SDimitry Andric break; 45000b57cec5SDimitry Andric 45010b57cec5SDimitry Andric case ICK_Qualification: { 4502f13e6193SDimitry Andric ExprValueKind VK = From->getValueKind(); 45030b57cec5SDimitry Andric CastKind CK = CK_NoOp; 45040b57cec5SDimitry Andric 45050b57cec5SDimitry Andric if (ToType->isReferenceType() && 45060b57cec5SDimitry Andric ToType->getPointeeType().getAddressSpace() != 45070b57cec5SDimitry Andric From->getType().getAddressSpace()) 45080b57cec5SDimitry Andric CK = CK_AddressSpaceConversion; 45090b57cec5SDimitry Andric 45100b57cec5SDimitry Andric if (ToType->isPointerType() && 45110b57cec5SDimitry Andric ToType->getPointeeType().getAddressSpace() != 45120b57cec5SDimitry Andric From->getType()->getPointeeType().getAddressSpace()) 45130b57cec5SDimitry Andric CK = CK_AddressSpaceConversion; 45140b57cec5SDimitry Andric 45150b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, 45160b57cec5SDimitry Andric /*BasePath=*/nullptr, CCK) 45170b57cec5SDimitry Andric .get(); 45180b57cec5SDimitry Andric 45190b57cec5SDimitry Andric if (SCS.DeprecatedStringLiteralToCharPtr && 45200b57cec5SDimitry Andric !getLangOpts().WritableStrings) { 45210b57cec5SDimitry Andric Diag(From->getBeginLoc(), 45220b57cec5SDimitry Andric getLangOpts().CPlusPlus11 45230b57cec5SDimitry Andric ? diag::ext_deprecated_string_literal_conversion 45240b57cec5SDimitry Andric : diag::warn_deprecated_string_literal_conversion) 45250b57cec5SDimitry Andric << ToType.getNonReferenceType(); 45260b57cec5SDimitry Andric } 45270b57cec5SDimitry Andric 45280b57cec5SDimitry Andric break; 45290b57cec5SDimitry Andric } 45300b57cec5SDimitry Andric 45310b57cec5SDimitry Andric default: 45320b57cec5SDimitry Andric llvm_unreachable("Improper third standard conversion"); 45330b57cec5SDimitry Andric } 45340b57cec5SDimitry Andric 45350b57cec5SDimitry Andric // If this conversion sequence involved a scalar -> atomic conversion, perform 45360b57cec5SDimitry Andric // that conversion now. 45370b57cec5SDimitry Andric if (!ToAtomicType.isNull()) { 45380b57cec5SDimitry Andric assert(Context.hasSameType( 45390b57cec5SDimitry Andric ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); 45400b57cec5SDimitry Andric From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 45410b57cec5SDimitry Andric VK_RValue, nullptr, CCK).get(); 45420b57cec5SDimitry Andric } 45430b57cec5SDimitry Andric 45445ffd83dbSDimitry Andric // Materialize a temporary if we're implicitly converting to a reference 45455ffd83dbSDimitry Andric // type. This is not required by the C++ rules but is necessary to maintain 45465ffd83dbSDimitry Andric // AST invariants. 45475ffd83dbSDimitry Andric if (ToType->isReferenceType() && From->isRValue()) { 45485ffd83dbSDimitry Andric ExprResult Res = TemporaryMaterializationConversion(From); 45495ffd83dbSDimitry Andric if (Res.isInvalid()) 45505ffd83dbSDimitry Andric return ExprError(); 45515ffd83dbSDimitry Andric From = Res.get(); 45525ffd83dbSDimitry Andric } 45535ffd83dbSDimitry Andric 45540b57cec5SDimitry Andric // If this conversion sequence succeeded and involved implicitly converting a 45550b57cec5SDimitry Andric // _Nullable type to a _Nonnull one, complain. 45560b57cec5SDimitry Andric if (!isCast(CCK)) 45570b57cec5SDimitry Andric diagnoseNullableToNonnullConversion(ToType, InitialFromType, 45580b57cec5SDimitry Andric From->getBeginLoc()); 45590b57cec5SDimitry Andric 45600b57cec5SDimitry Andric return From; 45610b57cec5SDimitry Andric } 45620b57cec5SDimitry Andric 45630b57cec5SDimitry Andric /// Check the completeness of a type in a unary type trait. 45640b57cec5SDimitry Andric /// 45650b57cec5SDimitry Andric /// If the particular type trait requires a complete type, tries to complete 45660b57cec5SDimitry Andric /// it. If completing the type fails, a diagnostic is emitted and false 45670b57cec5SDimitry Andric /// returned. If completing the type succeeds or no completion was required, 45680b57cec5SDimitry Andric /// returns true. 45690b57cec5SDimitry Andric static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 45700b57cec5SDimitry Andric SourceLocation Loc, 45710b57cec5SDimitry Andric QualType ArgTy) { 45720b57cec5SDimitry Andric // C++0x [meta.unary.prop]p3: 45730b57cec5SDimitry Andric // For all of the class templates X declared in this Clause, instantiating 45740b57cec5SDimitry Andric // that template with a template argument that is a class template 45750b57cec5SDimitry Andric // specialization may result in the implicit instantiation of the template 45760b57cec5SDimitry Andric // argument if and only if the semantics of X require that the argument 45770b57cec5SDimitry Andric // must be a complete type. 45780b57cec5SDimitry Andric // We apply this rule to all the type trait expressions used to implement 45790b57cec5SDimitry Andric // these class templates. We also try to follow any GCC documented behavior 45800b57cec5SDimitry Andric // in these expressions to ensure portability of standard libraries. 45810b57cec5SDimitry Andric switch (UTT) { 45820b57cec5SDimitry Andric default: llvm_unreachable("not a UTT"); 45830b57cec5SDimitry Andric // is_complete_type somewhat obviously cannot require a complete type. 45840b57cec5SDimitry Andric case UTT_IsCompleteType: 45850b57cec5SDimitry Andric // Fall-through 45860b57cec5SDimitry Andric 45870b57cec5SDimitry Andric // These traits are modeled on the type predicates in C++0x 45880b57cec5SDimitry Andric // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 45890b57cec5SDimitry Andric // requiring a complete type, as whether or not they return true cannot be 45900b57cec5SDimitry Andric // impacted by the completeness of the type. 45910b57cec5SDimitry Andric case UTT_IsVoid: 45920b57cec5SDimitry Andric case UTT_IsIntegral: 45930b57cec5SDimitry Andric case UTT_IsFloatingPoint: 45940b57cec5SDimitry Andric case UTT_IsArray: 45950b57cec5SDimitry Andric case UTT_IsPointer: 45960b57cec5SDimitry Andric case UTT_IsLvalueReference: 45970b57cec5SDimitry Andric case UTT_IsRvalueReference: 45980b57cec5SDimitry Andric case UTT_IsMemberFunctionPointer: 45990b57cec5SDimitry Andric case UTT_IsMemberObjectPointer: 46000b57cec5SDimitry Andric case UTT_IsEnum: 46010b57cec5SDimitry Andric case UTT_IsUnion: 46020b57cec5SDimitry Andric case UTT_IsClass: 46030b57cec5SDimitry Andric case UTT_IsFunction: 46040b57cec5SDimitry Andric case UTT_IsReference: 46050b57cec5SDimitry Andric case UTT_IsArithmetic: 46060b57cec5SDimitry Andric case UTT_IsFundamental: 46070b57cec5SDimitry Andric case UTT_IsObject: 46080b57cec5SDimitry Andric case UTT_IsScalar: 46090b57cec5SDimitry Andric case UTT_IsCompound: 46100b57cec5SDimitry Andric case UTT_IsMemberPointer: 46110b57cec5SDimitry Andric // Fall-through 46120b57cec5SDimitry Andric 46130b57cec5SDimitry Andric // These traits are modeled on type predicates in C++0x [meta.unary.prop] 46140b57cec5SDimitry Andric // which requires some of its traits to have the complete type. However, 46150b57cec5SDimitry Andric // the completeness of the type cannot impact these traits' semantics, and 46160b57cec5SDimitry Andric // so they don't require it. This matches the comments on these traits in 46170b57cec5SDimitry Andric // Table 49. 46180b57cec5SDimitry Andric case UTT_IsConst: 46190b57cec5SDimitry Andric case UTT_IsVolatile: 46200b57cec5SDimitry Andric case UTT_IsSigned: 46210b57cec5SDimitry Andric case UTT_IsUnsigned: 46220b57cec5SDimitry Andric 46230b57cec5SDimitry Andric // This type trait always returns false, checking the type is moot. 46240b57cec5SDimitry Andric case UTT_IsInterfaceClass: 46250b57cec5SDimitry Andric return true; 46260b57cec5SDimitry Andric 46270b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 46280b57cec5SDimitry Andric // If T is a non-union class type, T shall be a complete type. 46290b57cec5SDimitry Andric case UTT_IsEmpty: 46300b57cec5SDimitry Andric case UTT_IsPolymorphic: 46310b57cec5SDimitry Andric case UTT_IsAbstract: 46320b57cec5SDimitry Andric if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 46330b57cec5SDimitry Andric if (!RD->isUnion()) 46340b57cec5SDimitry Andric return !S.RequireCompleteType( 46350b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 46360b57cec5SDimitry Andric return true; 46370b57cec5SDimitry Andric 46380b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 46390b57cec5SDimitry Andric // If T is a class type, T shall be a complete type. 46400b57cec5SDimitry Andric case UTT_IsFinal: 46410b57cec5SDimitry Andric case UTT_IsSealed: 46420b57cec5SDimitry Andric if (ArgTy->getAsCXXRecordDecl()) 46430b57cec5SDimitry Andric return !S.RequireCompleteType( 46440b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 46450b57cec5SDimitry Andric return true; 46460b57cec5SDimitry Andric 46470b57cec5SDimitry Andric // C++1z [meta.unary.prop]: 46480b57cec5SDimitry Andric // remove_all_extents_t<T> shall be a complete type or cv void. 46490b57cec5SDimitry Andric case UTT_IsAggregate: 46500b57cec5SDimitry Andric case UTT_IsTrivial: 46510b57cec5SDimitry Andric case UTT_IsTriviallyCopyable: 46520b57cec5SDimitry Andric case UTT_IsStandardLayout: 46530b57cec5SDimitry Andric case UTT_IsPOD: 46540b57cec5SDimitry Andric case UTT_IsLiteral: 46550b57cec5SDimitry Andric // Per the GCC type traits documentation, T shall be a complete type, cv void, 46560b57cec5SDimitry Andric // or an array of unknown bound. But GCC actually imposes the same constraints 46570b57cec5SDimitry Andric // as above. 46580b57cec5SDimitry Andric case UTT_HasNothrowAssign: 46590b57cec5SDimitry Andric case UTT_HasNothrowMoveAssign: 46600b57cec5SDimitry Andric case UTT_HasNothrowConstructor: 46610b57cec5SDimitry Andric case UTT_HasNothrowCopy: 46620b57cec5SDimitry Andric case UTT_HasTrivialAssign: 46630b57cec5SDimitry Andric case UTT_HasTrivialMoveAssign: 46640b57cec5SDimitry Andric case UTT_HasTrivialDefaultConstructor: 46650b57cec5SDimitry Andric case UTT_HasTrivialMoveConstructor: 46660b57cec5SDimitry Andric case UTT_HasTrivialCopy: 46670b57cec5SDimitry Andric case UTT_HasTrivialDestructor: 46680b57cec5SDimitry Andric case UTT_HasVirtualDestructor: 46690b57cec5SDimitry Andric ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); 46700b57cec5SDimitry Andric LLVM_FALLTHROUGH; 46710b57cec5SDimitry Andric 46720b57cec5SDimitry Andric // C++1z [meta.unary.prop]: 46730b57cec5SDimitry Andric // T shall be a complete type, cv void, or an array of unknown bound. 46740b57cec5SDimitry Andric case UTT_IsDestructible: 46750b57cec5SDimitry Andric case UTT_IsNothrowDestructible: 46760b57cec5SDimitry Andric case UTT_IsTriviallyDestructible: 46770b57cec5SDimitry Andric case UTT_HasUniqueObjectRepresentations: 46780b57cec5SDimitry Andric if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) 46790b57cec5SDimitry Andric return true; 46800b57cec5SDimitry Andric 46810b57cec5SDimitry Andric return !S.RequireCompleteType( 46820b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 46830b57cec5SDimitry Andric } 46840b57cec5SDimitry Andric } 46850b57cec5SDimitry Andric 46860b57cec5SDimitry Andric static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 46870b57cec5SDimitry Andric Sema &Self, SourceLocation KeyLoc, ASTContext &C, 46880b57cec5SDimitry Andric bool (CXXRecordDecl::*HasTrivial)() const, 46890b57cec5SDimitry Andric bool (CXXRecordDecl::*HasNonTrivial)() const, 46900b57cec5SDimitry Andric bool (CXXMethodDecl::*IsDesiredOp)() const) 46910b57cec5SDimitry Andric { 46920b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 46930b57cec5SDimitry Andric if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 46940b57cec5SDimitry Andric return true; 46950b57cec5SDimitry Andric 46960b57cec5SDimitry Andric DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 46970b57cec5SDimitry Andric DeclarationNameInfo NameInfo(Name, KeyLoc); 46980b57cec5SDimitry Andric LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 46990b57cec5SDimitry Andric if (Self.LookupQualifiedName(Res, RD)) { 47000b57cec5SDimitry Andric bool FoundOperator = false; 47010b57cec5SDimitry Andric Res.suppressDiagnostics(); 47020b57cec5SDimitry Andric for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 47030b57cec5SDimitry Andric Op != OpEnd; ++Op) { 47040b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(*Op)) 47050b57cec5SDimitry Andric continue; 47060b57cec5SDimitry Andric 47070b57cec5SDimitry Andric CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 47080b57cec5SDimitry Andric if((Operator->*IsDesiredOp)()) { 47090b57cec5SDimitry Andric FoundOperator = true; 47105ffd83dbSDimitry Andric auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); 47110b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 47120b57cec5SDimitry Andric if (!CPT || !CPT->isNothrow()) 47130b57cec5SDimitry Andric return false; 47140b57cec5SDimitry Andric } 47150b57cec5SDimitry Andric } 47160b57cec5SDimitry Andric return FoundOperator; 47170b57cec5SDimitry Andric } 47180b57cec5SDimitry Andric return false; 47190b57cec5SDimitry Andric } 47200b57cec5SDimitry Andric 47210b57cec5SDimitry Andric static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 47220b57cec5SDimitry Andric SourceLocation KeyLoc, QualType T) { 47230b57cec5SDimitry Andric assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 47240b57cec5SDimitry Andric 47250b57cec5SDimitry Andric ASTContext &C = Self.Context; 47260b57cec5SDimitry Andric switch(UTT) { 47270b57cec5SDimitry Andric default: llvm_unreachable("not a UTT"); 47280b57cec5SDimitry Andric // Type trait expressions corresponding to the primary type category 47290b57cec5SDimitry Andric // predicates in C++0x [meta.unary.cat]. 47300b57cec5SDimitry Andric case UTT_IsVoid: 47310b57cec5SDimitry Andric return T->isVoidType(); 47320b57cec5SDimitry Andric case UTT_IsIntegral: 47330b57cec5SDimitry Andric return T->isIntegralType(C); 47340b57cec5SDimitry Andric case UTT_IsFloatingPoint: 47350b57cec5SDimitry Andric return T->isFloatingType(); 47360b57cec5SDimitry Andric case UTT_IsArray: 47370b57cec5SDimitry Andric return T->isArrayType(); 47380b57cec5SDimitry Andric case UTT_IsPointer: 47395ffd83dbSDimitry Andric return T->isAnyPointerType(); 47400b57cec5SDimitry Andric case UTT_IsLvalueReference: 47410b57cec5SDimitry Andric return T->isLValueReferenceType(); 47420b57cec5SDimitry Andric case UTT_IsRvalueReference: 47430b57cec5SDimitry Andric return T->isRValueReferenceType(); 47440b57cec5SDimitry Andric case UTT_IsMemberFunctionPointer: 47450b57cec5SDimitry Andric return T->isMemberFunctionPointerType(); 47460b57cec5SDimitry Andric case UTT_IsMemberObjectPointer: 47470b57cec5SDimitry Andric return T->isMemberDataPointerType(); 47480b57cec5SDimitry Andric case UTT_IsEnum: 47490b57cec5SDimitry Andric return T->isEnumeralType(); 47500b57cec5SDimitry Andric case UTT_IsUnion: 47510b57cec5SDimitry Andric return T->isUnionType(); 47520b57cec5SDimitry Andric case UTT_IsClass: 47530b57cec5SDimitry Andric return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 47540b57cec5SDimitry Andric case UTT_IsFunction: 47550b57cec5SDimitry Andric return T->isFunctionType(); 47560b57cec5SDimitry Andric 47570b57cec5SDimitry Andric // Type trait expressions which correspond to the convenient composition 47580b57cec5SDimitry Andric // predicates in C++0x [meta.unary.comp]. 47590b57cec5SDimitry Andric case UTT_IsReference: 47600b57cec5SDimitry Andric return T->isReferenceType(); 47610b57cec5SDimitry Andric case UTT_IsArithmetic: 47620b57cec5SDimitry Andric return T->isArithmeticType() && !T->isEnumeralType(); 47630b57cec5SDimitry Andric case UTT_IsFundamental: 47640b57cec5SDimitry Andric return T->isFundamentalType(); 47650b57cec5SDimitry Andric case UTT_IsObject: 47660b57cec5SDimitry Andric return T->isObjectType(); 47670b57cec5SDimitry Andric case UTT_IsScalar: 47680b57cec5SDimitry Andric // Note: semantic analysis depends on Objective-C lifetime types to be 47690b57cec5SDimitry Andric // considered scalar types. However, such types do not actually behave 47700b57cec5SDimitry Andric // like scalar types at run time (since they may require retain/release 47710b57cec5SDimitry Andric // operations), so we report them as non-scalar. 47720b57cec5SDimitry Andric if (T->isObjCLifetimeType()) { 47730b57cec5SDimitry Andric switch (T.getObjCLifetime()) { 47740b57cec5SDimitry Andric case Qualifiers::OCL_None: 47750b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone: 47760b57cec5SDimitry Andric return true; 47770b57cec5SDimitry Andric 47780b57cec5SDimitry Andric case Qualifiers::OCL_Strong: 47790b57cec5SDimitry Andric case Qualifiers::OCL_Weak: 47800b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing: 47810b57cec5SDimitry Andric return false; 47820b57cec5SDimitry Andric } 47830b57cec5SDimitry Andric } 47840b57cec5SDimitry Andric 47850b57cec5SDimitry Andric return T->isScalarType(); 47860b57cec5SDimitry Andric case UTT_IsCompound: 47870b57cec5SDimitry Andric return T->isCompoundType(); 47880b57cec5SDimitry Andric case UTT_IsMemberPointer: 47890b57cec5SDimitry Andric return T->isMemberPointerType(); 47900b57cec5SDimitry Andric 47910b57cec5SDimitry Andric // Type trait expressions which correspond to the type property predicates 47920b57cec5SDimitry Andric // in C++0x [meta.unary.prop]. 47930b57cec5SDimitry Andric case UTT_IsConst: 47940b57cec5SDimitry Andric return T.isConstQualified(); 47950b57cec5SDimitry Andric case UTT_IsVolatile: 47960b57cec5SDimitry Andric return T.isVolatileQualified(); 47970b57cec5SDimitry Andric case UTT_IsTrivial: 47980b57cec5SDimitry Andric return T.isTrivialType(C); 47990b57cec5SDimitry Andric case UTT_IsTriviallyCopyable: 48000b57cec5SDimitry Andric return T.isTriviallyCopyableType(C); 48010b57cec5SDimitry Andric case UTT_IsStandardLayout: 48020b57cec5SDimitry Andric return T->isStandardLayoutType(); 48030b57cec5SDimitry Andric case UTT_IsPOD: 48040b57cec5SDimitry Andric return T.isPODType(C); 48050b57cec5SDimitry Andric case UTT_IsLiteral: 48060b57cec5SDimitry Andric return T->isLiteralType(C); 48070b57cec5SDimitry Andric case UTT_IsEmpty: 48080b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 48090b57cec5SDimitry Andric return !RD->isUnion() && RD->isEmpty(); 48100b57cec5SDimitry Andric return false; 48110b57cec5SDimitry Andric case UTT_IsPolymorphic: 48120b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 48130b57cec5SDimitry Andric return !RD->isUnion() && RD->isPolymorphic(); 48140b57cec5SDimitry Andric return false; 48150b57cec5SDimitry Andric case UTT_IsAbstract: 48160b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 48170b57cec5SDimitry Andric return !RD->isUnion() && RD->isAbstract(); 48180b57cec5SDimitry Andric return false; 48190b57cec5SDimitry Andric case UTT_IsAggregate: 48200b57cec5SDimitry Andric // Report vector extensions and complex types as aggregates because they 48210b57cec5SDimitry Andric // support aggregate initialization. GCC mirrors this behavior for vectors 48220b57cec5SDimitry Andric // but not _Complex. 48230b57cec5SDimitry Andric return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || 48240b57cec5SDimitry Andric T->isAnyComplexType(); 48250b57cec5SDimitry Andric // __is_interface_class only returns true when CL is invoked in /CLR mode and 48260b57cec5SDimitry Andric // even then only when it is used with the 'interface struct ...' syntax 48270b57cec5SDimitry Andric // Clang doesn't support /CLR which makes this type trait moot. 48280b57cec5SDimitry Andric case UTT_IsInterfaceClass: 48290b57cec5SDimitry Andric return false; 48300b57cec5SDimitry Andric case UTT_IsFinal: 48310b57cec5SDimitry Andric case UTT_IsSealed: 48320b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 48330b57cec5SDimitry Andric return RD->hasAttr<FinalAttr>(); 48340b57cec5SDimitry Andric return false; 48350b57cec5SDimitry Andric case UTT_IsSigned: 4836a7dea167SDimitry Andric // Enum types should always return false. 4837a7dea167SDimitry Andric // Floating points should always return true. 4838a7dea167SDimitry Andric return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType()); 48390b57cec5SDimitry Andric case UTT_IsUnsigned: 48400b57cec5SDimitry Andric return T->isUnsignedIntegerType(); 48410b57cec5SDimitry Andric 48420b57cec5SDimitry Andric // Type trait expressions which query classes regarding their construction, 48430b57cec5SDimitry Andric // destruction, and copying. Rather than being based directly on the 48440b57cec5SDimitry Andric // related type predicates in the standard, they are specified by both 48450b57cec5SDimitry Andric // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 48460b57cec5SDimitry Andric // specifications. 48470b57cec5SDimitry Andric // 48480b57cec5SDimitry Andric // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 48490b57cec5SDimitry Andric // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 48500b57cec5SDimitry Andric // 48510b57cec5SDimitry Andric // Note that these builtins do not behave as documented in g++: if a class 48520b57cec5SDimitry Andric // has both a trivial and a non-trivial special member of a particular kind, 48530b57cec5SDimitry Andric // they return false! For now, we emulate this behavior. 48540b57cec5SDimitry Andric // FIXME: This appears to be a g++ bug: more complex cases reveal that it 48550b57cec5SDimitry Andric // does not correctly compute triviality in the presence of multiple special 48560b57cec5SDimitry Andric // members of the same kind. Revisit this once the g++ bug is fixed. 48570b57cec5SDimitry Andric case UTT_HasTrivialDefaultConstructor: 48580b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 48590b57cec5SDimitry Andric // If __is_pod (type) is true then the trait is true, else if type is 48600b57cec5SDimitry Andric // a cv class or union type (or array thereof) with a trivial default 48610b57cec5SDimitry Andric // constructor ([class.ctor]) then the trait is true, else it is false. 48620b57cec5SDimitry Andric if (T.isPODType(C)) 48630b57cec5SDimitry Andric return true; 48640b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 48650b57cec5SDimitry Andric return RD->hasTrivialDefaultConstructor() && 48660b57cec5SDimitry Andric !RD->hasNonTrivialDefaultConstructor(); 48670b57cec5SDimitry Andric return false; 48680b57cec5SDimitry Andric case UTT_HasTrivialMoveConstructor: 48690b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 48700b57cec5SDimitry Andric // standard library headers. Specifically this is used as the logic 48710b57cec5SDimitry Andric // behind std::is_trivially_move_constructible (20.9.4.3). 48720b57cec5SDimitry Andric if (T.isPODType(C)) 48730b57cec5SDimitry Andric return true; 48740b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 48750b57cec5SDimitry Andric return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 48760b57cec5SDimitry Andric return false; 48770b57cec5SDimitry Andric case UTT_HasTrivialCopy: 48780b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 48790b57cec5SDimitry Andric // If __is_pod (type) is true or type is a reference type then 48800b57cec5SDimitry Andric // the trait is true, else if type is a cv class or union type 48810b57cec5SDimitry Andric // with a trivial copy constructor ([class.copy]) then the trait 48820b57cec5SDimitry Andric // is true, else it is false. 48830b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType()) 48840b57cec5SDimitry Andric return true; 48850b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 48860b57cec5SDimitry Andric return RD->hasTrivialCopyConstructor() && 48870b57cec5SDimitry Andric !RD->hasNonTrivialCopyConstructor(); 48880b57cec5SDimitry Andric return false; 48890b57cec5SDimitry Andric case UTT_HasTrivialMoveAssign: 48900b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 48910b57cec5SDimitry Andric // standard library headers. Specifically it is used as the logic 48920b57cec5SDimitry Andric // behind std::is_trivially_move_assignable (20.9.4.3) 48930b57cec5SDimitry Andric if (T.isPODType(C)) 48940b57cec5SDimitry Andric return true; 48950b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 48960b57cec5SDimitry Andric return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 48970b57cec5SDimitry Andric return false; 48980b57cec5SDimitry Andric case UTT_HasTrivialAssign: 48990b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 49000b57cec5SDimitry Andric // If type is const qualified or is a reference type then the 49010b57cec5SDimitry Andric // trait is false. Otherwise if __is_pod (type) is true then the 49020b57cec5SDimitry Andric // trait is true, else if type is a cv class or union type with 49030b57cec5SDimitry Andric // a trivial copy assignment ([class.copy]) then the trait is 49040b57cec5SDimitry Andric // true, else it is false. 49050b57cec5SDimitry Andric // Note: the const and reference restrictions are interesting, 49060b57cec5SDimitry Andric // given that const and reference members don't prevent a class 49070b57cec5SDimitry Andric // from having a trivial copy assignment operator (but do cause 49080b57cec5SDimitry Andric // errors if the copy assignment operator is actually used, q.v. 49090b57cec5SDimitry Andric // [class.copy]p12). 49100b57cec5SDimitry Andric 49110b57cec5SDimitry Andric if (T.isConstQualified()) 49120b57cec5SDimitry Andric return false; 49130b57cec5SDimitry Andric if (T.isPODType(C)) 49140b57cec5SDimitry Andric return true; 49150b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49160b57cec5SDimitry Andric return RD->hasTrivialCopyAssignment() && 49170b57cec5SDimitry Andric !RD->hasNonTrivialCopyAssignment(); 49180b57cec5SDimitry Andric return false; 49190b57cec5SDimitry Andric case UTT_IsDestructible: 49200b57cec5SDimitry Andric case UTT_IsTriviallyDestructible: 49210b57cec5SDimitry Andric case UTT_IsNothrowDestructible: 49220b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 49230b57cec5SDimitry Andric // For reference types, is_destructible<T>::value is true. 49240b57cec5SDimitry Andric if (T->isReferenceType()) 49250b57cec5SDimitry Andric return true; 49260b57cec5SDimitry Andric 49270b57cec5SDimitry Andric // Objective-C++ ARC: autorelease types don't require destruction. 49280b57cec5SDimitry Andric if (T->isObjCLifetimeType() && 49290b57cec5SDimitry Andric T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 49300b57cec5SDimitry Andric return true; 49310b57cec5SDimitry Andric 49320b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 49330b57cec5SDimitry Andric // For incomplete types and function types, is_destructible<T>::value is 49340b57cec5SDimitry Andric // false. 49350b57cec5SDimitry Andric if (T->isIncompleteType() || T->isFunctionType()) 49360b57cec5SDimitry Andric return false; 49370b57cec5SDimitry Andric 49380b57cec5SDimitry Andric // A type that requires destruction (via a non-trivial destructor or ARC 49390b57cec5SDimitry Andric // lifetime semantics) is not trivially-destructible. 49400b57cec5SDimitry Andric if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) 49410b57cec5SDimitry Andric return false; 49420b57cec5SDimitry Andric 49430b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 49440b57cec5SDimitry Andric // For object types and given U equal to remove_all_extents_t<T>, if the 49450b57cec5SDimitry Andric // expression std::declval<U&>().~U() is well-formed when treated as an 49460b57cec5SDimitry Andric // unevaluated operand (Clause 5), then is_destructible<T>::value is true 49470b57cec5SDimitry Andric if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 49480b57cec5SDimitry Andric CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 49490b57cec5SDimitry Andric if (!Destructor) 49500b57cec5SDimitry Andric return false; 49510b57cec5SDimitry Andric // C++14 [dcl.fct.def.delete]p2: 49520b57cec5SDimitry Andric // A program that refers to a deleted function implicitly or 49530b57cec5SDimitry Andric // explicitly, other than to declare it, is ill-formed. 49540b57cec5SDimitry Andric if (Destructor->isDeleted()) 49550b57cec5SDimitry Andric return false; 49560b57cec5SDimitry Andric if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 49570b57cec5SDimitry Andric return false; 49580b57cec5SDimitry Andric if (UTT == UTT_IsNothrowDestructible) { 49595ffd83dbSDimitry Andric auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); 49600b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 49610b57cec5SDimitry Andric if (!CPT || !CPT->isNothrow()) 49620b57cec5SDimitry Andric return false; 49630b57cec5SDimitry Andric } 49640b57cec5SDimitry Andric } 49650b57cec5SDimitry Andric return true; 49660b57cec5SDimitry Andric 49670b57cec5SDimitry Andric case UTT_HasTrivialDestructor: 49680b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 49690b57cec5SDimitry Andric // If __is_pod (type) is true or type is a reference type 49700b57cec5SDimitry Andric // then the trait is true, else if type is a cv class or union 49710b57cec5SDimitry Andric // type (or array thereof) with a trivial destructor 49720b57cec5SDimitry Andric // ([class.dtor]) then the trait is true, else it is 49730b57cec5SDimitry Andric // false. 49740b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType()) 49750b57cec5SDimitry Andric return true; 49760b57cec5SDimitry Andric 49770b57cec5SDimitry Andric // Objective-C++ ARC: autorelease types don't require destruction. 49780b57cec5SDimitry Andric if (T->isObjCLifetimeType() && 49790b57cec5SDimitry Andric T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 49800b57cec5SDimitry Andric return true; 49810b57cec5SDimitry Andric 49820b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 49830b57cec5SDimitry Andric return RD->hasTrivialDestructor(); 49840b57cec5SDimitry Andric return false; 49850b57cec5SDimitry Andric // TODO: Propagate nothrowness for implicitly declared special members. 49860b57cec5SDimitry Andric case UTT_HasNothrowAssign: 49870b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 49880b57cec5SDimitry Andric // If type is const qualified or is a reference type then the 49890b57cec5SDimitry Andric // trait is false. Otherwise if __has_trivial_assign (type) 49900b57cec5SDimitry Andric // is true then the trait is true, else if type is a cv class 49910b57cec5SDimitry Andric // or union type with copy assignment operators that are known 49920b57cec5SDimitry Andric // not to throw an exception then the trait is true, else it is 49930b57cec5SDimitry Andric // false. 49940b57cec5SDimitry Andric if (C.getBaseElementType(T).isConstQualified()) 49950b57cec5SDimitry Andric return false; 49960b57cec5SDimitry Andric if (T->isReferenceType()) 49970b57cec5SDimitry Andric return false; 49980b57cec5SDimitry Andric if (T.isPODType(C) || T->isObjCLifetimeType()) 49990b57cec5SDimitry Andric return true; 50000b57cec5SDimitry Andric 50010b57cec5SDimitry Andric if (const RecordType *RT = T->getAs<RecordType>()) 50020b57cec5SDimitry Andric return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 50030b57cec5SDimitry Andric &CXXRecordDecl::hasTrivialCopyAssignment, 50040b57cec5SDimitry Andric &CXXRecordDecl::hasNonTrivialCopyAssignment, 50050b57cec5SDimitry Andric &CXXMethodDecl::isCopyAssignmentOperator); 50060b57cec5SDimitry Andric return false; 50070b57cec5SDimitry Andric case UTT_HasNothrowMoveAssign: 50080b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 50090b57cec5SDimitry Andric // standard library headers. Specifically this is used as the logic 50100b57cec5SDimitry Andric // behind std::is_nothrow_move_assignable (20.9.4.3). 50110b57cec5SDimitry Andric if (T.isPODType(C)) 50120b57cec5SDimitry Andric return true; 50130b57cec5SDimitry Andric 50140b57cec5SDimitry Andric if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 50150b57cec5SDimitry Andric return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 50160b57cec5SDimitry Andric &CXXRecordDecl::hasTrivialMoveAssignment, 50170b57cec5SDimitry Andric &CXXRecordDecl::hasNonTrivialMoveAssignment, 50180b57cec5SDimitry Andric &CXXMethodDecl::isMoveAssignmentOperator); 50190b57cec5SDimitry Andric return false; 50200b57cec5SDimitry Andric case UTT_HasNothrowCopy: 50210b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 50220b57cec5SDimitry Andric // If __has_trivial_copy (type) is true then the trait is true, else 50230b57cec5SDimitry Andric // if type is a cv class or union type with copy constructors that are 50240b57cec5SDimitry Andric // known not to throw an exception then the trait is true, else it is 50250b57cec5SDimitry Andric // false. 50260b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 50270b57cec5SDimitry Andric return true; 50280b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 50290b57cec5SDimitry Andric if (RD->hasTrivialCopyConstructor() && 50300b57cec5SDimitry Andric !RD->hasNonTrivialCopyConstructor()) 50310b57cec5SDimitry Andric return true; 50320b57cec5SDimitry Andric 50330b57cec5SDimitry Andric bool FoundConstructor = false; 50340b57cec5SDimitry Andric unsigned FoundTQs; 50350b57cec5SDimitry Andric for (const auto *ND : Self.LookupConstructors(RD)) { 50360b57cec5SDimitry Andric // A template constructor is never a copy constructor. 50370b57cec5SDimitry Andric // FIXME: However, it may actually be selected at the actual overload 50380b57cec5SDimitry Andric // resolution point. 50390b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 50400b57cec5SDimitry Andric continue; 50410b57cec5SDimitry Andric // UsingDecl itself is not a constructor 50420b57cec5SDimitry Andric if (isa<UsingDecl>(ND)) 50430b57cec5SDimitry Andric continue; 50440b57cec5SDimitry Andric auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 50450b57cec5SDimitry Andric if (Constructor->isCopyConstructor(FoundTQs)) { 50460b57cec5SDimitry Andric FoundConstructor = true; 50475ffd83dbSDimitry Andric auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 50480b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 50490b57cec5SDimitry Andric if (!CPT) 50500b57cec5SDimitry Andric return false; 50510b57cec5SDimitry Andric // TODO: check whether evaluating default arguments can throw. 50520b57cec5SDimitry Andric // For now, we'll be conservative and assume that they can throw. 50530b57cec5SDimitry Andric if (!CPT->isNothrow() || CPT->getNumParams() > 1) 50540b57cec5SDimitry Andric return false; 50550b57cec5SDimitry Andric } 50560b57cec5SDimitry Andric } 50570b57cec5SDimitry Andric 50580b57cec5SDimitry Andric return FoundConstructor; 50590b57cec5SDimitry Andric } 50600b57cec5SDimitry Andric return false; 50610b57cec5SDimitry Andric case UTT_HasNothrowConstructor: 50620b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 50630b57cec5SDimitry Andric // If __has_trivial_constructor (type) is true then the trait is 50640b57cec5SDimitry Andric // true, else if type is a cv class or union type (or array 50650b57cec5SDimitry Andric // thereof) with a default constructor that is known not to 50660b57cec5SDimitry Andric // throw an exception then the trait is true, else it is false. 50670b57cec5SDimitry Andric if (T.isPODType(C) || T->isObjCLifetimeType()) 50680b57cec5SDimitry Andric return true; 50690b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 50700b57cec5SDimitry Andric if (RD->hasTrivialDefaultConstructor() && 50710b57cec5SDimitry Andric !RD->hasNonTrivialDefaultConstructor()) 50720b57cec5SDimitry Andric return true; 50730b57cec5SDimitry Andric 50740b57cec5SDimitry Andric bool FoundConstructor = false; 50750b57cec5SDimitry Andric for (const auto *ND : Self.LookupConstructors(RD)) { 50760b57cec5SDimitry Andric // FIXME: In C++0x, a constructor template can be a default constructor. 50770b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 50780b57cec5SDimitry Andric continue; 50790b57cec5SDimitry Andric // UsingDecl itself is not a constructor 50800b57cec5SDimitry Andric if (isa<UsingDecl>(ND)) 50810b57cec5SDimitry Andric continue; 50820b57cec5SDimitry Andric auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 50830b57cec5SDimitry Andric if (Constructor->isDefaultConstructor()) { 50840b57cec5SDimitry Andric FoundConstructor = true; 50855ffd83dbSDimitry Andric auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 50860b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 50870b57cec5SDimitry Andric if (!CPT) 50880b57cec5SDimitry Andric return false; 50890b57cec5SDimitry Andric // FIXME: check whether evaluating default arguments can throw. 50900b57cec5SDimitry Andric // For now, we'll be conservative and assume that they can throw. 50910b57cec5SDimitry Andric if (!CPT->isNothrow() || CPT->getNumParams() > 0) 50920b57cec5SDimitry Andric return false; 50930b57cec5SDimitry Andric } 50940b57cec5SDimitry Andric } 50950b57cec5SDimitry Andric return FoundConstructor; 50960b57cec5SDimitry Andric } 50970b57cec5SDimitry Andric return false; 50980b57cec5SDimitry Andric case UTT_HasVirtualDestructor: 50990b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 51000b57cec5SDimitry Andric // If type is a class type with a virtual destructor ([class.dtor]) 51010b57cec5SDimitry Andric // then the trait is true, else it is false. 51020b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 51030b57cec5SDimitry Andric if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 51040b57cec5SDimitry Andric return Destructor->isVirtual(); 51050b57cec5SDimitry Andric return false; 51060b57cec5SDimitry Andric 51070b57cec5SDimitry Andric // These type trait expressions are modeled on the specifications for the 51080b57cec5SDimitry Andric // Embarcadero C++0x type trait functions: 51090b57cec5SDimitry Andric // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 51100b57cec5SDimitry Andric case UTT_IsCompleteType: 51110b57cec5SDimitry Andric // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 51120b57cec5SDimitry Andric // Returns True if and only if T is a complete type at the point of the 51130b57cec5SDimitry Andric // function call. 51140b57cec5SDimitry Andric return !T->isIncompleteType(); 51150b57cec5SDimitry Andric case UTT_HasUniqueObjectRepresentations: 51160b57cec5SDimitry Andric return C.hasUniqueObjectRepresentations(T); 51170b57cec5SDimitry Andric } 51180b57cec5SDimitry Andric } 51190b57cec5SDimitry Andric 51200b57cec5SDimitry Andric static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 51210b57cec5SDimitry Andric QualType RhsT, SourceLocation KeyLoc); 51220b57cec5SDimitry Andric 51230b57cec5SDimitry Andric static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 51240b57cec5SDimitry Andric ArrayRef<TypeSourceInfo *> Args, 51250b57cec5SDimitry Andric SourceLocation RParenLoc) { 51260b57cec5SDimitry Andric if (Kind <= UTT_Last) 51270b57cec5SDimitry Andric return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); 51280b57cec5SDimitry Andric 51290b57cec5SDimitry Andric // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible 51300b57cec5SDimitry Andric // traits to avoid duplication. 51310b57cec5SDimitry Andric if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) 51320b57cec5SDimitry Andric return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), 51330b57cec5SDimitry Andric Args[1]->getType(), RParenLoc); 51340b57cec5SDimitry Andric 51350b57cec5SDimitry Andric switch (Kind) { 51360b57cec5SDimitry Andric case clang::BTT_ReferenceBindsToTemporary: 51370b57cec5SDimitry Andric case clang::TT_IsConstructible: 51380b57cec5SDimitry Andric case clang::TT_IsNothrowConstructible: 51390b57cec5SDimitry Andric case clang::TT_IsTriviallyConstructible: { 51400b57cec5SDimitry Andric // C++11 [meta.unary.prop]: 51410b57cec5SDimitry Andric // is_trivially_constructible is defined as: 51420b57cec5SDimitry Andric // 51430b57cec5SDimitry Andric // is_constructible<T, Args...>::value is true and the variable 51440b57cec5SDimitry Andric // definition for is_constructible, as defined below, is known to call 51450b57cec5SDimitry Andric // no operation that is not trivial. 51460b57cec5SDimitry Andric // 51470b57cec5SDimitry Andric // The predicate condition for a template specialization 51480b57cec5SDimitry Andric // is_constructible<T, Args...> shall be satisfied if and only if the 51490b57cec5SDimitry Andric // following variable definition would be well-formed for some invented 51500b57cec5SDimitry Andric // variable t: 51510b57cec5SDimitry Andric // 51520b57cec5SDimitry Andric // T t(create<Args>()...); 51530b57cec5SDimitry Andric assert(!Args.empty()); 51540b57cec5SDimitry Andric 51550b57cec5SDimitry Andric // Precondition: T and all types in the parameter pack Args shall be 51560b57cec5SDimitry Andric // complete types, (possibly cv-qualified) void, or arrays of 51570b57cec5SDimitry Andric // unknown bound. 51580b57cec5SDimitry Andric for (const auto *TSI : Args) { 51590b57cec5SDimitry Andric QualType ArgTy = TSI->getType(); 51600b57cec5SDimitry Andric if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 51610b57cec5SDimitry Andric continue; 51620b57cec5SDimitry Andric 51630b57cec5SDimitry Andric if (S.RequireCompleteType(KWLoc, ArgTy, 51640b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 51650b57cec5SDimitry Andric return false; 51660b57cec5SDimitry Andric } 51670b57cec5SDimitry Andric 51680b57cec5SDimitry Andric // Make sure the first argument is not incomplete nor a function type. 51690b57cec5SDimitry Andric QualType T = Args[0]->getType(); 51700b57cec5SDimitry Andric if (T->isIncompleteType() || T->isFunctionType()) 51710b57cec5SDimitry Andric return false; 51720b57cec5SDimitry Andric 51730b57cec5SDimitry Andric // Make sure the first argument is not an abstract type. 51740b57cec5SDimitry Andric CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 51750b57cec5SDimitry Andric if (RD && RD->isAbstract()) 51760b57cec5SDimitry Andric return false; 51770b57cec5SDimitry Andric 51785ffd83dbSDimitry Andric llvm::BumpPtrAllocator OpaqueExprAllocator; 51790b57cec5SDimitry Andric SmallVector<Expr *, 2> ArgExprs; 51800b57cec5SDimitry Andric ArgExprs.reserve(Args.size() - 1); 51810b57cec5SDimitry Andric for (unsigned I = 1, N = Args.size(); I != N; ++I) { 51820b57cec5SDimitry Andric QualType ArgTy = Args[I]->getType(); 51830b57cec5SDimitry Andric if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 51840b57cec5SDimitry Andric ArgTy = S.Context.getRValueReferenceType(ArgTy); 51855ffd83dbSDimitry Andric ArgExprs.push_back( 51865ffd83dbSDimitry Andric new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) 51870b57cec5SDimitry Andric OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), 51880b57cec5SDimitry Andric ArgTy.getNonLValueExprType(S.Context), 51890b57cec5SDimitry Andric Expr::getValueKindForType(ArgTy))); 51900b57cec5SDimitry Andric } 51910b57cec5SDimitry Andric 51920b57cec5SDimitry Andric // Perform the initialization in an unevaluated context within a SFINAE 51930b57cec5SDimitry Andric // trap at translation unit scope. 51940b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 51950b57cec5SDimitry Andric S, Sema::ExpressionEvaluationContext::Unevaluated); 51960b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 51970b57cec5SDimitry Andric Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 51980b57cec5SDimitry Andric InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 51990b57cec5SDimitry Andric InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 52000b57cec5SDimitry Andric RParenLoc)); 52010b57cec5SDimitry Andric InitializationSequence Init(S, To, InitKind, ArgExprs); 52020b57cec5SDimitry Andric if (Init.Failed()) 52030b57cec5SDimitry Andric return false; 52040b57cec5SDimitry Andric 52050b57cec5SDimitry Andric ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 52060b57cec5SDimitry Andric if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 52070b57cec5SDimitry Andric return false; 52080b57cec5SDimitry Andric 52090b57cec5SDimitry Andric if (Kind == clang::TT_IsConstructible) 52100b57cec5SDimitry Andric return true; 52110b57cec5SDimitry Andric 52120b57cec5SDimitry Andric if (Kind == clang::BTT_ReferenceBindsToTemporary) { 52130b57cec5SDimitry Andric if (!T->isReferenceType()) 52140b57cec5SDimitry Andric return false; 52150b57cec5SDimitry Andric 52160b57cec5SDimitry Andric return !Init.isDirectReferenceBinding(); 52170b57cec5SDimitry Andric } 52180b57cec5SDimitry Andric 52190b57cec5SDimitry Andric if (Kind == clang::TT_IsNothrowConstructible) 52200b57cec5SDimitry Andric return S.canThrow(Result.get()) == CT_Cannot; 52210b57cec5SDimitry Andric 52220b57cec5SDimitry Andric if (Kind == clang::TT_IsTriviallyConstructible) { 52230b57cec5SDimitry Andric // Under Objective-C ARC and Weak, if the destination has non-trivial 52240b57cec5SDimitry Andric // Objective-C lifetime, this is a non-trivial construction. 52250b57cec5SDimitry Andric if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) 52260b57cec5SDimitry Andric return false; 52270b57cec5SDimitry Andric 52280b57cec5SDimitry Andric // The initialization succeeded; now make sure there are no non-trivial 52290b57cec5SDimitry Andric // calls. 52300b57cec5SDimitry Andric return !Result.get()->hasNonTrivialCall(S.Context); 52310b57cec5SDimitry Andric } 52320b57cec5SDimitry Andric 52330b57cec5SDimitry Andric llvm_unreachable("unhandled type trait"); 52340b57cec5SDimitry Andric return false; 52350b57cec5SDimitry Andric } 52360b57cec5SDimitry Andric default: llvm_unreachable("not a TT"); 52370b57cec5SDimitry Andric } 52380b57cec5SDimitry Andric 52390b57cec5SDimitry Andric return false; 52400b57cec5SDimitry Andric } 52410b57cec5SDimitry Andric 52420b57cec5SDimitry Andric ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 52430b57cec5SDimitry Andric ArrayRef<TypeSourceInfo *> Args, 52440b57cec5SDimitry Andric SourceLocation RParenLoc) { 52450b57cec5SDimitry Andric QualType ResultType = Context.getLogicalOperationType(); 52460b57cec5SDimitry Andric 52470b57cec5SDimitry Andric if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 52480b57cec5SDimitry Andric *this, Kind, KWLoc, Args[0]->getType())) 52490b57cec5SDimitry Andric return ExprError(); 52500b57cec5SDimitry Andric 52510b57cec5SDimitry Andric bool Dependent = false; 52520b57cec5SDimitry Andric for (unsigned I = 0, N = Args.size(); I != N; ++I) { 52530b57cec5SDimitry Andric if (Args[I]->getType()->isDependentType()) { 52540b57cec5SDimitry Andric Dependent = true; 52550b57cec5SDimitry Andric break; 52560b57cec5SDimitry Andric } 52570b57cec5SDimitry Andric } 52580b57cec5SDimitry Andric 52590b57cec5SDimitry Andric bool Result = false; 52600b57cec5SDimitry Andric if (!Dependent) 52610b57cec5SDimitry Andric Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 52620b57cec5SDimitry Andric 52630b57cec5SDimitry Andric return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, 52640b57cec5SDimitry Andric RParenLoc, Result); 52650b57cec5SDimitry Andric } 52660b57cec5SDimitry Andric 52670b57cec5SDimitry Andric ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 52680b57cec5SDimitry Andric ArrayRef<ParsedType> Args, 52690b57cec5SDimitry Andric SourceLocation RParenLoc) { 52700b57cec5SDimitry Andric SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 52710b57cec5SDimitry Andric ConvertedArgs.reserve(Args.size()); 52720b57cec5SDimitry Andric 52730b57cec5SDimitry Andric for (unsigned I = 0, N = Args.size(); I != N; ++I) { 52740b57cec5SDimitry Andric TypeSourceInfo *TInfo; 52750b57cec5SDimitry Andric QualType T = GetTypeFromParser(Args[I], &TInfo); 52760b57cec5SDimitry Andric if (!TInfo) 52770b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 52780b57cec5SDimitry Andric 52790b57cec5SDimitry Andric ConvertedArgs.push_back(TInfo); 52800b57cec5SDimitry Andric } 52810b57cec5SDimitry Andric 52820b57cec5SDimitry Andric return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 52830b57cec5SDimitry Andric } 52840b57cec5SDimitry Andric 52850b57cec5SDimitry Andric static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 52860b57cec5SDimitry Andric QualType RhsT, SourceLocation KeyLoc) { 52870b57cec5SDimitry Andric assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 52880b57cec5SDimitry Andric "Cannot evaluate traits of dependent types"); 52890b57cec5SDimitry Andric 52900b57cec5SDimitry Andric switch(BTT) { 52910b57cec5SDimitry Andric case BTT_IsBaseOf: { 52920b57cec5SDimitry Andric // C++0x [meta.rel]p2 52930b57cec5SDimitry Andric // Base is a base class of Derived without regard to cv-qualifiers or 52940b57cec5SDimitry Andric // Base and Derived are not unions and name the same class type without 52950b57cec5SDimitry Andric // regard to cv-qualifiers. 52960b57cec5SDimitry Andric 52970b57cec5SDimitry Andric const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 52980b57cec5SDimitry Andric const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 52990b57cec5SDimitry Andric if (!rhsRecord || !lhsRecord) { 53000b57cec5SDimitry Andric const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); 53010b57cec5SDimitry Andric const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); 53020b57cec5SDimitry Andric if (!LHSObjTy || !RHSObjTy) 53030b57cec5SDimitry Andric return false; 53040b57cec5SDimitry Andric 53050b57cec5SDimitry Andric ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); 53060b57cec5SDimitry Andric ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); 53070b57cec5SDimitry Andric if (!BaseInterface || !DerivedInterface) 53080b57cec5SDimitry Andric return false; 53090b57cec5SDimitry Andric 53100b57cec5SDimitry Andric if (Self.RequireCompleteType( 53110b57cec5SDimitry Andric KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) 53120b57cec5SDimitry Andric return false; 53130b57cec5SDimitry Andric 53140b57cec5SDimitry Andric return BaseInterface->isSuperClassOf(DerivedInterface); 53150b57cec5SDimitry Andric } 53160b57cec5SDimitry Andric 53170b57cec5SDimitry Andric assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 53180b57cec5SDimitry Andric == (lhsRecord == rhsRecord)); 53190b57cec5SDimitry Andric 53200b57cec5SDimitry Andric // Unions are never base classes, and never have base classes. 53210b57cec5SDimitry Andric // It doesn't matter if they are complete or not. See PR#41843 53220b57cec5SDimitry Andric if (lhsRecord && lhsRecord->getDecl()->isUnion()) 53230b57cec5SDimitry Andric return false; 53240b57cec5SDimitry Andric if (rhsRecord && rhsRecord->getDecl()->isUnion()) 53250b57cec5SDimitry Andric return false; 53260b57cec5SDimitry Andric 53270b57cec5SDimitry Andric if (lhsRecord == rhsRecord) 53280b57cec5SDimitry Andric return true; 53290b57cec5SDimitry Andric 53300b57cec5SDimitry Andric // C++0x [meta.rel]p2: 53310b57cec5SDimitry Andric // If Base and Derived are class types and are different types 53320b57cec5SDimitry Andric // (ignoring possible cv-qualifiers) then Derived shall be a 53330b57cec5SDimitry Andric // complete type. 53340b57cec5SDimitry Andric if (Self.RequireCompleteType(KeyLoc, RhsT, 53350b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 53360b57cec5SDimitry Andric return false; 53370b57cec5SDimitry Andric 53380b57cec5SDimitry Andric return cast<CXXRecordDecl>(rhsRecord->getDecl()) 53390b57cec5SDimitry Andric ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 53400b57cec5SDimitry Andric } 53410b57cec5SDimitry Andric case BTT_IsSame: 53420b57cec5SDimitry Andric return Self.Context.hasSameType(LhsT, RhsT); 53430b57cec5SDimitry Andric case BTT_TypeCompatible: { 53440b57cec5SDimitry Andric // GCC ignores cv-qualifiers on arrays for this builtin. 53450b57cec5SDimitry Andric Qualifiers LhsQuals, RhsQuals; 53460b57cec5SDimitry Andric QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); 53470b57cec5SDimitry Andric QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); 53480b57cec5SDimitry Andric return Self.Context.typesAreCompatible(Lhs, Rhs); 53490b57cec5SDimitry Andric } 53500b57cec5SDimitry Andric case BTT_IsConvertible: 53510b57cec5SDimitry Andric case BTT_IsConvertibleTo: { 53520b57cec5SDimitry Andric // C++0x [meta.rel]p4: 53530b57cec5SDimitry Andric // Given the following function prototype: 53540b57cec5SDimitry Andric // 53550b57cec5SDimitry Andric // template <class T> 53560b57cec5SDimitry Andric // typename add_rvalue_reference<T>::type create(); 53570b57cec5SDimitry Andric // 53580b57cec5SDimitry Andric // the predicate condition for a template specialization 53590b57cec5SDimitry Andric // is_convertible<From, To> shall be satisfied if and only if 53600b57cec5SDimitry Andric // the return expression in the following code would be 53610b57cec5SDimitry Andric // well-formed, including any implicit conversions to the return 53620b57cec5SDimitry Andric // type of the function: 53630b57cec5SDimitry Andric // 53640b57cec5SDimitry Andric // To test() { 53650b57cec5SDimitry Andric // return create<From>(); 53660b57cec5SDimitry Andric // } 53670b57cec5SDimitry Andric // 53680b57cec5SDimitry Andric // Access checking is performed as if in a context unrelated to To and 53690b57cec5SDimitry Andric // From. Only the validity of the immediate context of the expression 53700b57cec5SDimitry Andric // of the return-statement (including conversions to the return type) 53710b57cec5SDimitry Andric // is considered. 53720b57cec5SDimitry Andric // 53730b57cec5SDimitry Andric // We model the initialization as a copy-initialization of a temporary 53740b57cec5SDimitry Andric // of the appropriate type, which for this expression is identical to the 53750b57cec5SDimitry Andric // return statement (since NRVO doesn't apply). 53760b57cec5SDimitry Andric 53770b57cec5SDimitry Andric // Functions aren't allowed to return function or array types. 53780b57cec5SDimitry Andric if (RhsT->isFunctionType() || RhsT->isArrayType()) 53790b57cec5SDimitry Andric return false; 53800b57cec5SDimitry Andric 53810b57cec5SDimitry Andric // A return statement in a void function must have void type. 53820b57cec5SDimitry Andric if (RhsT->isVoidType()) 53830b57cec5SDimitry Andric return LhsT->isVoidType(); 53840b57cec5SDimitry Andric 53850b57cec5SDimitry Andric // A function definition requires a complete, non-abstract return type. 53860b57cec5SDimitry Andric if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) 53870b57cec5SDimitry Andric return false; 53880b57cec5SDimitry Andric 53890b57cec5SDimitry Andric // Compute the result of add_rvalue_reference. 53900b57cec5SDimitry Andric if (LhsT->isObjectType() || LhsT->isFunctionType()) 53910b57cec5SDimitry Andric LhsT = Self.Context.getRValueReferenceType(LhsT); 53920b57cec5SDimitry Andric 53930b57cec5SDimitry Andric // Build a fake source and destination for initialization. 53940b57cec5SDimitry Andric InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 53950b57cec5SDimitry Andric OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 53960b57cec5SDimitry Andric Expr::getValueKindForType(LhsT)); 53970b57cec5SDimitry Andric Expr *FromPtr = &From; 53980b57cec5SDimitry Andric InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 53990b57cec5SDimitry Andric SourceLocation())); 54000b57cec5SDimitry Andric 54010b57cec5SDimitry Andric // Perform the initialization in an unevaluated context within a SFINAE 54020b57cec5SDimitry Andric // trap at translation unit scope. 54030b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 54040b57cec5SDimitry Andric Self, Sema::ExpressionEvaluationContext::Unevaluated); 54050b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 54060b57cec5SDimitry Andric Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 54070b57cec5SDimitry Andric InitializationSequence Init(Self, To, Kind, FromPtr); 54080b57cec5SDimitry Andric if (Init.Failed()) 54090b57cec5SDimitry Andric return false; 54100b57cec5SDimitry Andric 54110b57cec5SDimitry Andric ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 54120b57cec5SDimitry Andric return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 54130b57cec5SDimitry Andric } 54140b57cec5SDimitry Andric 54150b57cec5SDimitry Andric case BTT_IsAssignable: 54160b57cec5SDimitry Andric case BTT_IsNothrowAssignable: 54170b57cec5SDimitry Andric case BTT_IsTriviallyAssignable: { 54180b57cec5SDimitry Andric // C++11 [meta.unary.prop]p3: 54190b57cec5SDimitry Andric // is_trivially_assignable is defined as: 54200b57cec5SDimitry Andric // is_assignable<T, U>::value is true and the assignment, as defined by 54210b57cec5SDimitry Andric // is_assignable, is known to call no operation that is not trivial 54220b57cec5SDimitry Andric // 54230b57cec5SDimitry Andric // is_assignable is defined as: 54240b57cec5SDimitry Andric // The expression declval<T>() = declval<U>() is well-formed when 54250b57cec5SDimitry Andric // treated as an unevaluated operand (Clause 5). 54260b57cec5SDimitry Andric // 54270b57cec5SDimitry Andric // For both, T and U shall be complete types, (possibly cv-qualified) 54280b57cec5SDimitry Andric // void, or arrays of unknown bound. 54290b57cec5SDimitry Andric if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 54300b57cec5SDimitry Andric Self.RequireCompleteType(KeyLoc, LhsT, 54310b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 54320b57cec5SDimitry Andric return false; 54330b57cec5SDimitry Andric if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 54340b57cec5SDimitry Andric Self.RequireCompleteType(KeyLoc, RhsT, 54350b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 54360b57cec5SDimitry Andric return false; 54370b57cec5SDimitry Andric 54380b57cec5SDimitry Andric // cv void is never assignable. 54390b57cec5SDimitry Andric if (LhsT->isVoidType() || RhsT->isVoidType()) 54400b57cec5SDimitry Andric return false; 54410b57cec5SDimitry Andric 54420b57cec5SDimitry Andric // Build expressions that emulate the effect of declval<T>() and 54430b57cec5SDimitry Andric // declval<U>(). 54440b57cec5SDimitry Andric if (LhsT->isObjectType() || LhsT->isFunctionType()) 54450b57cec5SDimitry Andric LhsT = Self.Context.getRValueReferenceType(LhsT); 54460b57cec5SDimitry Andric if (RhsT->isObjectType() || RhsT->isFunctionType()) 54470b57cec5SDimitry Andric RhsT = Self.Context.getRValueReferenceType(RhsT); 54480b57cec5SDimitry Andric OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 54490b57cec5SDimitry Andric Expr::getValueKindForType(LhsT)); 54500b57cec5SDimitry Andric OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 54510b57cec5SDimitry Andric Expr::getValueKindForType(RhsT)); 54520b57cec5SDimitry Andric 54530b57cec5SDimitry Andric // Attempt the assignment in an unevaluated context within a SFINAE 54540b57cec5SDimitry Andric // trap at translation unit scope. 54550b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 54560b57cec5SDimitry Andric Self, Sema::ExpressionEvaluationContext::Unevaluated); 54570b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 54580b57cec5SDimitry Andric Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 54590b57cec5SDimitry Andric ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 54600b57cec5SDimitry Andric &Rhs); 5461a7dea167SDimitry Andric if (Result.isInvalid()) 5462a7dea167SDimitry Andric return false; 5463a7dea167SDimitry Andric 5464a7dea167SDimitry Andric // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. 5465a7dea167SDimitry Andric Self.CheckUnusedVolatileAssignment(Result.get()); 5466a7dea167SDimitry Andric 5467a7dea167SDimitry Andric if (SFINAE.hasErrorOccurred()) 54680b57cec5SDimitry Andric return false; 54690b57cec5SDimitry Andric 54700b57cec5SDimitry Andric if (BTT == BTT_IsAssignable) 54710b57cec5SDimitry Andric return true; 54720b57cec5SDimitry Andric 54730b57cec5SDimitry Andric if (BTT == BTT_IsNothrowAssignable) 54740b57cec5SDimitry Andric return Self.canThrow(Result.get()) == CT_Cannot; 54750b57cec5SDimitry Andric 54760b57cec5SDimitry Andric if (BTT == BTT_IsTriviallyAssignable) { 54770b57cec5SDimitry Andric // Under Objective-C ARC and Weak, if the destination has non-trivial 54780b57cec5SDimitry Andric // Objective-C lifetime, this is a non-trivial assignment. 54790b57cec5SDimitry Andric if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) 54800b57cec5SDimitry Andric return false; 54810b57cec5SDimitry Andric 54820b57cec5SDimitry Andric return !Result.get()->hasNonTrivialCall(Self.Context); 54830b57cec5SDimitry Andric } 54840b57cec5SDimitry Andric 54850b57cec5SDimitry Andric llvm_unreachable("unhandled type trait"); 54860b57cec5SDimitry Andric return false; 54870b57cec5SDimitry Andric } 54880b57cec5SDimitry Andric default: llvm_unreachable("not a BTT"); 54890b57cec5SDimitry Andric } 54900b57cec5SDimitry Andric llvm_unreachable("Unknown type trait or not implemented"); 54910b57cec5SDimitry Andric } 54920b57cec5SDimitry Andric 54930b57cec5SDimitry Andric ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 54940b57cec5SDimitry Andric SourceLocation KWLoc, 54950b57cec5SDimitry Andric ParsedType Ty, 54960b57cec5SDimitry Andric Expr* DimExpr, 54970b57cec5SDimitry Andric SourceLocation RParen) { 54980b57cec5SDimitry Andric TypeSourceInfo *TSInfo; 54990b57cec5SDimitry Andric QualType T = GetTypeFromParser(Ty, &TSInfo); 55000b57cec5SDimitry Andric if (!TSInfo) 55010b57cec5SDimitry Andric TSInfo = Context.getTrivialTypeSourceInfo(T); 55020b57cec5SDimitry Andric 55030b57cec5SDimitry Andric return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 55040b57cec5SDimitry Andric } 55050b57cec5SDimitry Andric 55060b57cec5SDimitry Andric static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 55070b57cec5SDimitry Andric QualType T, Expr *DimExpr, 55080b57cec5SDimitry Andric SourceLocation KeyLoc) { 55090b57cec5SDimitry Andric assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 55100b57cec5SDimitry Andric 55110b57cec5SDimitry Andric switch(ATT) { 55120b57cec5SDimitry Andric case ATT_ArrayRank: 55130b57cec5SDimitry Andric if (T->isArrayType()) { 55140b57cec5SDimitry Andric unsigned Dim = 0; 55150b57cec5SDimitry Andric while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 55160b57cec5SDimitry Andric ++Dim; 55170b57cec5SDimitry Andric T = AT->getElementType(); 55180b57cec5SDimitry Andric } 55190b57cec5SDimitry Andric return Dim; 55200b57cec5SDimitry Andric } 55210b57cec5SDimitry Andric return 0; 55220b57cec5SDimitry Andric 55230b57cec5SDimitry Andric case ATT_ArrayExtent: { 55240b57cec5SDimitry Andric llvm::APSInt Value; 55250b57cec5SDimitry Andric uint64_t Dim; 5526e8d8bef9SDimitry Andric if (Self.VerifyIntegerConstantExpression( 5527e8d8bef9SDimitry Andric DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) 5528e8d8bef9SDimitry Andric .isInvalid()) 55290b57cec5SDimitry Andric return 0; 55300b57cec5SDimitry Andric if (Value.isSigned() && Value.isNegative()) { 55310b57cec5SDimitry Andric Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 55320b57cec5SDimitry Andric << DimExpr->getSourceRange(); 55330b57cec5SDimitry Andric return 0; 55340b57cec5SDimitry Andric } 55350b57cec5SDimitry Andric Dim = Value.getLimitedValue(); 55360b57cec5SDimitry Andric 55370b57cec5SDimitry Andric if (T->isArrayType()) { 55380b57cec5SDimitry Andric unsigned D = 0; 55390b57cec5SDimitry Andric bool Matched = false; 55400b57cec5SDimitry Andric while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 55410b57cec5SDimitry Andric if (Dim == D) { 55420b57cec5SDimitry Andric Matched = true; 55430b57cec5SDimitry Andric break; 55440b57cec5SDimitry Andric } 55450b57cec5SDimitry Andric ++D; 55460b57cec5SDimitry Andric T = AT->getElementType(); 55470b57cec5SDimitry Andric } 55480b57cec5SDimitry Andric 55490b57cec5SDimitry Andric if (Matched && T->isArrayType()) { 55500b57cec5SDimitry Andric if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 55510b57cec5SDimitry Andric return CAT->getSize().getLimitedValue(); 55520b57cec5SDimitry Andric } 55530b57cec5SDimitry Andric } 55540b57cec5SDimitry Andric return 0; 55550b57cec5SDimitry Andric } 55560b57cec5SDimitry Andric } 55570b57cec5SDimitry Andric llvm_unreachable("Unknown type trait or not implemented"); 55580b57cec5SDimitry Andric } 55590b57cec5SDimitry Andric 55600b57cec5SDimitry Andric ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 55610b57cec5SDimitry Andric SourceLocation KWLoc, 55620b57cec5SDimitry Andric TypeSourceInfo *TSInfo, 55630b57cec5SDimitry Andric Expr* DimExpr, 55640b57cec5SDimitry Andric SourceLocation RParen) { 55650b57cec5SDimitry Andric QualType T = TSInfo->getType(); 55660b57cec5SDimitry Andric 55670b57cec5SDimitry Andric // FIXME: This should likely be tracked as an APInt to remove any host 55680b57cec5SDimitry Andric // assumptions about the width of size_t on the target. 55690b57cec5SDimitry Andric uint64_t Value = 0; 55700b57cec5SDimitry Andric if (!T->isDependentType()) 55710b57cec5SDimitry Andric Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 55720b57cec5SDimitry Andric 55730b57cec5SDimitry Andric // While the specification for these traits from the Embarcadero C++ 55740b57cec5SDimitry Andric // compiler's documentation says the return type is 'unsigned int', Clang 55750b57cec5SDimitry Andric // returns 'size_t'. On Windows, the primary platform for the Embarcadero 55760b57cec5SDimitry Andric // compiler, there is no difference. On several other platforms this is an 55770b57cec5SDimitry Andric // important distinction. 55780b57cec5SDimitry Andric return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 55790b57cec5SDimitry Andric RParen, Context.getSizeType()); 55800b57cec5SDimitry Andric } 55810b57cec5SDimitry Andric 55820b57cec5SDimitry Andric ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 55830b57cec5SDimitry Andric SourceLocation KWLoc, 55840b57cec5SDimitry Andric Expr *Queried, 55850b57cec5SDimitry Andric SourceLocation RParen) { 55860b57cec5SDimitry Andric // If error parsing the expression, ignore. 55870b57cec5SDimitry Andric if (!Queried) 55880b57cec5SDimitry Andric return ExprError(); 55890b57cec5SDimitry Andric 55900b57cec5SDimitry Andric ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 55910b57cec5SDimitry Andric 55920b57cec5SDimitry Andric return Result; 55930b57cec5SDimitry Andric } 55940b57cec5SDimitry Andric 55950b57cec5SDimitry Andric static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 55960b57cec5SDimitry Andric switch (ET) { 55970b57cec5SDimitry Andric case ET_IsLValueExpr: return E->isLValue(); 55980b57cec5SDimitry Andric case ET_IsRValueExpr: return E->isRValue(); 55990b57cec5SDimitry Andric } 56000b57cec5SDimitry Andric llvm_unreachable("Expression trait not covered by switch"); 56010b57cec5SDimitry Andric } 56020b57cec5SDimitry Andric 56030b57cec5SDimitry Andric ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 56040b57cec5SDimitry Andric SourceLocation KWLoc, 56050b57cec5SDimitry Andric Expr *Queried, 56060b57cec5SDimitry Andric SourceLocation RParen) { 56070b57cec5SDimitry Andric if (Queried->isTypeDependent()) { 56080b57cec5SDimitry Andric // Delay type-checking for type-dependent expressions. 56090b57cec5SDimitry Andric } else if (Queried->getType()->isPlaceholderType()) { 56100b57cec5SDimitry Andric ExprResult PE = CheckPlaceholderExpr(Queried); 56110b57cec5SDimitry Andric if (PE.isInvalid()) return ExprError(); 56120b57cec5SDimitry Andric return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 56130b57cec5SDimitry Andric } 56140b57cec5SDimitry Andric 56150b57cec5SDimitry Andric bool Value = EvaluateExpressionTrait(ET, Queried); 56160b57cec5SDimitry Andric 56170b57cec5SDimitry Andric return new (Context) 56180b57cec5SDimitry Andric ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 56190b57cec5SDimitry Andric } 56200b57cec5SDimitry Andric 56210b57cec5SDimitry Andric QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 56220b57cec5SDimitry Andric ExprValueKind &VK, 56230b57cec5SDimitry Andric SourceLocation Loc, 56240b57cec5SDimitry Andric bool isIndirect) { 56250b57cec5SDimitry Andric assert(!LHS.get()->getType()->isPlaceholderType() && 56260b57cec5SDimitry Andric !RHS.get()->getType()->isPlaceholderType() && 56270b57cec5SDimitry Andric "placeholders should have been weeded out by now"); 56280b57cec5SDimitry Andric 56290b57cec5SDimitry Andric // The LHS undergoes lvalue conversions if this is ->*, and undergoes the 56300b57cec5SDimitry Andric // temporary materialization conversion otherwise. 56310b57cec5SDimitry Andric if (isIndirect) 56320b57cec5SDimitry Andric LHS = DefaultLvalueConversion(LHS.get()); 56330b57cec5SDimitry Andric else if (LHS.get()->isRValue()) 56340b57cec5SDimitry Andric LHS = TemporaryMaterializationConversion(LHS.get()); 56350b57cec5SDimitry Andric if (LHS.isInvalid()) 56360b57cec5SDimitry Andric return QualType(); 56370b57cec5SDimitry Andric 56380b57cec5SDimitry Andric // The RHS always undergoes lvalue conversions. 56390b57cec5SDimitry Andric RHS = DefaultLvalueConversion(RHS.get()); 56400b57cec5SDimitry Andric if (RHS.isInvalid()) return QualType(); 56410b57cec5SDimitry Andric 56420b57cec5SDimitry Andric const char *OpSpelling = isIndirect ? "->*" : ".*"; 56430b57cec5SDimitry Andric // C++ 5.5p2 56440b57cec5SDimitry Andric // The binary operator .* [p3: ->*] binds its second operand, which shall 56450b57cec5SDimitry Andric // be of type "pointer to member of T" (where T is a completely-defined 56460b57cec5SDimitry Andric // class type) [...] 56470b57cec5SDimitry Andric QualType RHSType = RHS.get()->getType(); 56480b57cec5SDimitry Andric const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 56490b57cec5SDimitry Andric if (!MemPtr) { 56500b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_rhs) 56510b57cec5SDimitry Andric << OpSpelling << RHSType << RHS.get()->getSourceRange(); 56520b57cec5SDimitry Andric return QualType(); 56530b57cec5SDimitry Andric } 56540b57cec5SDimitry Andric 56550b57cec5SDimitry Andric QualType Class(MemPtr->getClass(), 0); 56560b57cec5SDimitry Andric 56570b57cec5SDimitry Andric // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 56580b57cec5SDimitry Andric // member pointer points must be completely-defined. However, there is no 56590b57cec5SDimitry Andric // reason for this semantic distinction, and the rule is not enforced by 56600b57cec5SDimitry Andric // other compilers. Therefore, we do not check this property, as it is 56610b57cec5SDimitry Andric // likely to be considered a defect. 56620b57cec5SDimitry Andric 56630b57cec5SDimitry Andric // C++ 5.5p2 56640b57cec5SDimitry Andric // [...] to its first operand, which shall be of class T or of a class of 56650b57cec5SDimitry Andric // which T is an unambiguous and accessible base class. [p3: a pointer to 56660b57cec5SDimitry Andric // such a class] 56670b57cec5SDimitry Andric QualType LHSType = LHS.get()->getType(); 56680b57cec5SDimitry Andric if (isIndirect) { 56690b57cec5SDimitry Andric if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 56700b57cec5SDimitry Andric LHSType = Ptr->getPointeeType(); 56710b57cec5SDimitry Andric else { 56720b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_lhs) 56730b57cec5SDimitry Andric << OpSpelling << 1 << LHSType 56740b57cec5SDimitry Andric << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 56750b57cec5SDimitry Andric return QualType(); 56760b57cec5SDimitry Andric } 56770b57cec5SDimitry Andric } 56780b57cec5SDimitry Andric 56790b57cec5SDimitry Andric if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 56800b57cec5SDimitry Andric // If we want to check the hierarchy, we need a complete type. 56810b57cec5SDimitry Andric if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 56820b57cec5SDimitry Andric OpSpelling, (int)isIndirect)) { 56830b57cec5SDimitry Andric return QualType(); 56840b57cec5SDimitry Andric } 56850b57cec5SDimitry Andric 56860b57cec5SDimitry Andric if (!IsDerivedFrom(Loc, LHSType, Class)) { 56870b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 56880b57cec5SDimitry Andric << (int)isIndirect << LHS.get()->getType(); 56890b57cec5SDimitry Andric return QualType(); 56900b57cec5SDimitry Andric } 56910b57cec5SDimitry Andric 56920b57cec5SDimitry Andric CXXCastPath BasePath; 56930b57cec5SDimitry Andric if (CheckDerivedToBaseConversion( 56940b57cec5SDimitry Andric LHSType, Class, Loc, 56950b57cec5SDimitry Andric SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), 56960b57cec5SDimitry Andric &BasePath)) 56970b57cec5SDimitry Andric return QualType(); 56980b57cec5SDimitry Andric 56990b57cec5SDimitry Andric // Cast LHS to type of use. 57000b57cec5SDimitry Andric QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); 57010b57cec5SDimitry Andric if (isIndirect) 57020b57cec5SDimitry Andric UseType = Context.getPointerType(UseType); 57030b57cec5SDimitry Andric ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); 57040b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 57050b57cec5SDimitry Andric &BasePath); 57060b57cec5SDimitry Andric } 57070b57cec5SDimitry Andric 57080b57cec5SDimitry Andric if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 57090b57cec5SDimitry Andric // Diagnose use of pointer-to-member type which when used as 57100b57cec5SDimitry Andric // the functional cast in a pointer-to-member expression. 57110b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 57120b57cec5SDimitry Andric return QualType(); 57130b57cec5SDimitry Andric } 57140b57cec5SDimitry Andric 57150b57cec5SDimitry Andric // C++ 5.5p2 57160b57cec5SDimitry Andric // The result is an object or a function of the type specified by the 57170b57cec5SDimitry Andric // second operand. 57180b57cec5SDimitry Andric // The cv qualifiers are the union of those in the pointer and the left side, 57190b57cec5SDimitry Andric // in accordance with 5.5p5 and 5.2.5. 57200b57cec5SDimitry Andric QualType Result = MemPtr->getPointeeType(); 57210b57cec5SDimitry Andric Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 57220b57cec5SDimitry Andric 57230b57cec5SDimitry Andric // C++0x [expr.mptr.oper]p6: 57240b57cec5SDimitry Andric // In a .* expression whose object expression is an rvalue, the program is 57250b57cec5SDimitry Andric // ill-formed if the second operand is a pointer to member function with 57260b57cec5SDimitry Andric // ref-qualifier &. In a ->* expression or in a .* expression whose object 57270b57cec5SDimitry Andric // expression is an lvalue, the program is ill-formed if the second operand 57280b57cec5SDimitry Andric // is a pointer to member function with ref-qualifier &&. 57290b57cec5SDimitry Andric if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 57300b57cec5SDimitry Andric switch (Proto->getRefQualifier()) { 57310b57cec5SDimitry Andric case RQ_None: 57320b57cec5SDimitry Andric // Do nothing 57330b57cec5SDimitry Andric break; 57340b57cec5SDimitry Andric 57350b57cec5SDimitry Andric case RQ_LValue: 57360b57cec5SDimitry Andric if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { 57370b57cec5SDimitry Andric // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq 57380b57cec5SDimitry Andric // is (exactly) 'const'. 57390b57cec5SDimitry Andric if (Proto->isConst() && !Proto->isVolatile()) 57405ffd83dbSDimitry Andric Diag(Loc, getLangOpts().CPlusPlus20 57410b57cec5SDimitry Andric ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue 57420b57cec5SDimitry Andric : diag::ext_pointer_to_const_ref_member_on_rvalue); 57430b57cec5SDimitry Andric else 57440b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 57450b57cec5SDimitry Andric << RHSType << 1 << LHS.get()->getSourceRange(); 57460b57cec5SDimitry Andric } 57470b57cec5SDimitry Andric break; 57480b57cec5SDimitry Andric 57490b57cec5SDimitry Andric case RQ_RValue: 57500b57cec5SDimitry Andric if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 57510b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 57520b57cec5SDimitry Andric << RHSType << 0 << LHS.get()->getSourceRange(); 57530b57cec5SDimitry Andric break; 57540b57cec5SDimitry Andric } 57550b57cec5SDimitry Andric } 57560b57cec5SDimitry Andric 57570b57cec5SDimitry Andric // C++ [expr.mptr.oper]p6: 57580b57cec5SDimitry Andric // The result of a .* expression whose second operand is a pointer 57590b57cec5SDimitry Andric // to a data member is of the same value category as its 57600b57cec5SDimitry Andric // first operand. The result of a .* expression whose second 57610b57cec5SDimitry Andric // operand is a pointer to a member function is a prvalue. The 57620b57cec5SDimitry Andric // result of an ->* expression is an lvalue if its second operand 57630b57cec5SDimitry Andric // is a pointer to data member and a prvalue otherwise. 57640b57cec5SDimitry Andric if (Result->isFunctionType()) { 57650b57cec5SDimitry Andric VK = VK_RValue; 57660b57cec5SDimitry Andric return Context.BoundMemberTy; 57670b57cec5SDimitry Andric } else if (isIndirect) { 57680b57cec5SDimitry Andric VK = VK_LValue; 57690b57cec5SDimitry Andric } else { 57700b57cec5SDimitry Andric VK = LHS.get()->getValueKind(); 57710b57cec5SDimitry Andric } 57720b57cec5SDimitry Andric 57730b57cec5SDimitry Andric return Result; 57740b57cec5SDimitry Andric } 57750b57cec5SDimitry Andric 57760b57cec5SDimitry Andric /// Try to convert a type to another according to C++11 5.16p3. 57770b57cec5SDimitry Andric /// 57780b57cec5SDimitry Andric /// This is part of the parameter validation for the ? operator. If either 57790b57cec5SDimitry Andric /// value operand is a class type, the two operands are attempted to be 57800b57cec5SDimitry Andric /// converted to each other. This function does the conversion in one direction. 57810b57cec5SDimitry Andric /// It returns true if the program is ill-formed and has already been diagnosed 57820b57cec5SDimitry Andric /// as such. 57830b57cec5SDimitry Andric static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 57840b57cec5SDimitry Andric SourceLocation QuestionLoc, 57850b57cec5SDimitry Andric bool &HaveConversion, 57860b57cec5SDimitry Andric QualType &ToType) { 57870b57cec5SDimitry Andric HaveConversion = false; 57880b57cec5SDimitry Andric ToType = To->getType(); 57890b57cec5SDimitry Andric 57900b57cec5SDimitry Andric InitializationKind Kind = 57910b57cec5SDimitry Andric InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); 57920b57cec5SDimitry Andric // C++11 5.16p3 57930b57cec5SDimitry Andric // The process for determining whether an operand expression E1 of type T1 57940b57cec5SDimitry Andric // can be converted to match an operand expression E2 of type T2 is defined 57950b57cec5SDimitry Andric // as follows: 57960b57cec5SDimitry Andric // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be 57970b57cec5SDimitry Andric // implicitly converted to type "lvalue reference to T2", subject to the 57980b57cec5SDimitry Andric // constraint that in the conversion the reference must bind directly to 57990b57cec5SDimitry Andric // an lvalue. 58000b57cec5SDimitry Andric // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be 58010b57cec5SDimitry Andric // implicitly converted to the type "rvalue reference to R2", subject to 58020b57cec5SDimitry Andric // the constraint that the reference must bind directly. 58030b57cec5SDimitry Andric if (To->isLValue() || To->isXValue()) { 58040b57cec5SDimitry Andric QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType) 58050b57cec5SDimitry Andric : Self.Context.getRValueReferenceType(ToType); 58060b57cec5SDimitry Andric 58070b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 58080b57cec5SDimitry Andric 58090b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 58100b57cec5SDimitry Andric if (InitSeq.isDirectReferenceBinding()) { 58110b57cec5SDimitry Andric ToType = T; 58120b57cec5SDimitry Andric HaveConversion = true; 58130b57cec5SDimitry Andric return false; 58140b57cec5SDimitry Andric } 58150b57cec5SDimitry Andric 58160b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 58170b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 58180b57cec5SDimitry Andric } 58190b57cec5SDimitry Andric 58200b57cec5SDimitry Andric // -- If E2 is an rvalue, or if the conversion above cannot be done: 58210b57cec5SDimitry Andric // -- if E1 and E2 have class type, and the underlying class types are 58220b57cec5SDimitry Andric // the same or one is a base class of the other: 58230b57cec5SDimitry Andric QualType FTy = From->getType(); 58240b57cec5SDimitry Andric QualType TTy = To->getType(); 58250b57cec5SDimitry Andric const RecordType *FRec = FTy->getAs<RecordType>(); 58260b57cec5SDimitry Andric const RecordType *TRec = TTy->getAs<RecordType>(); 58270b57cec5SDimitry Andric bool FDerivedFromT = FRec && TRec && FRec != TRec && 58280b57cec5SDimitry Andric Self.IsDerivedFrom(QuestionLoc, FTy, TTy); 58290b57cec5SDimitry Andric if (FRec && TRec && (FRec == TRec || FDerivedFromT || 58300b57cec5SDimitry Andric Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { 58310b57cec5SDimitry Andric // E1 can be converted to match E2 if the class of T2 is the 58320b57cec5SDimitry Andric // same type as, or a base class of, the class of T1, and 58330b57cec5SDimitry Andric // [cv2 > cv1]. 58340b57cec5SDimitry Andric if (FRec == TRec || FDerivedFromT) { 58350b57cec5SDimitry Andric if (TTy.isAtLeastAsQualifiedAs(FTy)) { 58360b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 58370b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 58380b57cec5SDimitry Andric if (InitSeq) { 58390b57cec5SDimitry Andric HaveConversion = true; 58400b57cec5SDimitry Andric return false; 58410b57cec5SDimitry Andric } 58420b57cec5SDimitry Andric 58430b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 58440b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 58450b57cec5SDimitry Andric } 58460b57cec5SDimitry Andric } 58470b57cec5SDimitry Andric 58480b57cec5SDimitry Andric return false; 58490b57cec5SDimitry Andric } 58500b57cec5SDimitry Andric 58510b57cec5SDimitry Andric // -- Otherwise: E1 can be converted to match E2 if E1 can be 58520b57cec5SDimitry Andric // implicitly converted to the type that expression E2 would have 58530b57cec5SDimitry Andric // if E2 were converted to an rvalue (or the type it has, if E2 is 58540b57cec5SDimitry Andric // an rvalue). 58550b57cec5SDimitry Andric // 58560b57cec5SDimitry Andric // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 58570b57cec5SDimitry Andric // to the array-to-pointer or function-to-pointer conversions. 58580b57cec5SDimitry Andric TTy = TTy.getNonLValueExprType(Self.Context); 58590b57cec5SDimitry Andric 58600b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 58610b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 58620b57cec5SDimitry Andric HaveConversion = !InitSeq.Failed(); 58630b57cec5SDimitry Andric ToType = TTy; 58640b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 58650b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 58660b57cec5SDimitry Andric 58670b57cec5SDimitry Andric return false; 58680b57cec5SDimitry Andric } 58690b57cec5SDimitry Andric 58700b57cec5SDimitry Andric /// Try to find a common type for two according to C++0x 5.16p5. 58710b57cec5SDimitry Andric /// 58720b57cec5SDimitry Andric /// This is part of the parameter validation for the ? operator. If either 58730b57cec5SDimitry Andric /// value operand is a class type, overload resolution is used to find a 58740b57cec5SDimitry Andric /// conversion to a common type. 58750b57cec5SDimitry Andric static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 58760b57cec5SDimitry Andric SourceLocation QuestionLoc) { 58770b57cec5SDimitry Andric Expr *Args[2] = { LHS.get(), RHS.get() }; 58780b57cec5SDimitry Andric OverloadCandidateSet CandidateSet(QuestionLoc, 58790b57cec5SDimitry Andric OverloadCandidateSet::CSK_Operator); 58800b57cec5SDimitry Andric Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 58810b57cec5SDimitry Andric CandidateSet); 58820b57cec5SDimitry Andric 58830b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 58840b57cec5SDimitry Andric switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 58850b57cec5SDimitry Andric case OR_Success: { 58860b57cec5SDimitry Andric // We found a match. Perform the conversions on the arguments and move on. 58870b57cec5SDimitry Andric ExprResult LHSRes = Self.PerformImplicitConversion( 58880b57cec5SDimitry Andric LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], 58890b57cec5SDimitry Andric Sema::AA_Converting); 58900b57cec5SDimitry Andric if (LHSRes.isInvalid()) 58910b57cec5SDimitry Andric break; 58920b57cec5SDimitry Andric LHS = LHSRes; 58930b57cec5SDimitry Andric 58940b57cec5SDimitry Andric ExprResult RHSRes = Self.PerformImplicitConversion( 58950b57cec5SDimitry Andric RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], 58960b57cec5SDimitry Andric Sema::AA_Converting); 58970b57cec5SDimitry Andric if (RHSRes.isInvalid()) 58980b57cec5SDimitry Andric break; 58990b57cec5SDimitry Andric RHS = RHSRes; 59000b57cec5SDimitry Andric if (Best->Function) 59010b57cec5SDimitry Andric Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 59020b57cec5SDimitry Andric return false; 59030b57cec5SDimitry Andric } 59040b57cec5SDimitry Andric 59050b57cec5SDimitry Andric case OR_No_Viable_Function: 59060b57cec5SDimitry Andric 59070b57cec5SDimitry Andric // Emit a better diagnostic if one of the expressions is a null pointer 59080b57cec5SDimitry Andric // constant and the other is a pointer type. In this case, the user most 59090b57cec5SDimitry Andric // likely forgot to take the address of the other expression. 59100b57cec5SDimitry Andric if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 59110b57cec5SDimitry Andric return true; 59120b57cec5SDimitry Andric 59130b57cec5SDimitry Andric Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 59140b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 59150b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 59160b57cec5SDimitry Andric return true; 59170b57cec5SDimitry Andric 59180b57cec5SDimitry Andric case OR_Ambiguous: 59190b57cec5SDimitry Andric Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 59200b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 59210b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 59220b57cec5SDimitry Andric // FIXME: Print the possible common types by printing the return types of 59230b57cec5SDimitry Andric // the viable candidates. 59240b57cec5SDimitry Andric break; 59250b57cec5SDimitry Andric 59260b57cec5SDimitry Andric case OR_Deleted: 59270b57cec5SDimitry Andric llvm_unreachable("Conditional operator has only built-in overloads"); 59280b57cec5SDimitry Andric } 59290b57cec5SDimitry Andric return true; 59300b57cec5SDimitry Andric } 59310b57cec5SDimitry Andric 59320b57cec5SDimitry Andric /// Perform an "extended" implicit conversion as returned by 59330b57cec5SDimitry Andric /// TryClassUnification. 59340b57cec5SDimitry Andric static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 59350b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 59360b57cec5SDimitry Andric InitializationKind Kind = 59370b57cec5SDimitry Andric InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); 59380b57cec5SDimitry Andric Expr *Arg = E.get(); 59390b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, Arg); 59400b57cec5SDimitry Andric ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 59410b57cec5SDimitry Andric if (Result.isInvalid()) 59420b57cec5SDimitry Andric return true; 59430b57cec5SDimitry Andric 59440b57cec5SDimitry Andric E = Result; 59450b57cec5SDimitry Andric return false; 59460b57cec5SDimitry Andric } 59470b57cec5SDimitry Andric 5948480093f4SDimitry Andric // Check the condition operand of ?: to see if it is valid for the GCC 5949480093f4SDimitry Andric // extension. 5950480093f4SDimitry Andric static bool isValidVectorForConditionalCondition(ASTContext &Ctx, 5951480093f4SDimitry Andric QualType CondTy) { 5952480093f4SDimitry Andric if (!CondTy->isVectorType() || CondTy->isExtVectorType()) 5953480093f4SDimitry Andric return false; 5954480093f4SDimitry Andric const QualType EltTy = 5955480093f4SDimitry Andric cast<VectorType>(CondTy.getCanonicalType())->getElementType(); 5956480093f4SDimitry Andric 5957480093f4SDimitry Andric assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() && 5958480093f4SDimitry Andric "Vectors cant be boolean or enum types"); 5959480093f4SDimitry Andric return EltTy->isIntegralType(Ctx); 5960480093f4SDimitry Andric } 5961480093f4SDimitry Andric 5962480093f4SDimitry Andric QualType Sema::CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 5963480093f4SDimitry Andric ExprResult &RHS, 5964480093f4SDimitry Andric SourceLocation QuestionLoc) { 5965480093f4SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 5966480093f4SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 5967480093f4SDimitry Andric 5968480093f4SDimitry Andric QualType CondType = Cond.get()->getType(); 59695ffd83dbSDimitry Andric const auto *CondVT = CondType->castAs<VectorType>(); 5970480093f4SDimitry Andric QualType CondElementTy = CondVT->getElementType(); 5971480093f4SDimitry Andric unsigned CondElementCount = CondVT->getNumElements(); 5972480093f4SDimitry Andric QualType LHSType = LHS.get()->getType(); 5973480093f4SDimitry Andric const auto *LHSVT = LHSType->getAs<VectorType>(); 5974480093f4SDimitry Andric QualType RHSType = RHS.get()->getType(); 5975480093f4SDimitry Andric const auto *RHSVT = RHSType->getAs<VectorType>(); 5976480093f4SDimitry Andric 5977480093f4SDimitry Andric QualType ResultType; 5978480093f4SDimitry Andric 5979480093f4SDimitry Andric // FIXME: In the future we should define what the Extvector conditional 5980480093f4SDimitry Andric // operator looks like. 5981480093f4SDimitry Andric if (LHSVT && isa<ExtVectorType>(LHSVT)) { 5982480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 5983480093f4SDimitry Andric << /*isExtVector*/ true << LHSType; 5984480093f4SDimitry Andric return {}; 5985480093f4SDimitry Andric } 5986480093f4SDimitry Andric 5987480093f4SDimitry Andric if (RHSVT && isa<ExtVectorType>(RHSVT)) { 5988480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 5989480093f4SDimitry Andric << /*isExtVector*/ true << RHSType; 5990480093f4SDimitry Andric return {}; 5991480093f4SDimitry Andric } 5992480093f4SDimitry Andric 5993480093f4SDimitry Andric if (LHSVT && RHSVT) { 5994480093f4SDimitry Andric // If both are vector types, they must be the same type. 5995480093f4SDimitry Andric if (!Context.hasSameType(LHSType, RHSType)) { 5996480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_mismatched_vectors) 5997480093f4SDimitry Andric << LHSType << RHSType; 5998480093f4SDimitry Andric return {}; 5999480093f4SDimitry Andric } 6000480093f4SDimitry Andric ResultType = LHSType; 6001480093f4SDimitry Andric } else if (LHSVT || RHSVT) { 6002480093f4SDimitry Andric ResultType = CheckVectorOperands( 6003480093f4SDimitry Andric LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true, 6004480093f4SDimitry Andric /*AllowBoolConversions*/ false); 6005480093f4SDimitry Andric if (ResultType.isNull()) 6006480093f4SDimitry Andric return {}; 6007480093f4SDimitry Andric } else { 6008480093f4SDimitry Andric // Both are scalar. 6009480093f4SDimitry Andric QualType ResultElementTy; 6010480093f4SDimitry Andric LHSType = LHSType.getCanonicalType().getUnqualifiedType(); 6011480093f4SDimitry Andric RHSType = RHSType.getCanonicalType().getUnqualifiedType(); 6012480093f4SDimitry Andric 6013480093f4SDimitry Andric if (Context.hasSameType(LHSType, RHSType)) 6014480093f4SDimitry Andric ResultElementTy = LHSType; 6015480093f4SDimitry Andric else 6016480093f4SDimitry Andric ResultElementTy = 6017480093f4SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 6018480093f4SDimitry Andric 6019480093f4SDimitry Andric if (ResultElementTy->isEnumeralType()) { 6020480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 6021480093f4SDimitry Andric << /*isExtVector*/ false << ResultElementTy; 6022480093f4SDimitry Andric return {}; 6023480093f4SDimitry Andric } 6024480093f4SDimitry Andric ResultType = Context.getVectorType( 60255ffd83dbSDimitry Andric ResultElementTy, CondType->castAs<VectorType>()->getNumElements(), 6026480093f4SDimitry Andric VectorType::GenericVector); 6027480093f4SDimitry Andric 6028480093f4SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); 6029480093f4SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); 6030480093f4SDimitry Andric } 6031480093f4SDimitry Andric 6032480093f4SDimitry Andric assert(!ResultType.isNull() && ResultType->isVectorType() && 6033480093f4SDimitry Andric "Result should have been a vector type"); 60345ffd83dbSDimitry Andric auto *ResultVectorTy = ResultType->castAs<VectorType>(); 60355ffd83dbSDimitry Andric QualType ResultElementTy = ResultVectorTy->getElementType(); 60365ffd83dbSDimitry Andric unsigned ResultElementCount = ResultVectorTy->getNumElements(); 6037480093f4SDimitry Andric 6038480093f4SDimitry Andric if (ResultElementCount != CondElementCount) { 6039480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType 6040480093f4SDimitry Andric << ResultType; 6041480093f4SDimitry Andric return {}; 6042480093f4SDimitry Andric } 6043480093f4SDimitry Andric 6044480093f4SDimitry Andric if (Context.getTypeSize(ResultElementTy) != 6045480093f4SDimitry Andric Context.getTypeSize(CondElementTy)) { 6046480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType 6047480093f4SDimitry Andric << ResultType; 6048480093f4SDimitry Andric return {}; 6049480093f4SDimitry Andric } 6050480093f4SDimitry Andric 6051480093f4SDimitry Andric return ResultType; 6052480093f4SDimitry Andric } 6053480093f4SDimitry Andric 60540b57cec5SDimitry Andric /// Check the operands of ?: under C++ semantics. 60550b57cec5SDimitry Andric /// 60560b57cec5SDimitry Andric /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 60570b57cec5SDimitry Andric /// extension. In this case, LHS == Cond. (But they're not aliases.) 6058480093f4SDimitry Andric /// 6059480093f4SDimitry Andric /// This function also implements GCC's vector extension for conditionals. 6060480093f4SDimitry Andric /// GCC's vector extension permits the use of a?b:c where the type of 6061480093f4SDimitry Andric /// a is that of a integer vector with the same number of elements and 6062480093f4SDimitry Andric /// size as the vectors of b and c. If one of either b or c is a scalar 6063480093f4SDimitry Andric /// it is implicitly converted to match the type of the vector. 6064480093f4SDimitry Andric /// Otherwise the expression is ill-formed. If both b and c are scalars, 6065480093f4SDimitry Andric /// then b and c are checked and converted to the type of a if possible. 6066480093f4SDimitry Andric /// Unlike the OpenCL ?: operator, the expression is evaluated as 6067480093f4SDimitry Andric /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). 60680b57cec5SDimitry Andric QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 60690b57cec5SDimitry Andric ExprResult &RHS, ExprValueKind &VK, 60700b57cec5SDimitry Andric ExprObjectKind &OK, 60710b57cec5SDimitry Andric SourceLocation QuestionLoc) { 6072480093f4SDimitry Andric // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface 6073480093f4SDimitry Andric // pointers. 60740b57cec5SDimitry Andric 60750b57cec5SDimitry Andric // Assume r-value. 60760b57cec5SDimitry Andric VK = VK_RValue; 60770b57cec5SDimitry Andric OK = OK_Ordinary; 6078480093f4SDimitry Andric bool IsVectorConditional = 6079480093f4SDimitry Andric isValidVectorForConditionalCondition(Context, Cond.get()->getType()); 6080480093f4SDimitry Andric 6081480093f4SDimitry Andric // C++11 [expr.cond]p1 6082480093f4SDimitry Andric // The first expression is contextually converted to bool. 6083480093f4SDimitry Andric if (!Cond.get()->isTypeDependent()) { 6084480093f4SDimitry Andric ExprResult CondRes = IsVectorConditional 6085480093f4SDimitry Andric ? DefaultFunctionArrayLvalueConversion(Cond.get()) 6086480093f4SDimitry Andric : CheckCXXBooleanCondition(Cond.get()); 6087480093f4SDimitry Andric if (CondRes.isInvalid()) 6088480093f4SDimitry Andric return QualType(); 6089480093f4SDimitry Andric Cond = CondRes; 6090480093f4SDimitry Andric } else { 6091480093f4SDimitry Andric // To implement C++, the first expression typically doesn't alter the result 6092480093f4SDimitry Andric // type of the conditional, however the GCC compatible vector extension 6093480093f4SDimitry Andric // changes the result type to be that of the conditional. Since we cannot 6094480093f4SDimitry Andric // know if this is a vector extension here, delay the conversion of the 6095480093f4SDimitry Andric // LHS/RHS below until later. 6096480093f4SDimitry Andric return Context.DependentTy; 6097480093f4SDimitry Andric } 6098480093f4SDimitry Andric 60990b57cec5SDimitry Andric 61000b57cec5SDimitry Andric // Either of the arguments dependent? 61010b57cec5SDimitry Andric if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 61020b57cec5SDimitry Andric return Context.DependentTy; 61030b57cec5SDimitry Andric 61040b57cec5SDimitry Andric // C++11 [expr.cond]p2 61050b57cec5SDimitry Andric // If either the second or the third operand has type (cv) void, ... 61060b57cec5SDimitry Andric QualType LTy = LHS.get()->getType(); 61070b57cec5SDimitry Andric QualType RTy = RHS.get()->getType(); 61080b57cec5SDimitry Andric bool LVoid = LTy->isVoidType(); 61090b57cec5SDimitry Andric bool RVoid = RTy->isVoidType(); 61100b57cec5SDimitry Andric if (LVoid || RVoid) { 61110b57cec5SDimitry Andric // ... one of the following shall hold: 61120b57cec5SDimitry Andric // -- The second or the third operand (but not both) is a (possibly 61130b57cec5SDimitry Andric // parenthesized) throw-expression; the result is of the type 61140b57cec5SDimitry Andric // and value category of the other. 61150b57cec5SDimitry Andric bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); 61160b57cec5SDimitry Andric bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); 6117480093f4SDimitry Andric 6118480093f4SDimitry Andric // Void expressions aren't legal in the vector-conditional expressions. 6119480093f4SDimitry Andric if (IsVectorConditional) { 6120480093f4SDimitry Andric SourceRange DiagLoc = 6121480093f4SDimitry Andric LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); 6122480093f4SDimitry Andric bool IsThrow = LVoid ? LThrow : RThrow; 6123480093f4SDimitry Andric Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) 6124480093f4SDimitry Andric << DiagLoc << IsThrow; 6125480093f4SDimitry Andric return QualType(); 6126480093f4SDimitry Andric } 6127480093f4SDimitry Andric 61280b57cec5SDimitry Andric if (LThrow != RThrow) { 61290b57cec5SDimitry Andric Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); 61300b57cec5SDimitry Andric VK = NonThrow->getValueKind(); 61310b57cec5SDimitry Andric // DR (no number yet): the result is a bit-field if the 61320b57cec5SDimitry Andric // non-throw-expression operand is a bit-field. 61330b57cec5SDimitry Andric OK = NonThrow->getObjectKind(); 61340b57cec5SDimitry Andric return NonThrow->getType(); 61350b57cec5SDimitry Andric } 61360b57cec5SDimitry Andric 61370b57cec5SDimitry Andric // -- Both the second and third operands have type void; the result is of 61380b57cec5SDimitry Andric // type void and is a prvalue. 61390b57cec5SDimitry Andric if (LVoid && RVoid) 61400b57cec5SDimitry Andric return Context.VoidTy; 61410b57cec5SDimitry Andric 61420b57cec5SDimitry Andric // Neither holds, error. 61430b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 61440b57cec5SDimitry Andric << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 61450b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 61460b57cec5SDimitry Andric return QualType(); 61470b57cec5SDimitry Andric } 61480b57cec5SDimitry Andric 61490b57cec5SDimitry Andric // Neither is void. 6150480093f4SDimitry Andric if (IsVectorConditional) 6151480093f4SDimitry Andric return CheckGNUVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); 61520b57cec5SDimitry Andric 61530b57cec5SDimitry Andric // C++11 [expr.cond]p3 61540b57cec5SDimitry Andric // Otherwise, if the second and third operand have different types, and 61550b57cec5SDimitry Andric // either has (cv) class type [...] an attempt is made to convert each of 61560b57cec5SDimitry Andric // those operands to the type of the other. 61570b57cec5SDimitry Andric if (!Context.hasSameType(LTy, RTy) && 61580b57cec5SDimitry Andric (LTy->isRecordType() || RTy->isRecordType())) { 61590b57cec5SDimitry Andric // These return true if a single direction is already ambiguous. 61600b57cec5SDimitry Andric QualType L2RType, R2LType; 61610b57cec5SDimitry Andric bool HaveL2R, HaveR2L; 61620b57cec5SDimitry Andric if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 61630b57cec5SDimitry Andric return QualType(); 61640b57cec5SDimitry Andric if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 61650b57cec5SDimitry Andric return QualType(); 61660b57cec5SDimitry Andric 61670b57cec5SDimitry Andric // If both can be converted, [...] the program is ill-formed. 61680b57cec5SDimitry Andric if (HaveL2R && HaveR2L) { 61690b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_conditional_ambiguous) 61700b57cec5SDimitry Andric << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 61710b57cec5SDimitry Andric return QualType(); 61720b57cec5SDimitry Andric } 61730b57cec5SDimitry Andric 61740b57cec5SDimitry Andric // If exactly one conversion is possible, that conversion is applied to 61750b57cec5SDimitry Andric // the chosen operand and the converted operands are used in place of the 61760b57cec5SDimitry Andric // original operands for the remainder of this section. 61770b57cec5SDimitry Andric if (HaveL2R) { 61780b57cec5SDimitry Andric if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 61790b57cec5SDimitry Andric return QualType(); 61800b57cec5SDimitry Andric LTy = LHS.get()->getType(); 61810b57cec5SDimitry Andric } else if (HaveR2L) { 61820b57cec5SDimitry Andric if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 61830b57cec5SDimitry Andric return QualType(); 61840b57cec5SDimitry Andric RTy = RHS.get()->getType(); 61850b57cec5SDimitry Andric } 61860b57cec5SDimitry Andric } 61870b57cec5SDimitry Andric 61880b57cec5SDimitry Andric // C++11 [expr.cond]p3 61890b57cec5SDimitry Andric // if both are glvalues of the same value category and the same type except 61900b57cec5SDimitry Andric // for cv-qualification, an attempt is made to convert each of those 61910b57cec5SDimitry Andric // operands to the type of the other. 61920b57cec5SDimitry Andric // FIXME: 61930b57cec5SDimitry Andric // Resolving a defect in P0012R1: we extend this to cover all cases where 61940b57cec5SDimitry Andric // one of the operands is reference-compatible with the other, in order 6195480093f4SDimitry Andric // to support conditionals between functions differing in noexcept. This 6196480093f4SDimitry Andric // will similarly cover difference in array bounds after P0388R4. 6197480093f4SDimitry Andric // FIXME: If LTy and RTy have a composite pointer type, should we convert to 6198480093f4SDimitry Andric // that instead? 61990b57cec5SDimitry Andric ExprValueKind LVK = LHS.get()->getValueKind(); 62000b57cec5SDimitry Andric ExprValueKind RVK = RHS.get()->getValueKind(); 62010b57cec5SDimitry Andric if (!Context.hasSameType(LTy, RTy) && 62020b57cec5SDimitry Andric LVK == RVK && LVK != VK_RValue) { 62030b57cec5SDimitry Andric // DerivedToBase was already handled by the class-specific case above. 62040b57cec5SDimitry Andric // FIXME: Should we allow ObjC conversions here? 6205480093f4SDimitry Andric const ReferenceConversions AllowedConversions = 6206480093f4SDimitry Andric ReferenceConversions::Qualification | 6207480093f4SDimitry Andric ReferenceConversions::NestedQualification | 6208480093f4SDimitry Andric ReferenceConversions::Function; 6209480093f4SDimitry Andric 6210480093f4SDimitry Andric ReferenceConversions RefConv; 6211480093f4SDimitry Andric if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) == 6212480093f4SDimitry Andric Ref_Compatible && 6213480093f4SDimitry Andric !(RefConv & ~AllowedConversions) && 62140b57cec5SDimitry Andric // [...] subject to the constraint that the reference must bind 62150b57cec5SDimitry Andric // directly [...] 6216a7dea167SDimitry Andric !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { 62170b57cec5SDimitry Andric RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); 62180b57cec5SDimitry Andric RTy = RHS.get()->getType(); 6219480093f4SDimitry Andric } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) == 6220480093f4SDimitry Andric Ref_Compatible && 6221480093f4SDimitry Andric !(RefConv & ~AllowedConversions) && 62220b57cec5SDimitry Andric !LHS.get()->refersToBitField() && 62230b57cec5SDimitry Andric !LHS.get()->refersToVectorElement()) { 62240b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); 62250b57cec5SDimitry Andric LTy = LHS.get()->getType(); 62260b57cec5SDimitry Andric } 62270b57cec5SDimitry Andric } 62280b57cec5SDimitry Andric 62290b57cec5SDimitry Andric // C++11 [expr.cond]p4 62300b57cec5SDimitry Andric // If the second and third operands are glvalues of the same value 62310b57cec5SDimitry Andric // category and have the same type, the result is of that type and 62320b57cec5SDimitry Andric // value category and it is a bit-field if the second or the third 62330b57cec5SDimitry Andric // operand is a bit-field, or if both are bit-fields. 62340b57cec5SDimitry Andric // We only extend this to bitfields, not to the crazy other kinds of 62350b57cec5SDimitry Andric // l-values. 62360b57cec5SDimitry Andric bool Same = Context.hasSameType(LTy, RTy); 62370b57cec5SDimitry Andric if (Same && LVK == RVK && LVK != VK_RValue && 62380b57cec5SDimitry Andric LHS.get()->isOrdinaryOrBitFieldObject() && 62390b57cec5SDimitry Andric RHS.get()->isOrdinaryOrBitFieldObject()) { 62400b57cec5SDimitry Andric VK = LHS.get()->getValueKind(); 62410b57cec5SDimitry Andric if (LHS.get()->getObjectKind() == OK_BitField || 62420b57cec5SDimitry Andric RHS.get()->getObjectKind() == OK_BitField) 62430b57cec5SDimitry Andric OK = OK_BitField; 62440b57cec5SDimitry Andric 62450b57cec5SDimitry Andric // If we have function pointer types, unify them anyway to unify their 62460b57cec5SDimitry Andric // exception specifications, if any. 62470b57cec5SDimitry Andric if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 62480b57cec5SDimitry Andric Qualifiers Qs = LTy.getQualifiers(); 62490b57cec5SDimitry Andric LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, 62500b57cec5SDimitry Andric /*ConvertArgs*/false); 62510b57cec5SDimitry Andric LTy = Context.getQualifiedType(LTy, Qs); 62520b57cec5SDimitry Andric 62530b57cec5SDimitry Andric assert(!LTy.isNull() && "failed to find composite pointer type for " 62540b57cec5SDimitry Andric "canonically equivalent function ptr types"); 62550b57cec5SDimitry Andric assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type"); 62560b57cec5SDimitry Andric } 62570b57cec5SDimitry Andric 62580b57cec5SDimitry Andric return LTy; 62590b57cec5SDimitry Andric } 62600b57cec5SDimitry Andric 62610b57cec5SDimitry Andric // C++11 [expr.cond]p5 62620b57cec5SDimitry Andric // Otherwise, the result is a prvalue. If the second and third operands 62630b57cec5SDimitry Andric // do not have the same type, and either has (cv) class type, ... 62640b57cec5SDimitry Andric if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 62650b57cec5SDimitry Andric // ... overload resolution is used to determine the conversions (if any) 62660b57cec5SDimitry Andric // to be applied to the operands. If the overload resolution fails, the 62670b57cec5SDimitry Andric // program is ill-formed. 62680b57cec5SDimitry Andric if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 62690b57cec5SDimitry Andric return QualType(); 62700b57cec5SDimitry Andric } 62710b57cec5SDimitry Andric 62720b57cec5SDimitry Andric // C++11 [expr.cond]p6 62730b57cec5SDimitry Andric // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 62740b57cec5SDimitry Andric // conversions are performed on the second and third operands. 62750b57cec5SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 62760b57cec5SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 62770b57cec5SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 62780b57cec5SDimitry Andric return QualType(); 62790b57cec5SDimitry Andric LTy = LHS.get()->getType(); 62800b57cec5SDimitry Andric RTy = RHS.get()->getType(); 62810b57cec5SDimitry Andric 62820b57cec5SDimitry Andric // After those conversions, one of the following shall hold: 62830b57cec5SDimitry Andric // -- The second and third operands have the same type; the result 62840b57cec5SDimitry Andric // is of that type. If the operands have class type, the result 62850b57cec5SDimitry Andric // is a prvalue temporary of the result type, which is 62860b57cec5SDimitry Andric // copy-initialized from either the second operand or the third 62870b57cec5SDimitry Andric // operand depending on the value of the first operand. 62880b57cec5SDimitry Andric if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 62890b57cec5SDimitry Andric if (LTy->isRecordType()) { 62900b57cec5SDimitry Andric // The operands have class type. Make a temporary copy. 62910b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 62920b57cec5SDimitry Andric 62930b57cec5SDimitry Andric ExprResult LHSCopy = PerformCopyInitialization(Entity, 62940b57cec5SDimitry Andric SourceLocation(), 62950b57cec5SDimitry Andric LHS); 62960b57cec5SDimitry Andric if (LHSCopy.isInvalid()) 62970b57cec5SDimitry Andric return QualType(); 62980b57cec5SDimitry Andric 62990b57cec5SDimitry Andric ExprResult RHSCopy = PerformCopyInitialization(Entity, 63000b57cec5SDimitry Andric SourceLocation(), 63010b57cec5SDimitry Andric RHS); 63020b57cec5SDimitry Andric if (RHSCopy.isInvalid()) 63030b57cec5SDimitry Andric return QualType(); 63040b57cec5SDimitry Andric 63050b57cec5SDimitry Andric LHS = LHSCopy; 63060b57cec5SDimitry Andric RHS = RHSCopy; 63070b57cec5SDimitry Andric } 63080b57cec5SDimitry Andric 63090b57cec5SDimitry Andric // If we have function pointer types, unify them anyway to unify their 63100b57cec5SDimitry Andric // exception specifications, if any. 63110b57cec5SDimitry Andric if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 63120b57cec5SDimitry Andric LTy = FindCompositePointerType(QuestionLoc, LHS, RHS); 63130b57cec5SDimitry Andric assert(!LTy.isNull() && "failed to find composite pointer type for " 63140b57cec5SDimitry Andric "canonically equivalent function ptr types"); 63150b57cec5SDimitry Andric } 63160b57cec5SDimitry Andric 63170b57cec5SDimitry Andric return LTy; 63180b57cec5SDimitry Andric } 63190b57cec5SDimitry Andric 63200b57cec5SDimitry Andric // Extension: conditional operator involving vector types. 63210b57cec5SDimitry Andric if (LTy->isVectorType() || RTy->isVectorType()) 63220b57cec5SDimitry Andric return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 63230b57cec5SDimitry Andric /*AllowBothBool*/true, 63240b57cec5SDimitry Andric /*AllowBoolConversions*/false); 63250b57cec5SDimitry Andric 63260b57cec5SDimitry Andric // -- The second and third operands have arithmetic or enumeration type; 63270b57cec5SDimitry Andric // the usual arithmetic conversions are performed to bring them to a 63280b57cec5SDimitry Andric // common type, and the result is of that type. 63290b57cec5SDimitry Andric if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 6330480093f4SDimitry Andric QualType ResTy = 6331480093f4SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 63320b57cec5SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 63330b57cec5SDimitry Andric return QualType(); 63340b57cec5SDimitry Andric if (ResTy.isNull()) { 63350b57cec5SDimitry Andric Diag(QuestionLoc, 63360b57cec5SDimitry Andric diag::err_typecheck_cond_incompatible_operands) << LTy << RTy 63370b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 63380b57cec5SDimitry Andric return QualType(); 63390b57cec5SDimitry Andric } 63400b57cec5SDimitry Andric 63410b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 63420b57cec5SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 63430b57cec5SDimitry Andric 63440b57cec5SDimitry Andric return ResTy; 63450b57cec5SDimitry Andric } 63460b57cec5SDimitry Andric 63470b57cec5SDimitry Andric // -- The second and third operands have pointer type, or one has pointer 63480b57cec5SDimitry Andric // type and the other is a null pointer constant, or both are null 63490b57cec5SDimitry Andric // pointer constants, at least one of which is non-integral; pointer 63500b57cec5SDimitry Andric // conversions and qualification conversions are performed to bring them 63510b57cec5SDimitry Andric // to their composite pointer type. The result is of the composite 63520b57cec5SDimitry Andric // pointer type. 63530b57cec5SDimitry Andric // -- The second and third operands have pointer to member type, or one has 63540b57cec5SDimitry Andric // pointer to member type and the other is a null pointer constant; 63550b57cec5SDimitry Andric // pointer to member conversions and qualification conversions are 63560b57cec5SDimitry Andric // performed to bring them to a common type, whose cv-qualification 63570b57cec5SDimitry Andric // shall match the cv-qualification of either the second or the third 63580b57cec5SDimitry Andric // operand. The result is of the common type. 63590b57cec5SDimitry Andric QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); 63600b57cec5SDimitry Andric if (!Composite.isNull()) 63610b57cec5SDimitry Andric return Composite; 63620b57cec5SDimitry Andric 63630b57cec5SDimitry Andric // Similarly, attempt to find composite type of two objective-c pointers. 63640b57cec5SDimitry Andric Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 6365e8d8bef9SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 6366e8d8bef9SDimitry Andric return QualType(); 63670b57cec5SDimitry Andric if (!Composite.isNull()) 63680b57cec5SDimitry Andric return Composite; 63690b57cec5SDimitry Andric 63700b57cec5SDimitry Andric // Check if we are using a null with a non-pointer type. 63710b57cec5SDimitry Andric if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 63720b57cec5SDimitry Andric return QualType(); 63730b57cec5SDimitry Andric 63740b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 63750b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 63760b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 63770b57cec5SDimitry Andric return QualType(); 63780b57cec5SDimitry Andric } 63790b57cec5SDimitry Andric 63800b57cec5SDimitry Andric static FunctionProtoType::ExceptionSpecInfo 63810b57cec5SDimitry Andric mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, 63820b57cec5SDimitry Andric FunctionProtoType::ExceptionSpecInfo ESI2, 63830b57cec5SDimitry Andric SmallVectorImpl<QualType> &ExceptionTypeStorage) { 63840b57cec5SDimitry Andric ExceptionSpecificationType EST1 = ESI1.Type; 63850b57cec5SDimitry Andric ExceptionSpecificationType EST2 = ESI2.Type; 63860b57cec5SDimitry Andric 63870b57cec5SDimitry Andric // If either of them can throw anything, that is the result. 63880b57cec5SDimitry Andric if (EST1 == EST_None) return ESI1; 63890b57cec5SDimitry Andric if (EST2 == EST_None) return ESI2; 63900b57cec5SDimitry Andric if (EST1 == EST_MSAny) return ESI1; 63910b57cec5SDimitry Andric if (EST2 == EST_MSAny) return ESI2; 63920b57cec5SDimitry Andric if (EST1 == EST_NoexceptFalse) return ESI1; 63930b57cec5SDimitry Andric if (EST2 == EST_NoexceptFalse) return ESI2; 63940b57cec5SDimitry Andric 63950b57cec5SDimitry Andric // If either of them is non-throwing, the result is the other. 63960b57cec5SDimitry Andric if (EST1 == EST_NoThrow) return ESI2; 63970b57cec5SDimitry Andric if (EST2 == EST_NoThrow) return ESI1; 63980b57cec5SDimitry Andric if (EST1 == EST_DynamicNone) return ESI2; 63990b57cec5SDimitry Andric if (EST2 == EST_DynamicNone) return ESI1; 64000b57cec5SDimitry Andric if (EST1 == EST_BasicNoexcept) return ESI2; 64010b57cec5SDimitry Andric if (EST2 == EST_BasicNoexcept) return ESI1; 64020b57cec5SDimitry Andric if (EST1 == EST_NoexceptTrue) return ESI2; 64030b57cec5SDimitry Andric if (EST2 == EST_NoexceptTrue) return ESI1; 64040b57cec5SDimitry Andric 64050b57cec5SDimitry Andric // If we're left with value-dependent computed noexcept expressions, we're 64060b57cec5SDimitry Andric // stuck. Before C++17, we can just drop the exception specification entirely, 64070b57cec5SDimitry Andric // since it's not actually part of the canonical type. And this should never 64080b57cec5SDimitry Andric // happen in C++17, because it would mean we were computing the composite 64090b57cec5SDimitry Andric // pointer type of dependent types, which should never happen. 64100b57cec5SDimitry Andric if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) { 64110b57cec5SDimitry Andric assert(!S.getLangOpts().CPlusPlus17 && 64120b57cec5SDimitry Andric "computing composite pointer type of dependent types"); 64130b57cec5SDimitry Andric return FunctionProtoType::ExceptionSpecInfo(); 64140b57cec5SDimitry Andric } 64150b57cec5SDimitry Andric 64160b57cec5SDimitry Andric // Switch over the possibilities so that people adding new values know to 64170b57cec5SDimitry Andric // update this function. 64180b57cec5SDimitry Andric switch (EST1) { 64190b57cec5SDimitry Andric case EST_None: 64200b57cec5SDimitry Andric case EST_DynamicNone: 64210b57cec5SDimitry Andric case EST_MSAny: 64220b57cec5SDimitry Andric case EST_BasicNoexcept: 64230b57cec5SDimitry Andric case EST_DependentNoexcept: 64240b57cec5SDimitry Andric case EST_NoexceptFalse: 64250b57cec5SDimitry Andric case EST_NoexceptTrue: 64260b57cec5SDimitry Andric case EST_NoThrow: 64270b57cec5SDimitry Andric llvm_unreachable("handled above"); 64280b57cec5SDimitry Andric 64290b57cec5SDimitry Andric case EST_Dynamic: { 64300b57cec5SDimitry Andric // This is the fun case: both exception specifications are dynamic. Form 64310b57cec5SDimitry Andric // the union of the two lists. 64320b57cec5SDimitry Andric assert(EST2 == EST_Dynamic && "other cases should already be handled"); 64330b57cec5SDimitry Andric llvm::SmallPtrSet<QualType, 8> Found; 64340b57cec5SDimitry Andric for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions}) 64350b57cec5SDimitry Andric for (QualType E : Exceptions) 64360b57cec5SDimitry Andric if (Found.insert(S.Context.getCanonicalType(E)).second) 64370b57cec5SDimitry Andric ExceptionTypeStorage.push_back(E); 64380b57cec5SDimitry Andric 64390b57cec5SDimitry Andric FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); 64400b57cec5SDimitry Andric Result.Exceptions = ExceptionTypeStorage; 64410b57cec5SDimitry Andric return Result; 64420b57cec5SDimitry Andric } 64430b57cec5SDimitry Andric 64440b57cec5SDimitry Andric case EST_Unevaluated: 64450b57cec5SDimitry Andric case EST_Uninstantiated: 64460b57cec5SDimitry Andric case EST_Unparsed: 64470b57cec5SDimitry Andric llvm_unreachable("shouldn't see unresolved exception specifications here"); 64480b57cec5SDimitry Andric } 64490b57cec5SDimitry Andric 64500b57cec5SDimitry Andric llvm_unreachable("invalid ExceptionSpecificationType"); 64510b57cec5SDimitry Andric } 64520b57cec5SDimitry Andric 64530b57cec5SDimitry Andric /// Find a merged pointer type and convert the two expressions to it. 64540b57cec5SDimitry Andric /// 6455480093f4SDimitry Andric /// This finds the composite pointer type for \p E1 and \p E2 according to 6456480093f4SDimitry Andric /// C++2a [expr.type]p3. It converts both expressions to this type and returns 6457480093f4SDimitry Andric /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs 6458480093f4SDimitry Andric /// is \c true). 64590b57cec5SDimitry Andric /// 64600b57cec5SDimitry Andric /// \param Loc The location of the operator requiring these two expressions to 64610b57cec5SDimitry Andric /// be converted to the composite pointer type. 64620b57cec5SDimitry Andric /// 64630b57cec5SDimitry Andric /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. 64640b57cec5SDimitry Andric QualType Sema::FindCompositePointerType(SourceLocation Loc, 64650b57cec5SDimitry Andric Expr *&E1, Expr *&E2, 64660b57cec5SDimitry Andric bool ConvertArgs) { 64670b57cec5SDimitry Andric assert(getLangOpts().CPlusPlus && "This function assumes C++"); 64680b57cec5SDimitry Andric 64690b57cec5SDimitry Andric // C++1z [expr]p14: 64700b57cec5SDimitry Andric // The composite pointer type of two operands p1 and p2 having types T1 64710b57cec5SDimitry Andric // and T2 64720b57cec5SDimitry Andric QualType T1 = E1->getType(), T2 = E2->getType(); 64730b57cec5SDimitry Andric 64740b57cec5SDimitry Andric // where at least one is a pointer or pointer to member type or 64750b57cec5SDimitry Andric // std::nullptr_t is: 64760b57cec5SDimitry Andric bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || 64770b57cec5SDimitry Andric T1->isNullPtrType(); 64780b57cec5SDimitry Andric bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || 64790b57cec5SDimitry Andric T2->isNullPtrType(); 64800b57cec5SDimitry Andric if (!T1IsPointerLike && !T2IsPointerLike) 64810b57cec5SDimitry Andric return QualType(); 64820b57cec5SDimitry Andric 64830b57cec5SDimitry Andric // - if both p1 and p2 are null pointer constants, std::nullptr_t; 64840b57cec5SDimitry Andric // This can't actually happen, following the standard, but we also use this 64850b57cec5SDimitry Andric // to implement the end of [expr.conv], which hits this case. 64860b57cec5SDimitry Andric // 64870b57cec5SDimitry Andric // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; 64880b57cec5SDimitry Andric if (T1IsPointerLike && 64890b57cec5SDimitry Andric E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 64900b57cec5SDimitry Andric if (ConvertArgs) 64910b57cec5SDimitry Andric E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() 64920b57cec5SDimitry Andric ? CK_NullToMemberPointer 64930b57cec5SDimitry Andric : CK_NullToPointer).get(); 64940b57cec5SDimitry Andric return T1; 64950b57cec5SDimitry Andric } 64960b57cec5SDimitry Andric if (T2IsPointerLike && 64970b57cec5SDimitry Andric E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 64980b57cec5SDimitry Andric if (ConvertArgs) 64990b57cec5SDimitry Andric E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() 65000b57cec5SDimitry Andric ? CK_NullToMemberPointer 65010b57cec5SDimitry Andric : CK_NullToPointer).get(); 65020b57cec5SDimitry Andric return T2; 65030b57cec5SDimitry Andric } 65040b57cec5SDimitry Andric 65050b57cec5SDimitry Andric // Now both have to be pointers or member pointers. 65060b57cec5SDimitry Andric if (!T1IsPointerLike || !T2IsPointerLike) 65070b57cec5SDimitry Andric return QualType(); 65080b57cec5SDimitry Andric assert(!T1->isNullPtrType() && !T2->isNullPtrType() && 65090b57cec5SDimitry Andric "nullptr_t should be a null pointer constant"); 65100b57cec5SDimitry Andric 6511480093f4SDimitry Andric struct Step { 6512480093f4SDimitry Andric enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; 6513480093f4SDimitry Andric // Qualifiers to apply under the step kind. 6514480093f4SDimitry Andric Qualifiers Quals; 6515480093f4SDimitry Andric /// The class for a pointer-to-member; a constant array type with a bound 6516480093f4SDimitry Andric /// (if any) for an array. 6517480093f4SDimitry Andric const Type *ClassOrBound; 6518480093f4SDimitry Andric 6519480093f4SDimitry Andric Step(Kind K, const Type *ClassOrBound = nullptr) 6520480093f4SDimitry Andric : K(K), Quals(), ClassOrBound(ClassOrBound) {} 6521480093f4SDimitry Andric QualType rebuild(ASTContext &Ctx, QualType T) const { 6522480093f4SDimitry Andric T = Ctx.getQualifiedType(T, Quals); 6523480093f4SDimitry Andric switch (K) { 6524480093f4SDimitry Andric case Pointer: 6525480093f4SDimitry Andric return Ctx.getPointerType(T); 6526480093f4SDimitry Andric case MemberPointer: 6527480093f4SDimitry Andric return Ctx.getMemberPointerType(T, ClassOrBound); 6528480093f4SDimitry Andric case ObjCPointer: 6529480093f4SDimitry Andric return Ctx.getObjCObjectPointerType(T); 6530480093f4SDimitry Andric case Array: 6531480093f4SDimitry Andric if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound)) 6532480093f4SDimitry Andric return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr, 6533480093f4SDimitry Andric ArrayType::Normal, 0); 6534480093f4SDimitry Andric else 6535480093f4SDimitry Andric return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0); 6536480093f4SDimitry Andric } 6537480093f4SDimitry Andric llvm_unreachable("unknown step kind"); 6538480093f4SDimitry Andric } 6539480093f4SDimitry Andric }; 6540480093f4SDimitry Andric 6541480093f4SDimitry Andric SmallVector<Step, 8> Steps; 6542480093f4SDimitry Andric 65430b57cec5SDimitry Andric // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 65440b57cec5SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 65450b57cec5SDimitry Andric // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, 65460b57cec5SDimitry Andric // respectively; 65470b57cec5SDimitry Andric // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer 6548480093f4SDimitry Andric // to member of C2 of type cv2 U2" for some non-function type U, where 6549480093f4SDimitry Andric // C1 is reference-related to C2 or C2 is reference-related to C1, the 6550480093f4SDimitry Andric // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, 6551480093f4SDimitry Andric // respectively; 65520b57cec5SDimitry Andric // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and 65530b57cec5SDimitry Andric // T2; 65540b57cec5SDimitry Andric // 6555480093f4SDimitry Andric // Dismantle T1 and T2 to simultaneously determine whether they are similar 6556480093f4SDimitry Andric // and to prepare to form the cv-combined type if so. 65570b57cec5SDimitry Andric QualType Composite1 = T1; 65580b57cec5SDimitry Andric QualType Composite2 = T2; 65590b57cec5SDimitry Andric unsigned NeedConstBefore = 0; 65600b57cec5SDimitry Andric while (true) { 6561480093f4SDimitry Andric assert(!Composite1.isNull() && !Composite2.isNull()); 6562480093f4SDimitry Andric 6563480093f4SDimitry Andric Qualifiers Q1, Q2; 6564480093f4SDimitry Andric Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); 6565480093f4SDimitry Andric Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); 6566480093f4SDimitry Andric 6567480093f4SDimitry Andric // Top-level qualifiers are ignored. Merge at all lower levels. 6568480093f4SDimitry Andric if (!Steps.empty()) { 6569480093f4SDimitry Andric // Find the qualifier union: (approximately) the unique minimal set of 6570480093f4SDimitry Andric // qualifiers that is compatible with both types. 6571480093f4SDimitry Andric Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | 6572480093f4SDimitry Andric Q2.getCVRUQualifiers()); 6573480093f4SDimitry Andric 6574480093f4SDimitry Andric // Under one level of pointer or pointer-to-member, we can change to an 6575480093f4SDimitry Andric // unambiguous compatible address space. 6576480093f4SDimitry Andric if (Q1.getAddressSpace() == Q2.getAddressSpace()) { 6577480093f4SDimitry Andric Quals.setAddressSpace(Q1.getAddressSpace()); 6578480093f4SDimitry Andric } else if (Steps.size() == 1) { 6579480093f4SDimitry Andric bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2); 6580480093f4SDimitry Andric bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1); 6581480093f4SDimitry Andric if (MaybeQ1 == MaybeQ2) 6582480093f4SDimitry Andric return QualType(); // No unique best address space. 6583480093f4SDimitry Andric Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() 6584480093f4SDimitry Andric : Q2.getAddressSpace()); 6585480093f4SDimitry Andric } else { 6586480093f4SDimitry Andric return QualType(); 6587480093f4SDimitry Andric } 6588480093f4SDimitry Andric 6589480093f4SDimitry Andric // FIXME: In C, we merge __strong and none to __strong at the top level. 6590480093f4SDimitry Andric if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) 6591480093f4SDimitry Andric Quals.setObjCGCAttr(Q1.getObjCGCAttr()); 6592e8d8bef9SDimitry Andric else if (T1->isVoidPointerType() || T2->isVoidPointerType()) 6593e8d8bef9SDimitry Andric assert(Steps.size() == 1); 6594480093f4SDimitry Andric else 6595480093f4SDimitry Andric return QualType(); 6596480093f4SDimitry Andric 6597480093f4SDimitry Andric // Mismatched lifetime qualifiers never compatibly include each other. 6598480093f4SDimitry Andric if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) 6599480093f4SDimitry Andric Quals.setObjCLifetime(Q1.getObjCLifetime()); 6600e8d8bef9SDimitry Andric else if (T1->isVoidPointerType() || T2->isVoidPointerType()) 6601e8d8bef9SDimitry Andric assert(Steps.size() == 1); 6602480093f4SDimitry Andric else 6603480093f4SDimitry Andric return QualType(); 6604480093f4SDimitry Andric 6605480093f4SDimitry Andric Steps.back().Quals = Quals; 6606480093f4SDimitry Andric if (Q1 != Quals || Q2 != Quals) 6607480093f4SDimitry Andric NeedConstBefore = Steps.size() - 1; 6608480093f4SDimitry Andric } 6609480093f4SDimitry Andric 6610480093f4SDimitry Andric // FIXME: Can we unify the following with UnwrapSimilarTypes? 66110b57cec5SDimitry Andric const PointerType *Ptr1, *Ptr2; 66120b57cec5SDimitry Andric if ((Ptr1 = Composite1->getAs<PointerType>()) && 66130b57cec5SDimitry Andric (Ptr2 = Composite2->getAs<PointerType>())) { 66140b57cec5SDimitry Andric Composite1 = Ptr1->getPointeeType(); 66150b57cec5SDimitry Andric Composite2 = Ptr2->getPointeeType(); 6616480093f4SDimitry Andric Steps.emplace_back(Step::Pointer); 6617480093f4SDimitry Andric continue; 6618480093f4SDimitry Andric } 66190b57cec5SDimitry Andric 6620480093f4SDimitry Andric const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; 6621480093f4SDimitry Andric if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && 6622480093f4SDimitry Andric (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { 6623480093f4SDimitry Andric Composite1 = ObjPtr1->getPointeeType(); 6624480093f4SDimitry Andric Composite2 = ObjPtr2->getPointeeType(); 6625480093f4SDimitry Andric Steps.emplace_back(Step::ObjCPointer); 66260b57cec5SDimitry Andric continue; 66270b57cec5SDimitry Andric } 66280b57cec5SDimitry Andric 66290b57cec5SDimitry Andric const MemberPointerType *MemPtr1, *MemPtr2; 66300b57cec5SDimitry Andric if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 66310b57cec5SDimitry Andric (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 66320b57cec5SDimitry Andric Composite1 = MemPtr1->getPointeeType(); 66330b57cec5SDimitry Andric Composite2 = MemPtr2->getPointeeType(); 66340b57cec5SDimitry Andric 6635480093f4SDimitry Andric // At the top level, we can perform a base-to-derived pointer-to-member 6636480093f4SDimitry Andric // conversion: 6637480093f4SDimitry Andric // 6638480093f4SDimitry Andric // - [...] where C1 is reference-related to C2 or C2 is 6639480093f4SDimitry Andric // reference-related to C1 6640480093f4SDimitry Andric // 6641480093f4SDimitry Andric // (Note that the only kinds of reference-relatedness in scope here are 6642480093f4SDimitry Andric // "same type or derived from".) At any other level, the class must 6643480093f4SDimitry Andric // exactly match. 6644480093f4SDimitry Andric const Type *Class = nullptr; 6645480093f4SDimitry Andric QualType Cls1(MemPtr1->getClass(), 0); 6646480093f4SDimitry Andric QualType Cls2(MemPtr2->getClass(), 0); 6647480093f4SDimitry Andric if (Context.hasSameType(Cls1, Cls2)) 6648480093f4SDimitry Andric Class = MemPtr1->getClass(); 6649480093f4SDimitry Andric else if (Steps.empty()) 6650480093f4SDimitry Andric Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() : 6651480093f4SDimitry Andric IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr; 6652480093f4SDimitry Andric if (!Class) 6653480093f4SDimitry Andric return QualType(); 66540b57cec5SDimitry Andric 6655480093f4SDimitry Andric Steps.emplace_back(Step::MemberPointer, Class); 66560b57cec5SDimitry Andric continue; 66570b57cec5SDimitry Andric } 66580b57cec5SDimitry Andric 6659480093f4SDimitry Andric // Special case: at the top level, we can decompose an Objective-C pointer 6660480093f4SDimitry Andric // and a 'cv void *'. Unify the qualifiers. 6661480093f4SDimitry Andric if (Steps.empty() && ((Composite1->isVoidPointerType() && 6662480093f4SDimitry Andric Composite2->isObjCObjectPointerType()) || 6663480093f4SDimitry Andric (Composite1->isObjCObjectPointerType() && 6664480093f4SDimitry Andric Composite2->isVoidPointerType()))) { 6665480093f4SDimitry Andric Composite1 = Composite1->getPointeeType(); 6666480093f4SDimitry Andric Composite2 = Composite2->getPointeeType(); 6667480093f4SDimitry Andric Steps.emplace_back(Step::Pointer); 6668480093f4SDimitry Andric continue; 6669480093f4SDimitry Andric } 6670480093f4SDimitry Andric 6671480093f4SDimitry Andric // FIXME: arrays 6672480093f4SDimitry Andric 66730b57cec5SDimitry Andric // FIXME: block pointer types? 66740b57cec5SDimitry Andric 66750b57cec5SDimitry Andric // Cannot unwrap any more types. 66760b57cec5SDimitry Andric break; 66770b57cec5SDimitry Andric } 66780b57cec5SDimitry Andric 6679480093f4SDimitry Andric // - if T1 or T2 is "pointer to noexcept function" and the other type is 6680480093f4SDimitry Andric // "pointer to function", where the function types are otherwise the same, 6681480093f4SDimitry Andric // "pointer to function"; 6682480093f4SDimitry Andric // - if T1 or T2 is "pointer to member of C1 of type function", the other 6683480093f4SDimitry Andric // type is "pointer to member of C2 of type noexcept function", and C1 6684480093f4SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1, where 6685480093f4SDimitry Andric // the function types are otherwise the same, "pointer to member of C2 of 6686480093f4SDimitry Andric // type function" or "pointer to member of C1 of type function", 6687480093f4SDimitry Andric // respectively; 6688480093f4SDimitry Andric // 6689480093f4SDimitry Andric // We also support 'noreturn' here, so as a Clang extension we generalize the 6690480093f4SDimitry Andric // above to: 6691480093f4SDimitry Andric // 6692480093f4SDimitry Andric // - [Clang] If T1 and T2 are both of type "pointer to function" or 6693480093f4SDimitry Andric // "pointer to member function" and the pointee types can be unified 6694480093f4SDimitry Andric // by a function pointer conversion, that conversion is applied 6695480093f4SDimitry Andric // before checking the following rules. 6696480093f4SDimitry Andric // 6697480093f4SDimitry Andric // We've already unwrapped down to the function types, and we want to merge 6698480093f4SDimitry Andric // rather than just convert, so do this ourselves rather than calling 66990b57cec5SDimitry Andric // IsFunctionConversion. 67000b57cec5SDimitry Andric // 67010b57cec5SDimitry Andric // FIXME: In order to match the standard wording as closely as possible, we 67020b57cec5SDimitry Andric // currently only do this under a single level of pointers. Ideally, we would 67030b57cec5SDimitry Andric // allow this in general, and set NeedConstBefore to the relevant depth on 6704480093f4SDimitry Andric // the side(s) where we changed anything. If we permit that, we should also 6705480093f4SDimitry Andric // consider this conversion when determining type similarity and model it as 6706480093f4SDimitry Andric // a qualification conversion. 6707480093f4SDimitry Andric if (Steps.size() == 1) { 67080b57cec5SDimitry Andric if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { 67090b57cec5SDimitry Andric if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { 67100b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); 67110b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); 67120b57cec5SDimitry Andric 67130b57cec5SDimitry Andric // The result is noreturn if both operands are. 67140b57cec5SDimitry Andric bool Noreturn = 67150b57cec5SDimitry Andric EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); 67160b57cec5SDimitry Andric EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); 67170b57cec5SDimitry Andric EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); 67180b57cec5SDimitry Andric 67190b57cec5SDimitry Andric // The result is nothrow if both operands are. 67200b57cec5SDimitry Andric SmallVector<QualType, 8> ExceptionTypeStorage; 67210b57cec5SDimitry Andric EPI1.ExceptionSpec = EPI2.ExceptionSpec = 67220b57cec5SDimitry Andric mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec, 67230b57cec5SDimitry Andric ExceptionTypeStorage); 67240b57cec5SDimitry Andric 67250b57cec5SDimitry Andric Composite1 = Context.getFunctionType(FPT1->getReturnType(), 67260b57cec5SDimitry Andric FPT1->getParamTypes(), EPI1); 67270b57cec5SDimitry Andric Composite2 = Context.getFunctionType(FPT2->getReturnType(), 67280b57cec5SDimitry Andric FPT2->getParamTypes(), EPI2); 67290b57cec5SDimitry Andric } 67300b57cec5SDimitry Andric } 67310b57cec5SDimitry Andric } 67320b57cec5SDimitry Andric 6733480093f4SDimitry Andric // There are some more conversions we can perform under exactly one pointer. 6734480093f4SDimitry Andric if (Steps.size() == 1 && Steps.front().K == Step::Pointer && 6735480093f4SDimitry Andric !Context.hasSameType(Composite1, Composite2)) { 6736480093f4SDimitry Andric // - if T1 or T2 is "pointer to cv1 void" and the other type is 6737480093f4SDimitry Andric // "pointer to cv2 T", where T is an object type or void, 6738480093f4SDimitry Andric // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; 6739480093f4SDimitry Andric if (Composite1->isVoidType() && Composite2->isObjectType()) 6740480093f4SDimitry Andric Composite2 = Composite1; 6741480093f4SDimitry Andric else if (Composite2->isVoidType() && Composite1->isObjectType()) 6742480093f4SDimitry Andric Composite1 = Composite2; 6743480093f4SDimitry Andric // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 6744480093f4SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 6745480093f4SDimitry Andric // the cv-combined type of T1 and T2 or the cv-combined type of T2 and 6746480093f4SDimitry Andric // T1, respectively; 6747480093f4SDimitry Andric // 6748480093f4SDimitry Andric // The "similar type" handling covers all of this except for the "T1 is a 6749480093f4SDimitry Andric // base class of T2" case in the definition of reference-related. 6750480093f4SDimitry Andric else if (IsDerivedFrom(Loc, Composite1, Composite2)) 6751480093f4SDimitry Andric Composite1 = Composite2; 6752480093f4SDimitry Andric else if (IsDerivedFrom(Loc, Composite2, Composite1)) 6753480093f4SDimitry Andric Composite2 = Composite1; 6754480093f4SDimitry Andric } 6755480093f4SDimitry Andric 6756480093f4SDimitry Andric // At this point, either the inner types are the same or we have failed to 6757480093f4SDimitry Andric // find a composite pointer type. 6758480093f4SDimitry Andric if (!Context.hasSameType(Composite1, Composite2)) 6759480093f4SDimitry Andric return QualType(); 6760480093f4SDimitry Andric 6761480093f4SDimitry Andric // Per C++ [conv.qual]p3, add 'const' to every level before the last 6762480093f4SDimitry Andric // differing qualifier. 67630b57cec5SDimitry Andric for (unsigned I = 0; I != NeedConstBefore; ++I) 6764480093f4SDimitry Andric Steps[I].Quals.addConst(); 67650b57cec5SDimitry Andric 6766480093f4SDimitry Andric // Rebuild the composite type. 6767480093f4SDimitry Andric QualType Composite = Composite1; 6768480093f4SDimitry Andric for (auto &S : llvm::reverse(Steps)) 6769480093f4SDimitry Andric Composite = S.rebuild(Context, Composite); 67700b57cec5SDimitry Andric 6771480093f4SDimitry Andric if (ConvertArgs) { 6772480093f4SDimitry Andric // Convert the expressions to the composite pointer type. 6773480093f4SDimitry Andric InitializedEntity Entity = 6774480093f4SDimitry Andric InitializedEntity::InitializeTemporary(Composite); 6775480093f4SDimitry Andric InitializationKind Kind = 6776480093f4SDimitry Andric InitializationKind::CreateCopy(Loc, SourceLocation()); 67770b57cec5SDimitry Andric 6778480093f4SDimitry Andric InitializationSequence E1ToC(*this, Entity, Kind, E1); 6779480093f4SDimitry Andric if (!E1ToC) 6780480093f4SDimitry Andric return QualType(); 67810b57cec5SDimitry Andric 6782480093f4SDimitry Andric InitializationSequence E2ToC(*this, Entity, Kind, E2); 6783480093f4SDimitry Andric if (!E2ToC) 6784480093f4SDimitry Andric return QualType(); 6785480093f4SDimitry Andric 6786480093f4SDimitry Andric // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. 6787480093f4SDimitry Andric ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1); 67880b57cec5SDimitry Andric if (E1Result.isInvalid()) 6789480093f4SDimitry Andric return QualType(); 6790480093f4SDimitry Andric E1 = E1Result.get(); 67910b57cec5SDimitry Andric 6792480093f4SDimitry Andric ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2); 67930b57cec5SDimitry Andric if (E2Result.isInvalid()) 67940b57cec5SDimitry Andric return QualType(); 6795480093f4SDimitry Andric E2 = E2Result.get(); 67960b57cec5SDimitry Andric } 67970b57cec5SDimitry Andric 6798480093f4SDimitry Andric return Composite; 67990b57cec5SDimitry Andric } 68000b57cec5SDimitry Andric 68010b57cec5SDimitry Andric ExprResult Sema::MaybeBindToTemporary(Expr *E) { 68020b57cec5SDimitry Andric if (!E) 68030b57cec5SDimitry Andric return ExprError(); 68040b57cec5SDimitry Andric 68050b57cec5SDimitry Andric assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 68060b57cec5SDimitry Andric 68070b57cec5SDimitry Andric // If the result is a glvalue, we shouldn't bind it. 68080b57cec5SDimitry Andric if (!E->isRValue()) 68090b57cec5SDimitry Andric return E; 68100b57cec5SDimitry Andric 68110b57cec5SDimitry Andric // In ARC, calls that return a retainable type can return retained, 68120b57cec5SDimitry Andric // in which case we have to insert a consuming cast. 68130b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 68140b57cec5SDimitry Andric E->getType()->isObjCRetainableType()) { 68150b57cec5SDimitry Andric 68160b57cec5SDimitry Andric bool ReturnsRetained; 68170b57cec5SDimitry Andric 68180b57cec5SDimitry Andric // For actual calls, we compute this by examining the type of the 68190b57cec5SDimitry Andric // called value. 68200b57cec5SDimitry Andric if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 68210b57cec5SDimitry Andric Expr *Callee = Call->getCallee()->IgnoreParens(); 68220b57cec5SDimitry Andric QualType T = Callee->getType(); 68230b57cec5SDimitry Andric 68240b57cec5SDimitry Andric if (T == Context.BoundMemberTy) { 68250b57cec5SDimitry Andric // Handle pointer-to-members. 68260b57cec5SDimitry Andric if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 68270b57cec5SDimitry Andric T = BinOp->getRHS()->getType(); 68280b57cec5SDimitry Andric else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 68290b57cec5SDimitry Andric T = Mem->getMemberDecl()->getType(); 68300b57cec5SDimitry Andric } 68310b57cec5SDimitry Andric 68320b57cec5SDimitry Andric if (const PointerType *Ptr = T->getAs<PointerType>()) 68330b57cec5SDimitry Andric T = Ptr->getPointeeType(); 68340b57cec5SDimitry Andric else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 68350b57cec5SDimitry Andric T = Ptr->getPointeeType(); 68360b57cec5SDimitry Andric else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 68370b57cec5SDimitry Andric T = MemPtr->getPointeeType(); 68380b57cec5SDimitry Andric 68395ffd83dbSDimitry Andric auto *FTy = T->castAs<FunctionType>(); 68400b57cec5SDimitry Andric ReturnsRetained = FTy->getExtInfo().getProducesResult(); 68410b57cec5SDimitry Andric 68420b57cec5SDimitry Andric // ActOnStmtExpr arranges things so that StmtExprs of retainable 68430b57cec5SDimitry Andric // type always produce a +1 object. 68440b57cec5SDimitry Andric } else if (isa<StmtExpr>(E)) { 68450b57cec5SDimitry Andric ReturnsRetained = true; 68460b57cec5SDimitry Andric 68470b57cec5SDimitry Andric // We hit this case with the lambda conversion-to-block optimization; 68480b57cec5SDimitry Andric // we don't want any extra casts here. 68490b57cec5SDimitry Andric } else if (isa<CastExpr>(E) && 68500b57cec5SDimitry Andric isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 68510b57cec5SDimitry Andric return E; 68520b57cec5SDimitry Andric 68530b57cec5SDimitry Andric // For message sends and property references, we try to find an 68540b57cec5SDimitry Andric // actual method. FIXME: we should infer retention by selector in 68550b57cec5SDimitry Andric // cases where we don't have an actual method. 68560b57cec5SDimitry Andric } else { 68570b57cec5SDimitry Andric ObjCMethodDecl *D = nullptr; 68580b57cec5SDimitry Andric if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 68590b57cec5SDimitry Andric D = Send->getMethodDecl(); 68600b57cec5SDimitry Andric } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 68610b57cec5SDimitry Andric D = BoxedExpr->getBoxingMethod(); 68620b57cec5SDimitry Andric } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 68630b57cec5SDimitry Andric // Don't do reclaims if we're using the zero-element array 68640b57cec5SDimitry Andric // constant. 68650b57cec5SDimitry Andric if (ArrayLit->getNumElements() == 0 && 68660b57cec5SDimitry Andric Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 68670b57cec5SDimitry Andric return E; 68680b57cec5SDimitry Andric 68690b57cec5SDimitry Andric D = ArrayLit->getArrayWithObjectsMethod(); 68700b57cec5SDimitry Andric } else if (ObjCDictionaryLiteral *DictLit 68710b57cec5SDimitry Andric = dyn_cast<ObjCDictionaryLiteral>(E)) { 68720b57cec5SDimitry Andric // Don't do reclaims if we're using the zero-element dictionary 68730b57cec5SDimitry Andric // constant. 68740b57cec5SDimitry Andric if (DictLit->getNumElements() == 0 && 68750b57cec5SDimitry Andric Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 68760b57cec5SDimitry Andric return E; 68770b57cec5SDimitry Andric 68780b57cec5SDimitry Andric D = DictLit->getDictWithObjectsMethod(); 68790b57cec5SDimitry Andric } 68800b57cec5SDimitry Andric 68810b57cec5SDimitry Andric ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 68820b57cec5SDimitry Andric 68830b57cec5SDimitry Andric // Don't do reclaims on performSelector calls; despite their 68840b57cec5SDimitry Andric // return type, the invoked method doesn't necessarily actually 68850b57cec5SDimitry Andric // return an object. 68860b57cec5SDimitry Andric if (!ReturnsRetained && 68870b57cec5SDimitry Andric D && D->getMethodFamily() == OMF_performSelector) 68880b57cec5SDimitry Andric return E; 68890b57cec5SDimitry Andric } 68900b57cec5SDimitry Andric 68910b57cec5SDimitry Andric // Don't reclaim an object of Class type. 68920b57cec5SDimitry Andric if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 68930b57cec5SDimitry Andric return E; 68940b57cec5SDimitry Andric 68950b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 68960b57cec5SDimitry Andric 68970b57cec5SDimitry Andric CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 68980b57cec5SDimitry Andric : CK_ARCReclaimReturnedObject); 68990b57cec5SDimitry Andric return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, 6900e8d8bef9SDimitry Andric VK_RValue, FPOptionsOverride()); 69010b57cec5SDimitry Andric } 69020b57cec5SDimitry Andric 69035ffd83dbSDimitry Andric if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 69045ffd83dbSDimitry Andric Cleanup.setExprNeedsCleanups(true); 69055ffd83dbSDimitry Andric 69060b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 69070b57cec5SDimitry Andric return E; 69080b57cec5SDimitry Andric 69090b57cec5SDimitry Andric // Search for the base element type (cf. ASTContext::getBaseElementType) with 69100b57cec5SDimitry Andric // a fast path for the common case that the type is directly a RecordType. 69110b57cec5SDimitry Andric const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 69120b57cec5SDimitry Andric const RecordType *RT = nullptr; 69130b57cec5SDimitry Andric while (!RT) { 69140b57cec5SDimitry Andric switch (T->getTypeClass()) { 69150b57cec5SDimitry Andric case Type::Record: 69160b57cec5SDimitry Andric RT = cast<RecordType>(T); 69170b57cec5SDimitry Andric break; 69180b57cec5SDimitry Andric case Type::ConstantArray: 69190b57cec5SDimitry Andric case Type::IncompleteArray: 69200b57cec5SDimitry Andric case Type::VariableArray: 69210b57cec5SDimitry Andric case Type::DependentSizedArray: 69220b57cec5SDimitry Andric T = cast<ArrayType>(T)->getElementType().getTypePtr(); 69230b57cec5SDimitry Andric break; 69240b57cec5SDimitry Andric default: 69250b57cec5SDimitry Andric return E; 69260b57cec5SDimitry Andric } 69270b57cec5SDimitry Andric } 69280b57cec5SDimitry Andric 69290b57cec5SDimitry Andric // That should be enough to guarantee that this type is complete, if we're 69300b57cec5SDimitry Andric // not processing a decltype expression. 69310b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 69320b57cec5SDimitry Andric if (RD->isInvalidDecl() || RD->isDependentContext()) 69330b57cec5SDimitry Andric return E; 69340b57cec5SDimitry Andric 69350b57cec5SDimitry Andric bool IsDecltype = ExprEvalContexts.back().ExprContext == 69360b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Decltype; 69370b57cec5SDimitry Andric CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); 69380b57cec5SDimitry Andric 69390b57cec5SDimitry Andric if (Destructor) { 69400b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), Destructor); 69410b57cec5SDimitry Andric CheckDestructorAccess(E->getExprLoc(), Destructor, 69420b57cec5SDimitry Andric PDiag(diag::err_access_dtor_temp) 69430b57cec5SDimitry Andric << E->getType()); 69440b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 69450b57cec5SDimitry Andric return ExprError(); 69460b57cec5SDimitry Andric 69470b57cec5SDimitry Andric // If destructor is trivial, we can avoid the extra copy. 69480b57cec5SDimitry Andric if (Destructor->isTrivial()) 69490b57cec5SDimitry Andric return E; 69500b57cec5SDimitry Andric 69510b57cec5SDimitry Andric // We need a cleanup, but we don't need to remember the temporary. 69520b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 69530b57cec5SDimitry Andric } 69540b57cec5SDimitry Andric 69550b57cec5SDimitry Andric CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 69560b57cec5SDimitry Andric CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 69570b57cec5SDimitry Andric 69580b57cec5SDimitry Andric if (IsDecltype) 69590b57cec5SDimitry Andric ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 69600b57cec5SDimitry Andric 69610b57cec5SDimitry Andric return Bind; 69620b57cec5SDimitry Andric } 69630b57cec5SDimitry Andric 69640b57cec5SDimitry Andric ExprResult 69650b57cec5SDimitry Andric Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 69660b57cec5SDimitry Andric if (SubExpr.isInvalid()) 69670b57cec5SDimitry Andric return ExprError(); 69680b57cec5SDimitry Andric 69690b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(SubExpr.get()); 69700b57cec5SDimitry Andric } 69710b57cec5SDimitry Andric 69720b57cec5SDimitry Andric Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 69730b57cec5SDimitry Andric assert(SubExpr && "subexpression can't be null!"); 69740b57cec5SDimitry Andric 69750b57cec5SDimitry Andric CleanupVarDeclMarking(); 69760b57cec5SDimitry Andric 69770b57cec5SDimitry Andric unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 69780b57cec5SDimitry Andric assert(ExprCleanupObjects.size() >= FirstCleanup); 69790b57cec5SDimitry Andric assert(Cleanup.exprNeedsCleanups() || 69800b57cec5SDimitry Andric ExprCleanupObjects.size() == FirstCleanup); 69810b57cec5SDimitry Andric if (!Cleanup.exprNeedsCleanups()) 69820b57cec5SDimitry Andric return SubExpr; 69830b57cec5SDimitry Andric 69840b57cec5SDimitry Andric auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 69850b57cec5SDimitry Andric ExprCleanupObjects.size() - FirstCleanup); 69860b57cec5SDimitry Andric 69870b57cec5SDimitry Andric auto *E = ExprWithCleanups::Create( 69880b57cec5SDimitry Andric Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); 69890b57cec5SDimitry Andric DiscardCleanupsInEvaluationContext(); 69900b57cec5SDimitry Andric 69910b57cec5SDimitry Andric return E; 69920b57cec5SDimitry Andric } 69930b57cec5SDimitry Andric 69940b57cec5SDimitry Andric Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 69950b57cec5SDimitry Andric assert(SubStmt && "sub-statement can't be null!"); 69960b57cec5SDimitry Andric 69970b57cec5SDimitry Andric CleanupVarDeclMarking(); 69980b57cec5SDimitry Andric 69990b57cec5SDimitry Andric if (!Cleanup.exprNeedsCleanups()) 70000b57cec5SDimitry Andric return SubStmt; 70010b57cec5SDimitry Andric 70020b57cec5SDimitry Andric // FIXME: In order to attach the temporaries, wrap the statement into 70030b57cec5SDimitry Andric // a StmtExpr; currently this is only used for asm statements. 70040b57cec5SDimitry Andric // This is hacky, either create a new CXXStmtWithTemporaries statement or 70050b57cec5SDimitry Andric // a new AsmStmtWithTemporaries. 70060b57cec5SDimitry Andric CompoundStmt *CompStmt = CompoundStmt::Create( 70070b57cec5SDimitry Andric Context, SubStmt, SourceLocation(), SourceLocation()); 70088c27c554SDimitry Andric Expr *E = new (Context) 70098c27c554SDimitry Andric StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), 7010cd675bb6SDimitry Andric /*FIXME TemplateDepth=*/0); 70110b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(E); 70120b57cec5SDimitry Andric } 70130b57cec5SDimitry Andric 70140b57cec5SDimitry Andric /// Process the expression contained within a decltype. For such expressions, 70150b57cec5SDimitry Andric /// certain semantic checks on temporaries are delayed until this point, and 70160b57cec5SDimitry Andric /// are omitted for the 'topmost' call in the decltype expression. If the 70170b57cec5SDimitry Andric /// topmost call bound a temporary, strip that temporary off the expression. 70180b57cec5SDimitry Andric ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 70190b57cec5SDimitry Andric assert(ExprEvalContexts.back().ExprContext == 70200b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Decltype && 70210b57cec5SDimitry Andric "not in a decltype expression"); 70220b57cec5SDimitry Andric 70230b57cec5SDimitry Andric ExprResult Result = CheckPlaceholderExpr(E); 70240b57cec5SDimitry Andric if (Result.isInvalid()) 70250b57cec5SDimitry Andric return ExprError(); 70260b57cec5SDimitry Andric E = Result.get(); 70270b57cec5SDimitry Andric 70280b57cec5SDimitry Andric // C++11 [expr.call]p11: 70290b57cec5SDimitry Andric // If a function call is a prvalue of object type, 70300b57cec5SDimitry Andric // -- if the function call is either 70310b57cec5SDimitry Andric // -- the operand of a decltype-specifier, or 70320b57cec5SDimitry Andric // -- the right operand of a comma operator that is the operand of a 70330b57cec5SDimitry Andric // decltype-specifier, 70340b57cec5SDimitry Andric // a temporary object is not introduced for the prvalue. 70350b57cec5SDimitry Andric 70360b57cec5SDimitry Andric // Recursively rebuild ParenExprs and comma expressions to strip out the 70370b57cec5SDimitry Andric // outermost CXXBindTemporaryExpr, if any. 70380b57cec5SDimitry Andric if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 70390b57cec5SDimitry Andric ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 70400b57cec5SDimitry Andric if (SubExpr.isInvalid()) 70410b57cec5SDimitry Andric return ExprError(); 70420b57cec5SDimitry Andric if (SubExpr.get() == PE->getSubExpr()) 70430b57cec5SDimitry Andric return E; 70440b57cec5SDimitry Andric return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 70450b57cec5SDimitry Andric } 70460b57cec5SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 70470b57cec5SDimitry Andric if (BO->getOpcode() == BO_Comma) { 70480b57cec5SDimitry Andric ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 70490b57cec5SDimitry Andric if (RHS.isInvalid()) 70500b57cec5SDimitry Andric return ExprError(); 70510b57cec5SDimitry Andric if (RHS.get() == BO->getRHS()) 70520b57cec5SDimitry Andric return E; 70535ffd83dbSDimitry Andric return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma, 70545ffd83dbSDimitry Andric BO->getType(), BO->getValueKind(), 70555ffd83dbSDimitry Andric BO->getObjectKind(), BO->getOperatorLoc(), 70565ffd83dbSDimitry Andric BO->getFPFeatures(getLangOpts())); 70570b57cec5SDimitry Andric } 70580b57cec5SDimitry Andric } 70590b57cec5SDimitry Andric 70600b57cec5SDimitry Andric CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 70610b57cec5SDimitry Andric CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) 70620b57cec5SDimitry Andric : nullptr; 70630b57cec5SDimitry Andric if (TopCall) 70640b57cec5SDimitry Andric E = TopCall; 70650b57cec5SDimitry Andric else 70660b57cec5SDimitry Andric TopBind = nullptr; 70670b57cec5SDimitry Andric 70680b57cec5SDimitry Andric // Disable the special decltype handling now. 70690b57cec5SDimitry Andric ExprEvalContexts.back().ExprContext = 70700b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Other; 70710b57cec5SDimitry Andric 7072a7dea167SDimitry Andric Result = CheckUnevaluatedOperand(E); 7073a7dea167SDimitry Andric if (Result.isInvalid()) 7074a7dea167SDimitry Andric return ExprError(); 7075a7dea167SDimitry Andric E = Result.get(); 7076a7dea167SDimitry Andric 70770b57cec5SDimitry Andric // In MS mode, don't perform any extra checking of call return types within a 70780b57cec5SDimitry Andric // decltype expression. 70790b57cec5SDimitry Andric if (getLangOpts().MSVCCompat) 70800b57cec5SDimitry Andric return E; 70810b57cec5SDimitry Andric 70820b57cec5SDimitry Andric // Perform the semantic checks we delayed until this point. 70830b57cec5SDimitry Andric for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); 70840b57cec5SDimitry Andric I != N; ++I) { 70850b57cec5SDimitry Andric CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; 70860b57cec5SDimitry Andric if (Call == TopCall) 70870b57cec5SDimitry Andric continue; 70880b57cec5SDimitry Andric 70890b57cec5SDimitry Andric if (CheckCallReturnType(Call->getCallReturnType(Context), 70900b57cec5SDimitry Andric Call->getBeginLoc(), Call, Call->getDirectCallee())) 70910b57cec5SDimitry Andric return ExprError(); 70920b57cec5SDimitry Andric } 70930b57cec5SDimitry Andric 70940b57cec5SDimitry Andric // Now all relevant types are complete, check the destructors are accessible 70950b57cec5SDimitry Andric // and non-deleted, and annotate them on the temporaries. 70960b57cec5SDimitry Andric for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); 70970b57cec5SDimitry Andric I != N; ++I) { 70980b57cec5SDimitry Andric CXXBindTemporaryExpr *Bind = 70990b57cec5SDimitry Andric ExprEvalContexts.back().DelayedDecltypeBinds[I]; 71000b57cec5SDimitry Andric if (Bind == TopBind) 71010b57cec5SDimitry Andric continue; 71020b57cec5SDimitry Andric 71030b57cec5SDimitry Andric CXXTemporary *Temp = Bind->getTemporary(); 71040b57cec5SDimitry Andric 71050b57cec5SDimitry Andric CXXRecordDecl *RD = 71060b57cec5SDimitry Andric Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 71070b57cec5SDimitry Andric CXXDestructorDecl *Destructor = LookupDestructor(RD); 71080b57cec5SDimitry Andric Temp->setDestructor(Destructor); 71090b57cec5SDimitry Andric 71100b57cec5SDimitry Andric MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 71110b57cec5SDimitry Andric CheckDestructorAccess(Bind->getExprLoc(), Destructor, 71120b57cec5SDimitry Andric PDiag(diag::err_access_dtor_temp) 71130b57cec5SDimitry Andric << Bind->getType()); 71140b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) 71150b57cec5SDimitry Andric return ExprError(); 71160b57cec5SDimitry Andric 71170b57cec5SDimitry Andric // We need a cleanup, but we don't need to remember the temporary. 71180b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 71190b57cec5SDimitry Andric } 71200b57cec5SDimitry Andric 71210b57cec5SDimitry Andric // Possibly strip off the top CXXBindTemporaryExpr. 71220b57cec5SDimitry Andric return E; 71230b57cec5SDimitry Andric } 71240b57cec5SDimitry Andric 71250b57cec5SDimitry Andric /// Note a set of 'operator->' functions that were used for a member access. 71260b57cec5SDimitry Andric static void noteOperatorArrows(Sema &S, 71270b57cec5SDimitry Andric ArrayRef<FunctionDecl *> OperatorArrows) { 71280b57cec5SDimitry Andric unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; 71290b57cec5SDimitry Andric // FIXME: Make this configurable? 71300b57cec5SDimitry Andric unsigned Limit = 9; 71310b57cec5SDimitry Andric if (OperatorArrows.size() > Limit) { 71320b57cec5SDimitry Andric // Produce Limit-1 normal notes and one 'skipping' note. 71330b57cec5SDimitry Andric SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; 71340b57cec5SDimitry Andric SkipCount = OperatorArrows.size() - (Limit - 1); 71350b57cec5SDimitry Andric } 71360b57cec5SDimitry Andric 71370b57cec5SDimitry Andric for (unsigned I = 0; I < OperatorArrows.size(); /**/) { 71380b57cec5SDimitry Andric if (I == SkipStart) { 71390b57cec5SDimitry Andric S.Diag(OperatorArrows[I]->getLocation(), 71400b57cec5SDimitry Andric diag::note_operator_arrows_suppressed) 71410b57cec5SDimitry Andric << SkipCount; 71420b57cec5SDimitry Andric I += SkipCount; 71430b57cec5SDimitry Andric } else { 71440b57cec5SDimitry Andric S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) 71450b57cec5SDimitry Andric << OperatorArrows[I]->getCallResultType(); 71460b57cec5SDimitry Andric ++I; 71470b57cec5SDimitry Andric } 71480b57cec5SDimitry Andric } 71490b57cec5SDimitry Andric } 71500b57cec5SDimitry Andric 71510b57cec5SDimitry Andric ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, 71520b57cec5SDimitry Andric SourceLocation OpLoc, 71530b57cec5SDimitry Andric tok::TokenKind OpKind, 71540b57cec5SDimitry Andric ParsedType &ObjectType, 71550b57cec5SDimitry Andric bool &MayBePseudoDestructor) { 71560b57cec5SDimitry Andric // Since this might be a postfix expression, get rid of ParenListExprs. 71570b57cec5SDimitry Andric ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 71580b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 71590b57cec5SDimitry Andric Base = Result.get(); 71600b57cec5SDimitry Andric 71610b57cec5SDimitry Andric Result = CheckPlaceholderExpr(Base); 71620b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 71630b57cec5SDimitry Andric Base = Result.get(); 71640b57cec5SDimitry Andric 71650b57cec5SDimitry Andric QualType BaseType = Base->getType(); 71660b57cec5SDimitry Andric MayBePseudoDestructor = false; 71670b57cec5SDimitry Andric if (BaseType->isDependentType()) { 71680b57cec5SDimitry Andric // If we have a pointer to a dependent type and are using the -> operator, 71690b57cec5SDimitry Andric // the object type is the type that the pointer points to. We might still 71700b57cec5SDimitry Andric // have enough information about that type to do something useful. 71710b57cec5SDimitry Andric if (OpKind == tok::arrow) 71720b57cec5SDimitry Andric if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 71730b57cec5SDimitry Andric BaseType = Ptr->getPointeeType(); 71740b57cec5SDimitry Andric 71750b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 71760b57cec5SDimitry Andric MayBePseudoDestructor = true; 71770b57cec5SDimitry Andric return Base; 71780b57cec5SDimitry Andric } 71790b57cec5SDimitry Andric 71800b57cec5SDimitry Andric // C++ [over.match.oper]p8: 71810b57cec5SDimitry Andric // [...] When operator->returns, the operator-> is applied to the value 71820b57cec5SDimitry Andric // returned, with the original second operand. 71830b57cec5SDimitry Andric if (OpKind == tok::arrow) { 71840b57cec5SDimitry Andric QualType StartingType = BaseType; 71850b57cec5SDimitry Andric bool NoArrowOperatorFound = false; 71860b57cec5SDimitry Andric bool FirstIteration = true; 71870b57cec5SDimitry Andric FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); 71880b57cec5SDimitry Andric // The set of types we've considered so far. 71890b57cec5SDimitry Andric llvm::SmallPtrSet<CanQualType,8> CTypes; 71900b57cec5SDimitry Andric SmallVector<FunctionDecl*, 8> OperatorArrows; 71910b57cec5SDimitry Andric CTypes.insert(Context.getCanonicalType(BaseType)); 71920b57cec5SDimitry Andric 71930b57cec5SDimitry Andric while (BaseType->isRecordType()) { 71940b57cec5SDimitry Andric if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { 71950b57cec5SDimitry Andric Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) 71960b57cec5SDimitry Andric << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); 71970b57cec5SDimitry Andric noteOperatorArrows(*this, OperatorArrows); 71980b57cec5SDimitry Andric Diag(OpLoc, diag::note_operator_arrow_depth) 71990b57cec5SDimitry Andric << getLangOpts().ArrowDepth; 72000b57cec5SDimitry Andric return ExprError(); 72010b57cec5SDimitry Andric } 72020b57cec5SDimitry Andric 72030b57cec5SDimitry Andric Result = BuildOverloadedArrowExpr( 72040b57cec5SDimitry Andric S, Base, OpLoc, 72050b57cec5SDimitry Andric // When in a template specialization and on the first loop iteration, 72060b57cec5SDimitry Andric // potentially give the default diagnostic (with the fixit in a 72070b57cec5SDimitry Andric // separate note) instead of having the error reported back to here 72080b57cec5SDimitry Andric // and giving a diagnostic with a fixit attached to the error itself. 72090b57cec5SDimitry Andric (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) 72100b57cec5SDimitry Andric ? nullptr 72110b57cec5SDimitry Andric : &NoArrowOperatorFound); 72120b57cec5SDimitry Andric if (Result.isInvalid()) { 72130b57cec5SDimitry Andric if (NoArrowOperatorFound) { 72140b57cec5SDimitry Andric if (FirstIteration) { 72150b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 72160b57cec5SDimitry Andric << BaseType << 1 << Base->getSourceRange() 72170b57cec5SDimitry Andric << FixItHint::CreateReplacement(OpLoc, "."); 72180b57cec5SDimitry Andric OpKind = tok::period; 72190b57cec5SDimitry Andric break; 72200b57cec5SDimitry Andric } 72210b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 72220b57cec5SDimitry Andric << BaseType << Base->getSourceRange(); 72230b57cec5SDimitry Andric CallExpr *CE = dyn_cast<CallExpr>(Base); 72240b57cec5SDimitry Andric if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { 72250b57cec5SDimitry Andric Diag(CD->getBeginLoc(), 72260b57cec5SDimitry Andric diag::note_member_reference_arrow_from_operator_arrow); 72270b57cec5SDimitry Andric } 72280b57cec5SDimitry Andric } 72290b57cec5SDimitry Andric return ExprError(); 72300b57cec5SDimitry Andric } 72310b57cec5SDimitry Andric Base = Result.get(); 72320b57cec5SDimitry Andric if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 72330b57cec5SDimitry Andric OperatorArrows.push_back(OpCall->getDirectCallee()); 72340b57cec5SDimitry Andric BaseType = Base->getType(); 72350b57cec5SDimitry Andric CanQualType CBaseType = Context.getCanonicalType(BaseType); 72360b57cec5SDimitry Andric if (!CTypes.insert(CBaseType).second) { 72370b57cec5SDimitry Andric Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; 72380b57cec5SDimitry Andric noteOperatorArrows(*this, OperatorArrows); 72390b57cec5SDimitry Andric return ExprError(); 72400b57cec5SDimitry Andric } 72410b57cec5SDimitry Andric FirstIteration = false; 72420b57cec5SDimitry Andric } 72430b57cec5SDimitry Andric 72440b57cec5SDimitry Andric if (OpKind == tok::arrow) { 72450b57cec5SDimitry Andric if (BaseType->isPointerType()) 72460b57cec5SDimitry Andric BaseType = BaseType->getPointeeType(); 72470b57cec5SDimitry Andric else if (auto *AT = Context.getAsArrayType(BaseType)) 72480b57cec5SDimitry Andric BaseType = AT->getElementType(); 72490b57cec5SDimitry Andric } 72500b57cec5SDimitry Andric } 72510b57cec5SDimitry Andric 72520b57cec5SDimitry Andric // Objective-C properties allow "." access on Objective-C pointer types, 72530b57cec5SDimitry Andric // so adjust the base type to the object type itself. 72540b57cec5SDimitry Andric if (BaseType->isObjCObjectPointerType()) 72550b57cec5SDimitry Andric BaseType = BaseType->getPointeeType(); 72560b57cec5SDimitry Andric 72570b57cec5SDimitry Andric // C++ [basic.lookup.classref]p2: 72580b57cec5SDimitry Andric // [...] If the type of the object expression is of pointer to scalar 72590b57cec5SDimitry Andric // type, the unqualified-id is looked up in the context of the complete 72600b57cec5SDimitry Andric // postfix-expression. 72610b57cec5SDimitry Andric // 72620b57cec5SDimitry Andric // This also indicates that we could be parsing a pseudo-destructor-name. 72630b57cec5SDimitry Andric // Note that Objective-C class and object types can be pseudo-destructor 72640b57cec5SDimitry Andric // expressions or normal member (ivar or property) access expressions, and 72650b57cec5SDimitry Andric // it's legal for the type to be incomplete if this is a pseudo-destructor 72660b57cec5SDimitry Andric // call. We'll do more incomplete-type checks later in the lookup process, 72670b57cec5SDimitry Andric // so just skip this check for ObjC types. 72680b57cec5SDimitry Andric if (!BaseType->isRecordType()) { 72690b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 72700b57cec5SDimitry Andric MayBePseudoDestructor = true; 72710b57cec5SDimitry Andric return Base; 72720b57cec5SDimitry Andric } 72730b57cec5SDimitry Andric 72740b57cec5SDimitry Andric // The object type must be complete (or dependent), or 72750b57cec5SDimitry Andric // C++11 [expr.prim.general]p3: 72760b57cec5SDimitry Andric // Unlike the object expression in other contexts, *this is not required to 72770b57cec5SDimitry Andric // be of complete type for purposes of class member access (5.2.5) outside 72780b57cec5SDimitry Andric // the member function body. 72790b57cec5SDimitry Andric if (!BaseType->isDependentType() && 72800b57cec5SDimitry Andric !isThisOutsideMemberFunctionBody(BaseType) && 72810b57cec5SDimitry Andric RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) 72820b57cec5SDimitry Andric return ExprError(); 72830b57cec5SDimitry Andric 72840b57cec5SDimitry Andric // C++ [basic.lookup.classref]p2: 72850b57cec5SDimitry Andric // If the id-expression in a class member access (5.2.5) is an 72860b57cec5SDimitry Andric // unqualified-id, and the type of the object expression is of a class 72870b57cec5SDimitry Andric // type C (or of pointer to a class type C), the unqualified-id is looked 72880b57cec5SDimitry Andric // up in the scope of class C. [...] 72890b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 72900b57cec5SDimitry Andric return Base; 72910b57cec5SDimitry Andric } 72920b57cec5SDimitry Andric 72930b57cec5SDimitry Andric static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, 72940b57cec5SDimitry Andric tok::TokenKind &OpKind, SourceLocation OpLoc) { 72950b57cec5SDimitry Andric if (Base->hasPlaceholderType()) { 72960b57cec5SDimitry Andric ExprResult result = S.CheckPlaceholderExpr(Base); 72970b57cec5SDimitry Andric if (result.isInvalid()) return true; 72980b57cec5SDimitry Andric Base = result.get(); 72990b57cec5SDimitry Andric } 73000b57cec5SDimitry Andric ObjectType = Base->getType(); 73010b57cec5SDimitry Andric 73020b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 73030b57cec5SDimitry Andric // The left-hand side of the dot operator shall be of scalar type. The 73040b57cec5SDimitry Andric // left-hand side of the arrow operator shall be of pointer to scalar type. 73050b57cec5SDimitry Andric // This scalar type is the object type. 73060b57cec5SDimitry Andric // Note that this is rather different from the normal handling for the 73070b57cec5SDimitry Andric // arrow operator. 73080b57cec5SDimitry Andric if (OpKind == tok::arrow) { 7309e8d8bef9SDimitry Andric // The operator requires a prvalue, so perform lvalue conversions. 7310e8d8bef9SDimitry Andric // Only do this if we might plausibly end with a pointer, as otherwise 7311e8d8bef9SDimitry Andric // this was likely to be intended to be a '.'. 7312e8d8bef9SDimitry Andric if (ObjectType->isPointerType() || ObjectType->isArrayType() || 7313e8d8bef9SDimitry Andric ObjectType->isFunctionType()) { 7314e8d8bef9SDimitry Andric ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base); 7315e8d8bef9SDimitry Andric if (BaseResult.isInvalid()) 7316e8d8bef9SDimitry Andric return true; 7317e8d8bef9SDimitry Andric Base = BaseResult.get(); 7318e8d8bef9SDimitry Andric ObjectType = Base->getType(); 7319e8d8bef9SDimitry Andric } 7320e8d8bef9SDimitry Andric 73210b57cec5SDimitry Andric if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 73220b57cec5SDimitry Andric ObjectType = Ptr->getPointeeType(); 73230b57cec5SDimitry Andric } else if (!Base->isTypeDependent()) { 73240b57cec5SDimitry Andric // The user wrote "p->" when they probably meant "p."; fix it. 73250b57cec5SDimitry Andric S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 73260b57cec5SDimitry Andric << ObjectType << true 73270b57cec5SDimitry Andric << FixItHint::CreateReplacement(OpLoc, "."); 73280b57cec5SDimitry Andric if (S.isSFINAEContext()) 73290b57cec5SDimitry Andric return true; 73300b57cec5SDimitry Andric 73310b57cec5SDimitry Andric OpKind = tok::period; 73320b57cec5SDimitry Andric } 73330b57cec5SDimitry Andric } 73340b57cec5SDimitry Andric 73350b57cec5SDimitry Andric return false; 73360b57cec5SDimitry Andric } 73370b57cec5SDimitry Andric 73380b57cec5SDimitry Andric /// Check if it's ok to try and recover dot pseudo destructor calls on 73390b57cec5SDimitry Andric /// pointer objects. 73400b57cec5SDimitry Andric static bool 73410b57cec5SDimitry Andric canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, 73420b57cec5SDimitry Andric QualType DestructedType) { 73430b57cec5SDimitry Andric // If this is a record type, check if its destructor is callable. 73440b57cec5SDimitry Andric if (auto *RD = DestructedType->getAsCXXRecordDecl()) { 73450b57cec5SDimitry Andric if (RD->hasDefinition()) 73460b57cec5SDimitry Andric if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) 73470b57cec5SDimitry Andric return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); 73480b57cec5SDimitry Andric return false; 73490b57cec5SDimitry Andric } 73500b57cec5SDimitry Andric 73510b57cec5SDimitry Andric // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. 73520b57cec5SDimitry Andric return DestructedType->isDependentType() || DestructedType->isScalarType() || 73530b57cec5SDimitry Andric DestructedType->isVectorType(); 73540b57cec5SDimitry Andric } 73550b57cec5SDimitry Andric 73560b57cec5SDimitry Andric ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 73570b57cec5SDimitry Andric SourceLocation OpLoc, 73580b57cec5SDimitry Andric tok::TokenKind OpKind, 73590b57cec5SDimitry Andric const CXXScopeSpec &SS, 73600b57cec5SDimitry Andric TypeSourceInfo *ScopeTypeInfo, 73610b57cec5SDimitry Andric SourceLocation CCLoc, 73620b57cec5SDimitry Andric SourceLocation TildeLoc, 73630b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed) { 73640b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 73650b57cec5SDimitry Andric 73660b57cec5SDimitry Andric QualType ObjectType; 73670b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 73680b57cec5SDimitry Andric return ExprError(); 73690b57cec5SDimitry Andric 73700b57cec5SDimitry Andric if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 73710b57cec5SDimitry Andric !ObjectType->isVectorType()) { 73720b57cec5SDimitry Andric if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) 73730b57cec5SDimitry Andric Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 73740b57cec5SDimitry Andric else { 73750b57cec5SDimitry Andric Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 73760b57cec5SDimitry Andric << ObjectType << Base->getSourceRange(); 73770b57cec5SDimitry Andric return ExprError(); 73780b57cec5SDimitry Andric } 73790b57cec5SDimitry Andric } 73800b57cec5SDimitry Andric 73810b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 73820b57cec5SDimitry Andric // [...] The cv-unqualified versions of the object type and of the type 73830b57cec5SDimitry Andric // designated by the pseudo-destructor-name shall be the same type. 73840b57cec5SDimitry Andric if (DestructedTypeInfo) { 73850b57cec5SDimitry Andric QualType DestructedType = DestructedTypeInfo->getType(); 73860b57cec5SDimitry Andric SourceLocation DestructedTypeStart 73870b57cec5SDimitry Andric = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 73880b57cec5SDimitry Andric if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 73890b57cec5SDimitry Andric if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 73900b57cec5SDimitry Andric // Detect dot pseudo destructor calls on pointer objects, e.g.: 73910b57cec5SDimitry Andric // Foo *foo; 73920b57cec5SDimitry Andric // foo.~Foo(); 73930b57cec5SDimitry Andric if (OpKind == tok::period && ObjectType->isPointerType() && 73940b57cec5SDimitry Andric Context.hasSameUnqualifiedType(DestructedType, 73950b57cec5SDimitry Andric ObjectType->getPointeeType())) { 73960b57cec5SDimitry Andric auto Diagnostic = 73970b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 73980b57cec5SDimitry Andric << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); 73990b57cec5SDimitry Andric 74000b57cec5SDimitry Andric // Issue a fixit only when the destructor is valid. 74010b57cec5SDimitry Andric if (canRecoverDotPseudoDestructorCallsOnPointerObjects( 74020b57cec5SDimitry Andric *this, DestructedType)) 74030b57cec5SDimitry Andric Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); 74040b57cec5SDimitry Andric 74050b57cec5SDimitry Andric // Recover by setting the object type to the destructed type and the 74060b57cec5SDimitry Andric // operator to '->'. 74070b57cec5SDimitry Andric ObjectType = DestructedType; 74080b57cec5SDimitry Andric OpKind = tok::arrow; 74090b57cec5SDimitry Andric } else { 74100b57cec5SDimitry Andric Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 74110b57cec5SDimitry Andric << ObjectType << DestructedType << Base->getSourceRange() 74120b57cec5SDimitry Andric << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 74130b57cec5SDimitry Andric 74140b57cec5SDimitry Andric // Recover by setting the destructed type to the object type. 74150b57cec5SDimitry Andric DestructedType = ObjectType; 74160b57cec5SDimitry Andric DestructedTypeInfo = 74170b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); 74180b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 74190b57cec5SDimitry Andric } 74200b57cec5SDimitry Andric } else if (DestructedType.getObjCLifetime() != 74210b57cec5SDimitry Andric ObjectType.getObjCLifetime()) { 74220b57cec5SDimitry Andric 74230b57cec5SDimitry Andric if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 74240b57cec5SDimitry Andric // Okay: just pretend that the user provided the correctly-qualified 74250b57cec5SDimitry Andric // type. 74260b57cec5SDimitry Andric } else { 74270b57cec5SDimitry Andric Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 74280b57cec5SDimitry Andric << ObjectType << DestructedType << Base->getSourceRange() 74290b57cec5SDimitry Andric << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 74300b57cec5SDimitry Andric } 74310b57cec5SDimitry Andric 74320b57cec5SDimitry Andric // Recover by setting the destructed type to the object type. 74330b57cec5SDimitry Andric DestructedType = ObjectType; 74340b57cec5SDimitry Andric DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 74350b57cec5SDimitry Andric DestructedTypeStart); 74360b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 74370b57cec5SDimitry Andric } 74380b57cec5SDimitry Andric } 74390b57cec5SDimitry Andric } 74400b57cec5SDimitry Andric 74410b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 74420b57cec5SDimitry Andric // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 74430b57cec5SDimitry Andric // form 74440b57cec5SDimitry Andric // 74450b57cec5SDimitry Andric // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 74460b57cec5SDimitry Andric // 74470b57cec5SDimitry Andric // shall designate the same scalar type. 74480b57cec5SDimitry Andric if (ScopeTypeInfo) { 74490b57cec5SDimitry Andric QualType ScopeType = ScopeTypeInfo->getType(); 74500b57cec5SDimitry Andric if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 74510b57cec5SDimitry Andric !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 74520b57cec5SDimitry Andric 74530b57cec5SDimitry Andric Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 74540b57cec5SDimitry Andric diag::err_pseudo_dtor_type_mismatch) 74550b57cec5SDimitry Andric << ObjectType << ScopeType << Base->getSourceRange() 74560b57cec5SDimitry Andric << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 74570b57cec5SDimitry Andric 74580b57cec5SDimitry Andric ScopeType = QualType(); 74590b57cec5SDimitry Andric ScopeTypeInfo = nullptr; 74600b57cec5SDimitry Andric } 74610b57cec5SDimitry Andric } 74620b57cec5SDimitry Andric 74630b57cec5SDimitry Andric Expr *Result 74640b57cec5SDimitry Andric = new (Context) CXXPseudoDestructorExpr(Context, Base, 74650b57cec5SDimitry Andric OpKind == tok::arrow, OpLoc, 74660b57cec5SDimitry Andric SS.getWithLocInContext(Context), 74670b57cec5SDimitry Andric ScopeTypeInfo, 74680b57cec5SDimitry Andric CCLoc, 74690b57cec5SDimitry Andric TildeLoc, 74700b57cec5SDimitry Andric Destructed); 74710b57cec5SDimitry Andric 74720b57cec5SDimitry Andric return Result; 74730b57cec5SDimitry Andric } 74740b57cec5SDimitry Andric 74750b57cec5SDimitry Andric ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 74760b57cec5SDimitry Andric SourceLocation OpLoc, 74770b57cec5SDimitry Andric tok::TokenKind OpKind, 74780b57cec5SDimitry Andric CXXScopeSpec &SS, 74790b57cec5SDimitry Andric UnqualifiedId &FirstTypeName, 74800b57cec5SDimitry Andric SourceLocation CCLoc, 74810b57cec5SDimitry Andric SourceLocation TildeLoc, 74820b57cec5SDimitry Andric UnqualifiedId &SecondTypeName) { 74830b57cec5SDimitry Andric assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 74840b57cec5SDimitry Andric FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 74850b57cec5SDimitry Andric "Invalid first type name in pseudo-destructor"); 74860b57cec5SDimitry Andric assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 74870b57cec5SDimitry Andric SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 74880b57cec5SDimitry Andric "Invalid second type name in pseudo-destructor"); 74890b57cec5SDimitry Andric 74900b57cec5SDimitry Andric QualType ObjectType; 74910b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 74920b57cec5SDimitry Andric return ExprError(); 74930b57cec5SDimitry Andric 74940b57cec5SDimitry Andric // Compute the object type that we should use for name lookup purposes. Only 74950b57cec5SDimitry Andric // record types and dependent types matter. 74960b57cec5SDimitry Andric ParsedType ObjectTypePtrForLookup; 74970b57cec5SDimitry Andric if (!SS.isSet()) { 74980b57cec5SDimitry Andric if (ObjectType->isRecordType()) 74990b57cec5SDimitry Andric ObjectTypePtrForLookup = ParsedType::make(ObjectType); 75000b57cec5SDimitry Andric else if (ObjectType->isDependentType()) 75010b57cec5SDimitry Andric ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 75020b57cec5SDimitry Andric } 75030b57cec5SDimitry Andric 75040b57cec5SDimitry Andric // Convert the name of the type being destructed (following the ~) into a 75050b57cec5SDimitry Andric // type (with source-location information). 75060b57cec5SDimitry Andric QualType DestructedType; 75070b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = nullptr; 75080b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed; 75090b57cec5SDimitry Andric if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 75100b57cec5SDimitry Andric ParsedType T = getTypeName(*SecondTypeName.Identifier, 75110b57cec5SDimitry Andric SecondTypeName.StartLocation, 75120b57cec5SDimitry Andric S, &SS, true, false, ObjectTypePtrForLookup, 75130b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 75140b57cec5SDimitry Andric if (!T && 75150b57cec5SDimitry Andric ((SS.isSet() && !computeDeclContext(SS, false)) || 75160b57cec5SDimitry Andric (!SS.isSet() && ObjectType->isDependentType()))) { 75170b57cec5SDimitry Andric // The name of the type being destroyed is a dependent name, and we 75180b57cec5SDimitry Andric // couldn't find anything useful in scope. Just store the identifier and 75190b57cec5SDimitry Andric // it's location, and we'll perform (qualified) name lookup again at 75200b57cec5SDimitry Andric // template instantiation time. 75210b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 75220b57cec5SDimitry Andric SecondTypeName.StartLocation); 75230b57cec5SDimitry Andric } else if (!T) { 75240b57cec5SDimitry Andric Diag(SecondTypeName.StartLocation, 75250b57cec5SDimitry Andric diag::err_pseudo_dtor_destructor_non_type) 75260b57cec5SDimitry Andric << SecondTypeName.Identifier << ObjectType; 75270b57cec5SDimitry Andric if (isSFINAEContext()) 75280b57cec5SDimitry Andric return ExprError(); 75290b57cec5SDimitry Andric 75300b57cec5SDimitry Andric // Recover by assuming we had the right type all along. 75310b57cec5SDimitry Andric DestructedType = ObjectType; 75320b57cec5SDimitry Andric } else 75330b57cec5SDimitry Andric DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 75340b57cec5SDimitry Andric } else { 75350b57cec5SDimitry Andric // Resolve the template-id to a type. 75360b57cec5SDimitry Andric TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 75370b57cec5SDimitry Andric ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 75380b57cec5SDimitry Andric TemplateId->NumArgs); 75390b57cec5SDimitry Andric TypeResult T = ActOnTemplateIdType(S, 754055e4f9d5SDimitry Andric SS, 75410b57cec5SDimitry Andric TemplateId->TemplateKWLoc, 75420b57cec5SDimitry Andric TemplateId->Template, 75430b57cec5SDimitry Andric TemplateId->Name, 75440b57cec5SDimitry Andric TemplateId->TemplateNameLoc, 75450b57cec5SDimitry Andric TemplateId->LAngleLoc, 75460b57cec5SDimitry Andric TemplateArgsPtr, 75470b57cec5SDimitry Andric TemplateId->RAngleLoc, 75480b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 75490b57cec5SDimitry Andric if (T.isInvalid() || !T.get()) { 75500b57cec5SDimitry Andric // Recover by assuming we had the right type all along. 75510b57cec5SDimitry Andric DestructedType = ObjectType; 75520b57cec5SDimitry Andric } else 75530b57cec5SDimitry Andric DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 75540b57cec5SDimitry Andric } 75550b57cec5SDimitry Andric 75560b57cec5SDimitry Andric // If we've performed some kind of recovery, (re-)build the type source 75570b57cec5SDimitry Andric // information. 75580b57cec5SDimitry Andric if (!DestructedType.isNull()) { 75590b57cec5SDimitry Andric if (!DestructedTypeInfo) 75600b57cec5SDimitry Andric DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 75610b57cec5SDimitry Andric SecondTypeName.StartLocation); 75620b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 75630b57cec5SDimitry Andric } 75640b57cec5SDimitry Andric 75650b57cec5SDimitry Andric // Convert the name of the scope type (the type prior to '::') into a type. 75660b57cec5SDimitry Andric TypeSourceInfo *ScopeTypeInfo = nullptr; 75670b57cec5SDimitry Andric QualType ScopeType; 75680b57cec5SDimitry Andric if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 75690b57cec5SDimitry Andric FirstTypeName.Identifier) { 75700b57cec5SDimitry Andric if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 75710b57cec5SDimitry Andric ParsedType T = getTypeName(*FirstTypeName.Identifier, 75720b57cec5SDimitry Andric FirstTypeName.StartLocation, 75730b57cec5SDimitry Andric S, &SS, true, false, ObjectTypePtrForLookup, 75740b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 75750b57cec5SDimitry Andric if (!T) { 75760b57cec5SDimitry Andric Diag(FirstTypeName.StartLocation, 75770b57cec5SDimitry Andric diag::err_pseudo_dtor_destructor_non_type) 75780b57cec5SDimitry Andric << FirstTypeName.Identifier << ObjectType; 75790b57cec5SDimitry Andric 75800b57cec5SDimitry Andric if (isSFINAEContext()) 75810b57cec5SDimitry Andric return ExprError(); 75820b57cec5SDimitry Andric 75830b57cec5SDimitry Andric // Just drop this type. It's unnecessary anyway. 75840b57cec5SDimitry Andric ScopeType = QualType(); 75850b57cec5SDimitry Andric } else 75860b57cec5SDimitry Andric ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 75870b57cec5SDimitry Andric } else { 75880b57cec5SDimitry Andric // Resolve the template-id to a type. 75890b57cec5SDimitry Andric TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 75900b57cec5SDimitry Andric ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 75910b57cec5SDimitry Andric TemplateId->NumArgs); 75920b57cec5SDimitry Andric TypeResult T = ActOnTemplateIdType(S, 759355e4f9d5SDimitry Andric SS, 75940b57cec5SDimitry Andric TemplateId->TemplateKWLoc, 75950b57cec5SDimitry Andric TemplateId->Template, 75960b57cec5SDimitry Andric TemplateId->Name, 75970b57cec5SDimitry Andric TemplateId->TemplateNameLoc, 75980b57cec5SDimitry Andric TemplateId->LAngleLoc, 75990b57cec5SDimitry Andric TemplateArgsPtr, 76000b57cec5SDimitry Andric TemplateId->RAngleLoc, 76010b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 76020b57cec5SDimitry Andric if (T.isInvalid() || !T.get()) { 76030b57cec5SDimitry Andric // Recover by dropping this type. 76040b57cec5SDimitry Andric ScopeType = QualType(); 76050b57cec5SDimitry Andric } else 76060b57cec5SDimitry Andric ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 76070b57cec5SDimitry Andric } 76080b57cec5SDimitry Andric } 76090b57cec5SDimitry Andric 76100b57cec5SDimitry Andric if (!ScopeType.isNull() && !ScopeTypeInfo) 76110b57cec5SDimitry Andric ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 76120b57cec5SDimitry Andric FirstTypeName.StartLocation); 76130b57cec5SDimitry Andric 76140b57cec5SDimitry Andric 76150b57cec5SDimitry Andric return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 76160b57cec5SDimitry Andric ScopeTypeInfo, CCLoc, TildeLoc, 76170b57cec5SDimitry Andric Destructed); 76180b57cec5SDimitry Andric } 76190b57cec5SDimitry Andric 76200b57cec5SDimitry Andric ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 76210b57cec5SDimitry Andric SourceLocation OpLoc, 76220b57cec5SDimitry Andric tok::TokenKind OpKind, 76230b57cec5SDimitry Andric SourceLocation TildeLoc, 76240b57cec5SDimitry Andric const DeclSpec& DS) { 76250b57cec5SDimitry Andric QualType ObjectType; 76260b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 76270b57cec5SDimitry Andric return ExprError(); 76280b57cec5SDimitry Andric 7629e8d8bef9SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { 7630e8d8bef9SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 7631e8d8bef9SDimitry Andric return true; 7632e8d8bef9SDimitry Andric } 7633e8d8bef9SDimitry Andric 76340b57cec5SDimitry Andric QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(), 76350b57cec5SDimitry Andric false); 76360b57cec5SDimitry Andric 76370b57cec5SDimitry Andric TypeLocBuilder TLB; 76380b57cec5SDimitry Andric DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 76390b57cec5SDimitry Andric DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); 76400b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 76410b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 76420b57cec5SDimitry Andric 76430b57cec5SDimitry Andric return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 76440b57cec5SDimitry Andric nullptr, SourceLocation(), TildeLoc, 76450b57cec5SDimitry Andric Destructed); 76460b57cec5SDimitry Andric } 76470b57cec5SDimitry Andric 76480b57cec5SDimitry Andric ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 76490b57cec5SDimitry Andric CXXConversionDecl *Method, 76500b57cec5SDimitry Andric bool HadMultipleCandidates) { 76510b57cec5SDimitry Andric // Convert the expression to match the conversion function's implicit object 76520b57cec5SDimitry Andric // parameter. 76530b57cec5SDimitry Andric ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 76540b57cec5SDimitry Andric FoundDecl, Method); 76550b57cec5SDimitry Andric if (Exp.isInvalid()) 76560b57cec5SDimitry Andric return true; 76570b57cec5SDimitry Andric 76580b57cec5SDimitry Andric if (Method->getParent()->isLambda() && 76590b57cec5SDimitry Andric Method->getConversionType()->isBlockPointerType()) { 7660a7dea167SDimitry Andric // This is a lambda conversion to block pointer; check if the argument 76610b57cec5SDimitry Andric // was a LambdaExpr. 76620b57cec5SDimitry Andric Expr *SubE = E; 76630b57cec5SDimitry Andric CastExpr *CE = dyn_cast<CastExpr>(SubE); 76640b57cec5SDimitry Andric if (CE && CE->getCastKind() == CK_NoOp) 76650b57cec5SDimitry Andric SubE = CE->getSubExpr(); 76660b57cec5SDimitry Andric SubE = SubE->IgnoreParens(); 76670b57cec5SDimitry Andric if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 76680b57cec5SDimitry Andric SubE = BE->getSubExpr(); 76690b57cec5SDimitry Andric if (isa<LambdaExpr>(SubE)) { 76700b57cec5SDimitry Andric // For the conversion to block pointer on a lambda expression, we 76710b57cec5SDimitry Andric // construct a special BlockLiteral instead; this doesn't really make 76720b57cec5SDimitry Andric // a difference in ARC, but outside of ARC the resulting block literal 76730b57cec5SDimitry Andric // follows the normal lifetime rules for block literals instead of being 76740b57cec5SDimitry Andric // autoreleased. 76750b57cec5SDimitry Andric PushExpressionEvaluationContext( 76760b57cec5SDimitry Andric ExpressionEvaluationContext::PotentiallyEvaluated); 76770b57cec5SDimitry Andric ExprResult BlockExp = BuildBlockForLambdaConversion( 76780b57cec5SDimitry Andric Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); 76790b57cec5SDimitry Andric PopExpressionEvaluationContext(); 76800b57cec5SDimitry Andric 76815ffd83dbSDimitry Andric // FIXME: This note should be produced by a CodeSynthesisContext. 76820b57cec5SDimitry Andric if (BlockExp.isInvalid()) 76830b57cec5SDimitry Andric Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); 76840b57cec5SDimitry Andric return BlockExp; 76850b57cec5SDimitry Andric } 76860b57cec5SDimitry Andric } 76870b57cec5SDimitry Andric 76880b57cec5SDimitry Andric MemberExpr *ME = 76890b57cec5SDimitry Andric BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), 76900b57cec5SDimitry Andric NestedNameSpecifierLoc(), SourceLocation(), Method, 76910b57cec5SDimitry Andric DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), 76920b57cec5SDimitry Andric HadMultipleCandidates, DeclarationNameInfo(), 76930b57cec5SDimitry Andric Context.BoundMemberTy, VK_RValue, OK_Ordinary); 76940b57cec5SDimitry Andric 76950b57cec5SDimitry Andric QualType ResultType = Method->getReturnType(); 76960b57cec5SDimitry Andric ExprValueKind VK = Expr::getValueKindForType(ResultType); 76970b57cec5SDimitry Andric ResultType = ResultType.getNonLValueExprType(Context); 76980b57cec5SDimitry Andric 76990b57cec5SDimitry Andric CXXMemberCallExpr *CE = CXXMemberCallExpr::Create( 7700e8d8bef9SDimitry Andric Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(), 7701e8d8bef9SDimitry Andric CurFPFeatureOverrides()); 77020b57cec5SDimitry Andric 77030b57cec5SDimitry Andric if (CheckFunctionCall(Method, CE, 77040b57cec5SDimitry Andric Method->getType()->castAs<FunctionProtoType>())) 77050b57cec5SDimitry Andric return ExprError(); 77060b57cec5SDimitry Andric 77070b57cec5SDimitry Andric return CE; 77080b57cec5SDimitry Andric } 77090b57cec5SDimitry Andric 77100b57cec5SDimitry Andric ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 77110b57cec5SDimitry Andric SourceLocation RParen) { 77120b57cec5SDimitry Andric // If the operand is an unresolved lookup expression, the expression is ill- 77130b57cec5SDimitry Andric // formed per [over.over]p1, because overloaded function names cannot be used 77140b57cec5SDimitry Andric // without arguments except in explicit contexts. 77150b57cec5SDimitry Andric ExprResult R = CheckPlaceholderExpr(Operand); 77160b57cec5SDimitry Andric if (R.isInvalid()) 77170b57cec5SDimitry Andric return R; 77180b57cec5SDimitry Andric 7719a7dea167SDimitry Andric R = CheckUnevaluatedOperand(R.get()); 7720a7dea167SDimitry Andric if (R.isInvalid()) 7721a7dea167SDimitry Andric return ExprError(); 7722a7dea167SDimitry Andric 77230b57cec5SDimitry Andric Operand = R.get(); 77240b57cec5SDimitry Andric 7725e8d8bef9SDimitry Andric if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && 7726e8d8bef9SDimitry Andric Operand->HasSideEffects(Context, false)) { 77270b57cec5SDimitry Andric // The expression operand for noexcept is in an unevaluated expression 77280b57cec5SDimitry Andric // context, so side effects could result in unintended consequences. 77290b57cec5SDimitry Andric Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); 77300b57cec5SDimitry Andric } 77310b57cec5SDimitry Andric 77320b57cec5SDimitry Andric CanThrowResult CanThrow = canThrow(Operand); 77330b57cec5SDimitry Andric return new (Context) 77340b57cec5SDimitry Andric CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); 77350b57cec5SDimitry Andric } 77360b57cec5SDimitry Andric 77370b57cec5SDimitry Andric ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 77380b57cec5SDimitry Andric Expr *Operand, SourceLocation RParen) { 77390b57cec5SDimitry Andric return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 77400b57cec5SDimitry Andric } 77410b57cec5SDimitry Andric 77420b57cec5SDimitry Andric /// Perform the conversions required for an expression used in a 77430b57cec5SDimitry Andric /// context that ignores the result. 77440b57cec5SDimitry Andric ExprResult Sema::IgnoredValueConversions(Expr *E) { 77450b57cec5SDimitry Andric if (E->hasPlaceholderType()) { 77460b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(E); 77470b57cec5SDimitry Andric if (result.isInvalid()) return E; 77480b57cec5SDimitry Andric E = result.get(); 77490b57cec5SDimitry Andric } 77500b57cec5SDimitry Andric 77510b57cec5SDimitry Andric // C99 6.3.2.1: 77520b57cec5SDimitry Andric // [Except in specific positions,] an lvalue that does not have 77530b57cec5SDimitry Andric // array type is converted to the value stored in the 77540b57cec5SDimitry Andric // designated object (and is no longer an lvalue). 77550b57cec5SDimitry Andric if (E->isRValue()) { 77560b57cec5SDimitry Andric // In C, function designators (i.e. expressions of function type) 77570b57cec5SDimitry Andric // are r-values, but we still want to do function-to-pointer decay 77580b57cec5SDimitry Andric // on them. This is both technically correct and convenient for 77590b57cec5SDimitry Andric // some clients. 77600b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 77610b57cec5SDimitry Andric return DefaultFunctionArrayConversion(E); 77620b57cec5SDimitry Andric 77630b57cec5SDimitry Andric return E; 77640b57cec5SDimitry Andric } 77650b57cec5SDimitry Andric 77660b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 77670b57cec5SDimitry Andric // The C++11 standard defines the notion of a discarded-value expression; 77680b57cec5SDimitry Andric // normally, we don't need to do anything to handle it, but if it is a 77690b57cec5SDimitry Andric // volatile lvalue with a special form, we perform an lvalue-to-rvalue 77700b57cec5SDimitry Andric // conversion. 77715ffd83dbSDimitry Andric if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { 77720b57cec5SDimitry Andric ExprResult Res = DefaultLvalueConversion(E); 77730b57cec5SDimitry Andric if (Res.isInvalid()) 77740b57cec5SDimitry Andric return E; 77750b57cec5SDimitry Andric E = Res.get(); 7776a7dea167SDimitry Andric } else { 7777a7dea167SDimitry Andric // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 7778a7dea167SDimitry Andric // it occurs as a discarded-value expression. 7779a7dea167SDimitry Andric CheckUnusedVolatileAssignment(E); 7780a7dea167SDimitry Andric } 77810b57cec5SDimitry Andric 77820b57cec5SDimitry Andric // C++1z: 77830b57cec5SDimitry Andric // If the expression is a prvalue after this optional conversion, the 77840b57cec5SDimitry Andric // temporary materialization conversion is applied. 77850b57cec5SDimitry Andric // 77860b57cec5SDimitry Andric // We skip this step: IR generation is able to synthesize the storage for 77870b57cec5SDimitry Andric // itself in the aggregate case, and adding the extra node to the AST is 77880b57cec5SDimitry Andric // just clutter. 77890b57cec5SDimitry Andric // FIXME: We don't emit lifetime markers for the temporaries due to this. 77900b57cec5SDimitry Andric // FIXME: Do any other AST consumers care about this? 77910b57cec5SDimitry Andric return E; 77920b57cec5SDimitry Andric } 77930b57cec5SDimitry Andric 77940b57cec5SDimitry Andric // GCC seems to also exclude expressions of incomplete enum type. 77950b57cec5SDimitry Andric if (const EnumType *T = E->getType()->getAs<EnumType>()) { 77960b57cec5SDimitry Andric if (!T->getDecl()->isComplete()) { 77970b57cec5SDimitry Andric // FIXME: stupid workaround for a codegen bug! 77980b57cec5SDimitry Andric E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); 77990b57cec5SDimitry Andric return E; 78000b57cec5SDimitry Andric } 78010b57cec5SDimitry Andric } 78020b57cec5SDimitry Andric 78030b57cec5SDimitry Andric ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 78040b57cec5SDimitry Andric if (Res.isInvalid()) 78050b57cec5SDimitry Andric return E; 78060b57cec5SDimitry Andric E = Res.get(); 78070b57cec5SDimitry Andric 78080b57cec5SDimitry Andric if (!E->getType()->isVoidType()) 78090b57cec5SDimitry Andric RequireCompleteType(E->getExprLoc(), E->getType(), 78100b57cec5SDimitry Andric diag::err_incomplete_type); 78110b57cec5SDimitry Andric return E; 78120b57cec5SDimitry Andric } 78130b57cec5SDimitry Andric 7814a7dea167SDimitry Andric ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { 7815a7dea167SDimitry Andric // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 7816a7dea167SDimitry Andric // it occurs as an unevaluated operand. 7817a7dea167SDimitry Andric CheckUnusedVolatileAssignment(E); 7818a7dea167SDimitry Andric 7819a7dea167SDimitry Andric return E; 7820a7dea167SDimitry Andric } 7821a7dea167SDimitry Andric 78220b57cec5SDimitry Andric // If we can unambiguously determine whether Var can never be used 78230b57cec5SDimitry Andric // in a constant expression, return true. 78240b57cec5SDimitry Andric // - if the variable and its initializer are non-dependent, then 78250b57cec5SDimitry Andric // we can unambiguously check if the variable is a constant expression. 78260b57cec5SDimitry Andric // - if the initializer is not value dependent - we can determine whether 78270b57cec5SDimitry Andric // it can be used to initialize a constant expression. If Init can not 78280b57cec5SDimitry Andric // be used to initialize a constant expression we conclude that Var can 78290b57cec5SDimitry Andric // never be a constant expression. 78300b57cec5SDimitry Andric // - FXIME: if the initializer is dependent, we can still do some analysis and 78310b57cec5SDimitry Andric // identify certain cases unambiguously as non-const by using a Visitor: 78320b57cec5SDimitry Andric // - such as those that involve odr-use of a ParmVarDecl, involve a new 78330b57cec5SDimitry Andric // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... 78340b57cec5SDimitry Andric static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 78350b57cec5SDimitry Andric ASTContext &Context) { 78360b57cec5SDimitry Andric if (isa<ParmVarDecl>(Var)) return true; 78370b57cec5SDimitry Andric const VarDecl *DefVD = nullptr; 78380b57cec5SDimitry Andric 78390b57cec5SDimitry Andric // If there is no initializer - this can not be a constant expression. 78400b57cec5SDimitry Andric if (!Var->getAnyInitializer(DefVD)) return true; 78410b57cec5SDimitry Andric assert(DefVD); 78420b57cec5SDimitry Andric if (DefVD->isWeak()) return false; 78430b57cec5SDimitry Andric EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 78440b57cec5SDimitry Andric 78450b57cec5SDimitry Andric Expr *Init = cast<Expr>(Eval->Value); 78460b57cec5SDimitry Andric 78470b57cec5SDimitry Andric if (Var->getType()->isDependentType() || Init->isValueDependent()) { 78480b57cec5SDimitry Andric // FIXME: Teach the constant evaluator to deal with the non-dependent parts 78490b57cec5SDimitry Andric // of value-dependent expressions, and use it here to determine whether the 78500b57cec5SDimitry Andric // initializer is a potential constant expression. 78510b57cec5SDimitry Andric return false; 78520b57cec5SDimitry Andric } 78530b57cec5SDimitry Andric 78540b57cec5SDimitry Andric return !Var->isUsableInConstantExpressions(Context); 78550b57cec5SDimitry Andric } 78560b57cec5SDimitry Andric 78570b57cec5SDimitry Andric /// Check if the current lambda has any potential captures 78580b57cec5SDimitry Andric /// that must be captured by any of its enclosing lambdas that are ready to 78590b57cec5SDimitry Andric /// capture. If there is a lambda that can capture a nested 78600b57cec5SDimitry Andric /// potential-capture, go ahead and do so. Also, check to see if any 78610b57cec5SDimitry Andric /// variables are uncaptureable or do not involve an odr-use so do not 78620b57cec5SDimitry Andric /// need to be captured. 78630b57cec5SDimitry Andric 78640b57cec5SDimitry Andric static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( 78650b57cec5SDimitry Andric Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { 78660b57cec5SDimitry Andric 78670b57cec5SDimitry Andric assert(!S.isUnevaluatedContext()); 78680b57cec5SDimitry Andric assert(S.CurContext->isDependentContext()); 78690b57cec5SDimitry Andric #ifndef NDEBUG 78700b57cec5SDimitry Andric DeclContext *DC = S.CurContext; 78710b57cec5SDimitry Andric while (DC && isa<CapturedDecl>(DC)) 78720b57cec5SDimitry Andric DC = DC->getParent(); 78730b57cec5SDimitry Andric assert( 78740b57cec5SDimitry Andric CurrentLSI->CallOperator == DC && 78750b57cec5SDimitry Andric "The current call operator must be synchronized with Sema's CurContext"); 78760b57cec5SDimitry Andric #endif // NDEBUG 78770b57cec5SDimitry Andric 78780b57cec5SDimitry Andric const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); 78790b57cec5SDimitry Andric 78800b57cec5SDimitry Andric // All the potentially captureable variables in the current nested 78810b57cec5SDimitry Andric // lambda (within a generic outer lambda), must be captured by an 78820b57cec5SDimitry Andric // outer lambda that is enclosed within a non-dependent context. 78830b57cec5SDimitry Andric CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) { 78840b57cec5SDimitry Andric // If the variable is clearly identified as non-odr-used and the full 78850b57cec5SDimitry Andric // expression is not instantiation dependent, only then do we not 78860b57cec5SDimitry Andric // need to check enclosing lambda's for speculative captures. 78870b57cec5SDimitry Andric // For e.g.: 78880b57cec5SDimitry Andric // Even though 'x' is not odr-used, it should be captured. 78890b57cec5SDimitry Andric // int test() { 78900b57cec5SDimitry Andric // const int x = 10; 78910b57cec5SDimitry Andric // auto L = [=](auto a) { 78920b57cec5SDimitry Andric // (void) +x + a; 78930b57cec5SDimitry Andric // }; 78940b57cec5SDimitry Andric // } 78950b57cec5SDimitry Andric if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && 78960b57cec5SDimitry Andric !IsFullExprInstantiationDependent) 78970b57cec5SDimitry Andric return; 78980b57cec5SDimitry Andric 78990b57cec5SDimitry Andric // If we have a capture-capable lambda for the variable, go ahead and 79000b57cec5SDimitry Andric // capture the variable in that lambda (and all its enclosing lambdas). 79010b57cec5SDimitry Andric if (const Optional<unsigned> Index = 79020b57cec5SDimitry Andric getStackIndexOfNearestEnclosingCaptureCapableLambda( 79030b57cec5SDimitry Andric S.FunctionScopes, Var, S)) 79040b57cec5SDimitry Andric S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), 79050b57cec5SDimitry Andric Index.getValue()); 79060b57cec5SDimitry Andric const bool IsVarNeverAConstantExpression = 79070b57cec5SDimitry Andric VariableCanNeverBeAConstantExpression(Var, S.Context); 79080b57cec5SDimitry Andric if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { 79090b57cec5SDimitry Andric // This full expression is not instantiation dependent or the variable 79100b57cec5SDimitry Andric // can not be used in a constant expression - which means 79110b57cec5SDimitry Andric // this variable must be odr-used here, so diagnose a 79120b57cec5SDimitry Andric // capture violation early, if the variable is un-captureable. 79130b57cec5SDimitry Andric // This is purely for diagnosing errors early. Otherwise, this 79140b57cec5SDimitry Andric // error would get diagnosed when the lambda becomes capture ready. 79150b57cec5SDimitry Andric QualType CaptureType, DeclRefType; 79160b57cec5SDimitry Andric SourceLocation ExprLoc = VarExpr->getExprLoc(); 79170b57cec5SDimitry Andric if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 79180b57cec5SDimitry Andric /*EllipsisLoc*/ SourceLocation(), 79190b57cec5SDimitry Andric /*BuildAndDiagnose*/false, CaptureType, 79200b57cec5SDimitry Andric DeclRefType, nullptr)) { 79210b57cec5SDimitry Andric // We will never be able to capture this variable, and we need 79220b57cec5SDimitry Andric // to be able to in any and all instantiations, so diagnose it. 79230b57cec5SDimitry Andric S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 79240b57cec5SDimitry Andric /*EllipsisLoc*/ SourceLocation(), 79250b57cec5SDimitry Andric /*BuildAndDiagnose*/true, CaptureType, 79260b57cec5SDimitry Andric DeclRefType, nullptr); 79270b57cec5SDimitry Andric } 79280b57cec5SDimitry Andric } 79290b57cec5SDimitry Andric }); 79300b57cec5SDimitry Andric 79310b57cec5SDimitry Andric // Check if 'this' needs to be captured. 79320b57cec5SDimitry Andric if (CurrentLSI->hasPotentialThisCapture()) { 79330b57cec5SDimitry Andric // If we have a capture-capable lambda for 'this', go ahead and capture 79340b57cec5SDimitry Andric // 'this' in that lambda (and all its enclosing lambdas). 79350b57cec5SDimitry Andric if (const Optional<unsigned> Index = 79360b57cec5SDimitry Andric getStackIndexOfNearestEnclosingCaptureCapableLambda( 79370b57cec5SDimitry Andric S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { 79380b57cec5SDimitry Andric const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); 79390b57cec5SDimitry Andric S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, 79400b57cec5SDimitry Andric /*Explicit*/ false, /*BuildAndDiagnose*/ true, 79410b57cec5SDimitry Andric &FunctionScopeIndexOfCapturableLambda); 79420b57cec5SDimitry Andric } 79430b57cec5SDimitry Andric } 79440b57cec5SDimitry Andric 79450b57cec5SDimitry Andric // Reset all the potential captures at the end of each full-expression. 79460b57cec5SDimitry Andric CurrentLSI->clearPotentialCaptures(); 79470b57cec5SDimitry Andric } 79480b57cec5SDimitry Andric 79490b57cec5SDimitry Andric static ExprResult attemptRecovery(Sema &SemaRef, 79500b57cec5SDimitry Andric const TypoCorrectionConsumer &Consumer, 79510b57cec5SDimitry Andric const TypoCorrection &TC) { 79520b57cec5SDimitry Andric LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), 79530b57cec5SDimitry Andric Consumer.getLookupResult().getLookupKind()); 79540b57cec5SDimitry Andric const CXXScopeSpec *SS = Consumer.getSS(); 79550b57cec5SDimitry Andric CXXScopeSpec NewSS; 79560b57cec5SDimitry Andric 79570b57cec5SDimitry Andric // Use an approprate CXXScopeSpec for building the expr. 79580b57cec5SDimitry Andric if (auto *NNS = TC.getCorrectionSpecifier()) 79590b57cec5SDimitry Andric NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); 79600b57cec5SDimitry Andric else if (SS && !TC.WillReplaceSpecifier()) 79610b57cec5SDimitry Andric NewSS = *SS; 79620b57cec5SDimitry Andric 79630b57cec5SDimitry Andric if (auto *ND = TC.getFoundDecl()) { 79640b57cec5SDimitry Andric R.setLookupName(ND->getDeclName()); 79650b57cec5SDimitry Andric R.addDecl(ND); 79660b57cec5SDimitry Andric if (ND->isCXXClassMember()) { 79670b57cec5SDimitry Andric // Figure out the correct naming class to add to the LookupResult. 79680b57cec5SDimitry Andric CXXRecordDecl *Record = nullptr; 79690b57cec5SDimitry Andric if (auto *NNS = TC.getCorrectionSpecifier()) 79700b57cec5SDimitry Andric Record = NNS->getAsType()->getAsCXXRecordDecl(); 79710b57cec5SDimitry Andric if (!Record) 79720b57cec5SDimitry Andric Record = 79730b57cec5SDimitry Andric dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); 79740b57cec5SDimitry Andric if (Record) 79750b57cec5SDimitry Andric R.setNamingClass(Record); 79760b57cec5SDimitry Andric 79770b57cec5SDimitry Andric // Detect and handle the case where the decl might be an implicit 79780b57cec5SDimitry Andric // member. 79790b57cec5SDimitry Andric bool MightBeImplicitMember; 79800b57cec5SDimitry Andric if (!Consumer.isAddressOfOperand()) 79810b57cec5SDimitry Andric MightBeImplicitMember = true; 79820b57cec5SDimitry Andric else if (!NewSS.isEmpty()) 79830b57cec5SDimitry Andric MightBeImplicitMember = false; 79840b57cec5SDimitry Andric else if (R.isOverloadedResult()) 79850b57cec5SDimitry Andric MightBeImplicitMember = false; 79860b57cec5SDimitry Andric else if (R.isUnresolvableResult()) 79870b57cec5SDimitry Andric MightBeImplicitMember = true; 79880b57cec5SDimitry Andric else 79890b57cec5SDimitry Andric MightBeImplicitMember = isa<FieldDecl>(ND) || 79900b57cec5SDimitry Andric isa<IndirectFieldDecl>(ND) || 79910b57cec5SDimitry Andric isa<MSPropertyDecl>(ND); 79920b57cec5SDimitry Andric 79930b57cec5SDimitry Andric if (MightBeImplicitMember) 79940b57cec5SDimitry Andric return SemaRef.BuildPossibleImplicitMemberExpr( 79950b57cec5SDimitry Andric NewSS, /*TemplateKWLoc*/ SourceLocation(), R, 79960b57cec5SDimitry Andric /*TemplateArgs*/ nullptr, /*S*/ nullptr); 79970b57cec5SDimitry Andric } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 79980b57cec5SDimitry Andric return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), 79990b57cec5SDimitry Andric Ivar->getIdentifier()); 80000b57cec5SDimitry Andric } 80010b57cec5SDimitry Andric } 80020b57cec5SDimitry Andric 80030b57cec5SDimitry Andric return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, 80040b57cec5SDimitry Andric /*AcceptInvalidDecl*/ true); 80050b57cec5SDimitry Andric } 80060b57cec5SDimitry Andric 80070b57cec5SDimitry Andric namespace { 80080b57cec5SDimitry Andric class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { 80090b57cec5SDimitry Andric llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; 80100b57cec5SDimitry Andric 80110b57cec5SDimitry Andric public: 80120b57cec5SDimitry Andric explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) 80130b57cec5SDimitry Andric : TypoExprs(TypoExprs) {} 80140b57cec5SDimitry Andric bool VisitTypoExpr(TypoExpr *TE) { 80150b57cec5SDimitry Andric TypoExprs.insert(TE); 80160b57cec5SDimitry Andric return true; 80170b57cec5SDimitry Andric } 80180b57cec5SDimitry Andric }; 80190b57cec5SDimitry Andric 80200b57cec5SDimitry Andric class TransformTypos : public TreeTransform<TransformTypos> { 80210b57cec5SDimitry Andric typedef TreeTransform<TransformTypos> BaseTransform; 80220b57cec5SDimitry Andric 80230b57cec5SDimitry Andric VarDecl *InitDecl; // A decl to avoid as a correction because it is in the 80240b57cec5SDimitry Andric // process of being initialized. 80250b57cec5SDimitry Andric llvm::function_ref<ExprResult(Expr *)> ExprFilter; 80260b57cec5SDimitry Andric llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; 80270b57cec5SDimitry Andric llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; 80280b57cec5SDimitry Andric llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; 80290b57cec5SDimitry Andric 80300b57cec5SDimitry Andric /// Emit diagnostics for all of the TypoExprs encountered. 8031a7dea167SDimitry Andric /// 80320b57cec5SDimitry Andric /// If the TypoExprs were successfully corrected, then the diagnostics should 80330b57cec5SDimitry Andric /// suggest the corrections. Otherwise the diagnostics will not suggest 80340b57cec5SDimitry Andric /// anything (having been passed an empty TypoCorrection). 8035a7dea167SDimitry Andric /// 8036a7dea167SDimitry Andric /// If we've failed to correct due to ambiguous corrections, we need to 8037a7dea167SDimitry Andric /// be sure to pass empty corrections and replacements. Otherwise it's 8038a7dea167SDimitry Andric /// possible that the Consumer has a TypoCorrection that failed to ambiguity 8039a7dea167SDimitry Andric /// and we don't want to report those diagnostics. 8040a7dea167SDimitry Andric void EmitAllDiagnostics(bool IsAmbiguous) { 80410b57cec5SDimitry Andric for (TypoExpr *TE : TypoExprs) { 80420b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(TE); 80430b57cec5SDimitry Andric if (State.DiagHandler) { 8044a7dea167SDimitry Andric TypoCorrection TC = IsAmbiguous 8045a7dea167SDimitry Andric ? TypoCorrection() : State.Consumer->getCurrentCorrection(); 8046a7dea167SDimitry Andric ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; 80470b57cec5SDimitry Andric 80480b57cec5SDimitry Andric // Extract the NamedDecl from the transformed TypoExpr and add it to the 80490b57cec5SDimitry Andric // TypoCorrection, replacing the existing decls. This ensures the right 80500b57cec5SDimitry Andric // NamedDecl is used in diagnostics e.g. in the case where overload 80510b57cec5SDimitry Andric // resolution was used to select one from several possible decls that 80520b57cec5SDimitry Andric // had been stored in the TypoCorrection. 80530b57cec5SDimitry Andric if (auto *ND = getDeclFromExpr( 80540b57cec5SDimitry Andric Replacement.isInvalid() ? nullptr : Replacement.get())) 80550b57cec5SDimitry Andric TC.setCorrectionDecl(ND); 80560b57cec5SDimitry Andric 80570b57cec5SDimitry Andric State.DiagHandler(TC); 80580b57cec5SDimitry Andric } 80590b57cec5SDimitry Andric SemaRef.clearDelayedTypo(TE); 80600b57cec5SDimitry Andric } 80610b57cec5SDimitry Andric } 80620b57cec5SDimitry Andric 8063590d96feSDimitry Andric /// Try to advance the typo correction state of the first unfinished TypoExpr. 8064590d96feSDimitry Andric /// We allow advancement of the correction stream by removing it from the 8065590d96feSDimitry Andric /// TransformCache which allows `TransformTypoExpr` to advance during the 8066590d96feSDimitry Andric /// next transformation attempt. 8067590d96feSDimitry Andric /// 8068590d96feSDimitry Andric /// Any substitution attempts for the previous TypoExprs (which must have been 8069590d96feSDimitry Andric /// finished) will need to be retried since it's possible that they will now 8070590d96feSDimitry Andric /// be invalid given the latest advancement. 8071590d96feSDimitry Andric /// 8072590d96feSDimitry Andric /// We need to be sure that we're making progress - it's possible that the 8073590d96feSDimitry Andric /// tree is so malformed that the transform never makes it to the 8074590d96feSDimitry Andric /// `TransformTypoExpr`. 8075590d96feSDimitry Andric /// 8076590d96feSDimitry Andric /// Returns true if there are any untried correction combinations. 80770b57cec5SDimitry Andric bool CheckAndAdvanceTypoExprCorrectionStreams() { 80780b57cec5SDimitry Andric for (auto TE : TypoExprs) { 80790b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(TE); 80800b57cec5SDimitry Andric TransformCache.erase(TE); 8081590d96feSDimitry Andric if (!State.Consumer->hasMadeAnyCorrectionProgress()) 8082590d96feSDimitry Andric return false; 80830b57cec5SDimitry Andric if (!State.Consumer->finished()) 80840b57cec5SDimitry Andric return true; 80850b57cec5SDimitry Andric State.Consumer->resetCorrectionStream(); 80860b57cec5SDimitry Andric } 80870b57cec5SDimitry Andric return false; 80880b57cec5SDimitry Andric } 80890b57cec5SDimitry Andric 80900b57cec5SDimitry Andric NamedDecl *getDeclFromExpr(Expr *E) { 80910b57cec5SDimitry Andric if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) 80920b57cec5SDimitry Andric E = OverloadResolution[OE]; 80930b57cec5SDimitry Andric 80940b57cec5SDimitry Andric if (!E) 80950b57cec5SDimitry Andric return nullptr; 80960b57cec5SDimitry Andric if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 80970b57cec5SDimitry Andric return DRE->getFoundDecl(); 80980b57cec5SDimitry Andric if (auto *ME = dyn_cast<MemberExpr>(E)) 80990b57cec5SDimitry Andric return ME->getFoundDecl(); 81000b57cec5SDimitry Andric // FIXME: Add any other expr types that could be be seen by the delayed typo 81010b57cec5SDimitry Andric // correction TreeTransform for which the corresponding TypoCorrection could 81020b57cec5SDimitry Andric // contain multiple decls. 81030b57cec5SDimitry Andric return nullptr; 81040b57cec5SDimitry Andric } 81050b57cec5SDimitry Andric 81060b57cec5SDimitry Andric ExprResult TryTransform(Expr *E) { 81070b57cec5SDimitry Andric Sema::SFINAETrap Trap(SemaRef); 81080b57cec5SDimitry Andric ExprResult Res = TransformExpr(E); 81090b57cec5SDimitry Andric if (Trap.hasErrorOccurred() || Res.isInvalid()) 81100b57cec5SDimitry Andric return ExprError(); 81110b57cec5SDimitry Andric 81120b57cec5SDimitry Andric return ExprFilter(Res.get()); 81130b57cec5SDimitry Andric } 81140b57cec5SDimitry Andric 8115a7dea167SDimitry Andric // Since correcting typos may intoduce new TypoExprs, this function 8116a7dea167SDimitry Andric // checks for new TypoExprs and recurses if it finds any. Note that it will 8117a7dea167SDimitry Andric // only succeed if it is able to correct all typos in the given expression. 8118a7dea167SDimitry Andric ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { 8119a7dea167SDimitry Andric if (Res.isInvalid()) { 8120a7dea167SDimitry Andric return Res; 8121a7dea167SDimitry Andric } 8122a7dea167SDimitry Andric // Check to see if any new TypoExprs were created. If so, we need to recurse 8123a7dea167SDimitry Andric // to check their validity. 8124a7dea167SDimitry Andric Expr *FixedExpr = Res.get(); 8125a7dea167SDimitry Andric 8126a7dea167SDimitry Andric auto SavedTypoExprs = std::move(TypoExprs); 8127a7dea167SDimitry Andric auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); 8128a7dea167SDimitry Andric TypoExprs.clear(); 8129a7dea167SDimitry Andric AmbiguousTypoExprs.clear(); 8130a7dea167SDimitry Andric 8131a7dea167SDimitry Andric FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); 8132a7dea167SDimitry Andric if (!TypoExprs.empty()) { 8133a7dea167SDimitry Andric // Recurse to handle newly created TypoExprs. If we're not able to 8134a7dea167SDimitry Andric // handle them, discard these TypoExprs. 8135a7dea167SDimitry Andric ExprResult RecurResult = 8136a7dea167SDimitry Andric RecursiveTransformLoop(FixedExpr, IsAmbiguous); 8137a7dea167SDimitry Andric if (RecurResult.isInvalid()) { 8138a7dea167SDimitry Andric Res = ExprError(); 8139a7dea167SDimitry Andric // Recursive corrections didn't work, wipe them away and don't add 8140a7dea167SDimitry Andric // them to the TypoExprs set. Remove them from Sema's TypoExpr list 8141a7dea167SDimitry Andric // since we don't want to clear them twice. Note: it's possible the 8142a7dea167SDimitry Andric // TypoExprs were created recursively and thus won't be in our 8143a7dea167SDimitry Andric // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. 8144a7dea167SDimitry Andric auto &SemaTypoExprs = SemaRef.TypoExprs; 8145a7dea167SDimitry Andric for (auto TE : TypoExprs) { 8146a7dea167SDimitry Andric TransformCache.erase(TE); 8147a7dea167SDimitry Andric SemaRef.clearDelayedTypo(TE); 8148a7dea167SDimitry Andric 8149a7dea167SDimitry Andric auto SI = find(SemaTypoExprs, TE); 8150a7dea167SDimitry Andric if (SI != SemaTypoExprs.end()) { 8151a7dea167SDimitry Andric SemaTypoExprs.erase(SI); 8152a7dea167SDimitry Andric } 8153a7dea167SDimitry Andric } 8154a7dea167SDimitry Andric } else { 8155a7dea167SDimitry Andric // TypoExpr is valid: add newly created TypoExprs since we were 8156a7dea167SDimitry Andric // able to correct them. 8157a7dea167SDimitry Andric Res = RecurResult; 8158a7dea167SDimitry Andric SavedTypoExprs.set_union(TypoExprs); 8159a7dea167SDimitry Andric } 8160a7dea167SDimitry Andric } 8161a7dea167SDimitry Andric 8162a7dea167SDimitry Andric TypoExprs = std::move(SavedTypoExprs); 8163a7dea167SDimitry Andric AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); 8164a7dea167SDimitry Andric 8165a7dea167SDimitry Andric return Res; 8166a7dea167SDimitry Andric } 8167a7dea167SDimitry Andric 8168a7dea167SDimitry Andric // Try to transform the given expression, looping through the correction 8169a7dea167SDimitry Andric // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. 8170a7dea167SDimitry Andric // 8171a7dea167SDimitry Andric // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to 8172a7dea167SDimitry Andric // true and this method immediately will return an `ExprError`. 8173a7dea167SDimitry Andric ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { 8174a7dea167SDimitry Andric ExprResult Res; 8175a7dea167SDimitry Andric auto SavedTypoExprs = std::move(SemaRef.TypoExprs); 8176a7dea167SDimitry Andric SemaRef.TypoExprs.clear(); 8177a7dea167SDimitry Andric 8178a7dea167SDimitry Andric while (true) { 8179a7dea167SDimitry Andric Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 8180a7dea167SDimitry Andric 8181a7dea167SDimitry Andric // Recursion encountered an ambiguous correction. This means that our 8182a7dea167SDimitry Andric // correction itself is ambiguous, so stop now. 8183a7dea167SDimitry Andric if (IsAmbiguous) 8184a7dea167SDimitry Andric break; 8185a7dea167SDimitry Andric 8186a7dea167SDimitry Andric // If the transform is still valid after checking for any new typos, 8187a7dea167SDimitry Andric // it's good to go. 8188a7dea167SDimitry Andric if (!Res.isInvalid()) 8189a7dea167SDimitry Andric break; 8190a7dea167SDimitry Andric 8191a7dea167SDimitry Andric // The transform was invalid, see if we have any TypoExprs with untried 8192a7dea167SDimitry Andric // correction candidates. 8193a7dea167SDimitry Andric if (!CheckAndAdvanceTypoExprCorrectionStreams()) 8194a7dea167SDimitry Andric break; 8195a7dea167SDimitry Andric } 8196a7dea167SDimitry Andric 8197a7dea167SDimitry Andric // If we found a valid result, double check to make sure it's not ambiguous. 8198a7dea167SDimitry Andric if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { 8199480093f4SDimitry Andric auto SavedTransformCache = 8200480093f4SDimitry Andric llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); 8201480093f4SDimitry Andric 8202a7dea167SDimitry Andric // Ensure none of the TypoExprs have multiple typo correction candidates 8203a7dea167SDimitry Andric // with the same edit length that pass all the checks and filters. 8204a7dea167SDimitry Andric while (!AmbiguousTypoExprs.empty()) { 8205a7dea167SDimitry Andric auto TE = AmbiguousTypoExprs.back(); 8206a7dea167SDimitry Andric 8207a7dea167SDimitry Andric // TryTransform itself can create new Typos, adding them to the TypoExpr map 8208a7dea167SDimitry Andric // and invalidating our TypoExprState, so always fetch it instead of storing. 8209a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); 8210a7dea167SDimitry Andric 8211a7dea167SDimitry Andric TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); 8212a7dea167SDimitry Andric TypoCorrection Next; 8213a7dea167SDimitry Andric do { 8214a7dea167SDimitry Andric // Fetch the next correction by erasing the typo from the cache and calling 8215a7dea167SDimitry Andric // `TryTransform` which will iterate through corrections in 8216a7dea167SDimitry Andric // `TransformTypoExpr`. 8217a7dea167SDimitry Andric TransformCache.erase(TE); 8218a7dea167SDimitry Andric ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 8219a7dea167SDimitry Andric 8220a7dea167SDimitry Andric if (!AmbigRes.isInvalid() || IsAmbiguous) { 8221a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); 8222a7dea167SDimitry Andric SavedTransformCache.erase(TE); 8223a7dea167SDimitry Andric Res = ExprError(); 8224a7dea167SDimitry Andric IsAmbiguous = true; 8225a7dea167SDimitry Andric break; 8226a7dea167SDimitry Andric } 8227a7dea167SDimitry Andric } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && 8228a7dea167SDimitry Andric Next.getEditDistance(false) == TC.getEditDistance(false)); 8229a7dea167SDimitry Andric 8230a7dea167SDimitry Andric if (IsAmbiguous) 8231a7dea167SDimitry Andric break; 8232a7dea167SDimitry Andric 8233a7dea167SDimitry Andric AmbiguousTypoExprs.remove(TE); 8234a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); 8235a7dea167SDimitry Andric } 8236a7dea167SDimitry Andric TransformCache = std::move(SavedTransformCache); 8237a7dea167SDimitry Andric } 8238a7dea167SDimitry Andric 8239a7dea167SDimitry Andric // Wipe away any newly created TypoExprs that we don't know about. Since we 8240a7dea167SDimitry Andric // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only 8241a7dea167SDimitry Andric // possible if a `TypoExpr` is created during a transformation but then 8242a7dea167SDimitry Andric // fails before we can discover it. 8243a7dea167SDimitry Andric auto &SemaTypoExprs = SemaRef.TypoExprs; 8244a7dea167SDimitry Andric for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { 8245a7dea167SDimitry Andric auto TE = *Iterator; 8246a7dea167SDimitry Andric auto FI = find(TypoExprs, TE); 8247a7dea167SDimitry Andric if (FI != TypoExprs.end()) { 8248a7dea167SDimitry Andric Iterator++; 8249a7dea167SDimitry Andric continue; 8250a7dea167SDimitry Andric } 8251a7dea167SDimitry Andric SemaRef.clearDelayedTypo(TE); 8252a7dea167SDimitry Andric Iterator = SemaTypoExprs.erase(Iterator); 8253a7dea167SDimitry Andric } 8254a7dea167SDimitry Andric SemaRef.TypoExprs = std::move(SavedTypoExprs); 8255a7dea167SDimitry Andric 8256a7dea167SDimitry Andric return Res; 8257a7dea167SDimitry Andric } 8258a7dea167SDimitry Andric 82590b57cec5SDimitry Andric public: 82600b57cec5SDimitry Andric TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) 82610b57cec5SDimitry Andric : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} 82620b57cec5SDimitry Andric 82630b57cec5SDimitry Andric ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, 82640b57cec5SDimitry Andric MultiExprArg Args, 82650b57cec5SDimitry Andric SourceLocation RParenLoc, 82660b57cec5SDimitry Andric Expr *ExecConfig = nullptr) { 82670b57cec5SDimitry Andric auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, 82680b57cec5SDimitry Andric RParenLoc, ExecConfig); 82690b57cec5SDimitry Andric if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { 82700b57cec5SDimitry Andric if (Result.isUsable()) { 82710b57cec5SDimitry Andric Expr *ResultCall = Result.get(); 82720b57cec5SDimitry Andric if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) 82730b57cec5SDimitry Andric ResultCall = BE->getSubExpr(); 82740b57cec5SDimitry Andric if (auto *CE = dyn_cast<CallExpr>(ResultCall)) 82750b57cec5SDimitry Andric OverloadResolution[OE] = CE->getCallee(); 82760b57cec5SDimitry Andric } 82770b57cec5SDimitry Andric } 82780b57cec5SDimitry Andric return Result; 82790b57cec5SDimitry Andric } 82800b57cec5SDimitry Andric 82810b57cec5SDimitry Andric ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } 82820b57cec5SDimitry Andric 82830b57cec5SDimitry Andric ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } 82840b57cec5SDimitry Andric 82850b57cec5SDimitry Andric ExprResult Transform(Expr *E) { 8286a7dea167SDimitry Andric bool IsAmbiguous = false; 8287a7dea167SDimitry Andric ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); 82880b57cec5SDimitry Andric 82890b57cec5SDimitry Andric if (!Res.isUsable()) 82900b57cec5SDimitry Andric FindTypoExprs(TypoExprs).TraverseStmt(E); 82910b57cec5SDimitry Andric 8292a7dea167SDimitry Andric EmitAllDiagnostics(IsAmbiguous); 82930b57cec5SDimitry Andric 82940b57cec5SDimitry Andric return Res; 82950b57cec5SDimitry Andric } 82960b57cec5SDimitry Andric 82970b57cec5SDimitry Andric ExprResult TransformTypoExpr(TypoExpr *E) { 82980b57cec5SDimitry Andric // If the TypoExpr hasn't been seen before, record it. Otherwise, return the 82990b57cec5SDimitry Andric // cached transformation result if there is one and the TypoExpr isn't the 83000b57cec5SDimitry Andric // first one that was encountered. 83010b57cec5SDimitry Andric auto &CacheEntry = TransformCache[E]; 83020b57cec5SDimitry Andric if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { 83030b57cec5SDimitry Andric return CacheEntry; 83040b57cec5SDimitry Andric } 83050b57cec5SDimitry Andric 83060b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(E); 83070b57cec5SDimitry Andric assert(State.Consumer && "Cannot transform a cleared TypoExpr"); 83080b57cec5SDimitry Andric 83090b57cec5SDimitry Andric // For the first TypoExpr and an uncached TypoExpr, find the next likely 83100b57cec5SDimitry Andric // typo correction and return it. 83110b57cec5SDimitry Andric while (TypoCorrection TC = State.Consumer->getNextCorrection()) { 83120b57cec5SDimitry Andric if (InitDecl && TC.getFoundDecl() == InitDecl) 83130b57cec5SDimitry Andric continue; 83140b57cec5SDimitry Andric // FIXME: If we would typo-correct to an invalid declaration, it's 83150b57cec5SDimitry Andric // probably best to just suppress all errors from this typo correction. 83160b57cec5SDimitry Andric ExprResult NE = State.RecoveryHandler ? 83170b57cec5SDimitry Andric State.RecoveryHandler(SemaRef, E, TC) : 83180b57cec5SDimitry Andric attemptRecovery(SemaRef, *State.Consumer, TC); 83190b57cec5SDimitry Andric if (!NE.isInvalid()) { 83200b57cec5SDimitry Andric // Check whether there may be a second viable correction with the same 83210b57cec5SDimitry Andric // edit distance; if so, remember this TypoExpr may have an ambiguous 83220b57cec5SDimitry Andric // correction so it can be more thoroughly vetted later. 83230b57cec5SDimitry Andric TypoCorrection Next; 83240b57cec5SDimitry Andric if ((Next = State.Consumer->peekNextCorrection()) && 83250b57cec5SDimitry Andric Next.getEditDistance(false) == TC.getEditDistance(false)) { 83260b57cec5SDimitry Andric AmbiguousTypoExprs.insert(E); 83270b57cec5SDimitry Andric } else { 83280b57cec5SDimitry Andric AmbiguousTypoExprs.remove(E); 83290b57cec5SDimitry Andric } 83300b57cec5SDimitry Andric assert(!NE.isUnset() && 83310b57cec5SDimitry Andric "Typo was transformed into a valid-but-null ExprResult"); 83320b57cec5SDimitry Andric return CacheEntry = NE; 83330b57cec5SDimitry Andric } 83340b57cec5SDimitry Andric } 83350b57cec5SDimitry Andric return CacheEntry = ExprError(); 83360b57cec5SDimitry Andric } 83370b57cec5SDimitry Andric }; 83380b57cec5SDimitry Andric } 83390b57cec5SDimitry Andric 83400b57cec5SDimitry Andric ExprResult 83410b57cec5SDimitry Andric Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, 83425ffd83dbSDimitry Andric bool RecoverUncorrectedTypos, 83430b57cec5SDimitry Andric llvm::function_ref<ExprResult(Expr *)> Filter) { 83440b57cec5SDimitry Andric // If the current evaluation context indicates there are uncorrected typos 83450b57cec5SDimitry Andric // and the current expression isn't guaranteed to not have typos, try to 83460b57cec5SDimitry Andric // resolve any TypoExpr nodes that might be in the expression. 83470b57cec5SDimitry Andric if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && 83480b57cec5SDimitry Andric (E->isTypeDependent() || E->isValueDependent() || 83490b57cec5SDimitry Andric E->isInstantiationDependent())) { 83500b57cec5SDimitry Andric auto TyposResolved = DelayedTypos.size(); 83510b57cec5SDimitry Andric auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); 83520b57cec5SDimitry Andric TyposResolved -= DelayedTypos.size(); 83530b57cec5SDimitry Andric if (Result.isInvalid() || Result.get() != E) { 83540b57cec5SDimitry Andric ExprEvalContexts.back().NumTypos -= TyposResolved; 83555ffd83dbSDimitry Andric if (Result.isInvalid() && RecoverUncorrectedTypos) { 83565ffd83dbSDimitry Andric struct TyposReplace : TreeTransform<TyposReplace> { 83575ffd83dbSDimitry Andric TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {} 83585ffd83dbSDimitry Andric ExprResult TransformTypoExpr(clang::TypoExpr *E) { 83595ffd83dbSDimitry Andric return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(), 83605ffd83dbSDimitry Andric E->getEndLoc(), {}); 83615ffd83dbSDimitry Andric } 83625ffd83dbSDimitry Andric } TT(*this); 83635ffd83dbSDimitry Andric return TT.TransformExpr(E); 83645ffd83dbSDimitry Andric } 83650b57cec5SDimitry Andric return Result; 83660b57cec5SDimitry Andric } 83670b57cec5SDimitry Andric assert(TyposResolved == 0 && "Corrected typo but got same Expr back?"); 83680b57cec5SDimitry Andric } 83690b57cec5SDimitry Andric return E; 83700b57cec5SDimitry Andric } 83710b57cec5SDimitry Andric 83720b57cec5SDimitry Andric ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, 83730b57cec5SDimitry Andric bool DiscardedValue, 83740b57cec5SDimitry Andric bool IsConstexpr) { 83750b57cec5SDimitry Andric ExprResult FullExpr = FE; 83760b57cec5SDimitry Andric 83770b57cec5SDimitry Andric if (!FullExpr.get()) 83780b57cec5SDimitry Andric return ExprError(); 83790b57cec5SDimitry Andric 83800b57cec5SDimitry Andric if (DiagnoseUnexpandedParameterPack(FullExpr.get())) 83810b57cec5SDimitry Andric return ExprError(); 83820b57cec5SDimitry Andric 83830b57cec5SDimitry Andric if (DiscardedValue) { 83840b57cec5SDimitry Andric // Top-level expressions default to 'id' when we're in a debugger. 83850b57cec5SDimitry Andric if (getLangOpts().DebuggerCastResultToId && 83860b57cec5SDimitry Andric FullExpr.get()->getType() == Context.UnknownAnyTy) { 83870b57cec5SDimitry Andric FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); 83880b57cec5SDimitry Andric if (FullExpr.isInvalid()) 83890b57cec5SDimitry Andric return ExprError(); 83900b57cec5SDimitry Andric } 83910b57cec5SDimitry Andric 83920b57cec5SDimitry Andric FullExpr = CheckPlaceholderExpr(FullExpr.get()); 83930b57cec5SDimitry Andric if (FullExpr.isInvalid()) 83940b57cec5SDimitry Andric return ExprError(); 83950b57cec5SDimitry Andric 83960b57cec5SDimitry Andric FullExpr = IgnoredValueConversions(FullExpr.get()); 83970b57cec5SDimitry Andric if (FullExpr.isInvalid()) 83980b57cec5SDimitry Andric return ExprError(); 83990b57cec5SDimitry Andric 84000b57cec5SDimitry Andric DiagnoseUnusedExprResult(FullExpr.get()); 84010b57cec5SDimitry Andric } 84020b57cec5SDimitry Andric 84035ffd83dbSDimitry Andric FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr, 84045ffd83dbSDimitry Andric /*RecoverUncorrectedTypos=*/true); 84050b57cec5SDimitry Andric if (FullExpr.isInvalid()) 84060b57cec5SDimitry Andric return ExprError(); 84070b57cec5SDimitry Andric 84080b57cec5SDimitry Andric CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); 84090b57cec5SDimitry Andric 84100b57cec5SDimitry Andric // At the end of this full expression (which could be a deeply nested 84110b57cec5SDimitry Andric // lambda), if there is a potential capture within the nested lambda, 84120b57cec5SDimitry Andric // have the outer capture-able lambda try and capture it. 84130b57cec5SDimitry Andric // Consider the following code: 84140b57cec5SDimitry Andric // void f(int, int); 84150b57cec5SDimitry Andric // void f(const int&, double); 84160b57cec5SDimitry Andric // void foo() { 84170b57cec5SDimitry Andric // const int x = 10, y = 20; 84180b57cec5SDimitry Andric // auto L = [=](auto a) { 84190b57cec5SDimitry Andric // auto M = [=](auto b) { 84200b57cec5SDimitry Andric // f(x, b); <-- requires x to be captured by L and M 84210b57cec5SDimitry Andric // f(y, a); <-- requires y to be captured by L, but not all Ms 84220b57cec5SDimitry Andric // }; 84230b57cec5SDimitry Andric // }; 84240b57cec5SDimitry Andric // } 84250b57cec5SDimitry Andric 84260b57cec5SDimitry Andric // FIXME: Also consider what happens for something like this that involves 84270b57cec5SDimitry Andric // the gnu-extension statement-expressions or even lambda-init-captures: 84280b57cec5SDimitry Andric // void f() { 84290b57cec5SDimitry Andric // const int n = 0; 84300b57cec5SDimitry Andric // auto L = [&](auto a) { 84310b57cec5SDimitry Andric // +n + ({ 0; a; }); 84320b57cec5SDimitry Andric // }; 84330b57cec5SDimitry Andric // } 84340b57cec5SDimitry Andric // 84350b57cec5SDimitry Andric // Here, we see +n, and then the full-expression 0; ends, so we don't 84360b57cec5SDimitry Andric // capture n (and instead remove it from our list of potential captures), 84370b57cec5SDimitry Andric // and then the full-expression +n + ({ 0; }); ends, but it's too late 84380b57cec5SDimitry Andric // for us to see that we need to capture n after all. 84390b57cec5SDimitry Andric 84400b57cec5SDimitry Andric LambdaScopeInfo *const CurrentLSI = 84410b57cec5SDimitry Andric getCurLambda(/*IgnoreCapturedRegions=*/true); 84420b57cec5SDimitry Andric // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 84430b57cec5SDimitry Andric // even if CurContext is not a lambda call operator. Refer to that Bug Report 84440b57cec5SDimitry Andric // for an example of the code that might cause this asynchrony. 84450b57cec5SDimitry Andric // By ensuring we are in the context of a lambda's call operator 84460b57cec5SDimitry Andric // we can fix the bug (we only need to check whether we need to capture 84470b57cec5SDimitry Andric // if we are within a lambda's body); but per the comments in that 84480b57cec5SDimitry Andric // PR, a proper fix would entail : 84490b57cec5SDimitry Andric // "Alternative suggestion: 84500b57cec5SDimitry Andric // - Add to Sema an integer holding the smallest (outermost) scope 84510b57cec5SDimitry Andric // index that we are *lexically* within, and save/restore/set to 84520b57cec5SDimitry Andric // FunctionScopes.size() in InstantiatingTemplate's 84530b57cec5SDimitry Andric // constructor/destructor. 84540b57cec5SDimitry Andric // - Teach the handful of places that iterate over FunctionScopes to 84550b57cec5SDimitry Andric // stop at the outermost enclosing lexical scope." 84560b57cec5SDimitry Andric DeclContext *DC = CurContext; 84570b57cec5SDimitry Andric while (DC && isa<CapturedDecl>(DC)) 84580b57cec5SDimitry Andric DC = DC->getParent(); 84590b57cec5SDimitry Andric const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); 84600b57cec5SDimitry Andric if (IsInLambdaDeclContext && CurrentLSI && 84610b57cec5SDimitry Andric CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) 84620b57cec5SDimitry Andric CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, 84630b57cec5SDimitry Andric *this); 84640b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(FullExpr); 84650b57cec5SDimitry Andric } 84660b57cec5SDimitry Andric 84670b57cec5SDimitry Andric StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 84680b57cec5SDimitry Andric if (!FullStmt) return StmtError(); 84690b57cec5SDimitry Andric 84700b57cec5SDimitry Andric return MaybeCreateStmtWithCleanups(FullStmt); 84710b57cec5SDimitry Andric } 84720b57cec5SDimitry Andric 84730b57cec5SDimitry Andric Sema::IfExistsResult 84740b57cec5SDimitry Andric Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 84750b57cec5SDimitry Andric CXXScopeSpec &SS, 84760b57cec5SDimitry Andric const DeclarationNameInfo &TargetNameInfo) { 84770b57cec5SDimitry Andric DeclarationName TargetName = TargetNameInfo.getName(); 84780b57cec5SDimitry Andric if (!TargetName) 84790b57cec5SDimitry Andric return IER_DoesNotExist; 84800b57cec5SDimitry Andric 84810b57cec5SDimitry Andric // If the name itself is dependent, then the result is dependent. 84820b57cec5SDimitry Andric if (TargetName.isDependentName()) 84830b57cec5SDimitry Andric return IER_Dependent; 84840b57cec5SDimitry Andric 84850b57cec5SDimitry Andric // Do the redeclaration lookup in the current scope. 84860b57cec5SDimitry Andric LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 84870b57cec5SDimitry Andric Sema::NotForRedeclaration); 84880b57cec5SDimitry Andric LookupParsedName(R, S, &SS); 84890b57cec5SDimitry Andric R.suppressDiagnostics(); 84900b57cec5SDimitry Andric 84910b57cec5SDimitry Andric switch (R.getResultKind()) { 84920b57cec5SDimitry Andric case LookupResult::Found: 84930b57cec5SDimitry Andric case LookupResult::FoundOverloaded: 84940b57cec5SDimitry Andric case LookupResult::FoundUnresolvedValue: 84950b57cec5SDimitry Andric case LookupResult::Ambiguous: 84960b57cec5SDimitry Andric return IER_Exists; 84970b57cec5SDimitry Andric 84980b57cec5SDimitry Andric case LookupResult::NotFound: 84990b57cec5SDimitry Andric return IER_DoesNotExist; 85000b57cec5SDimitry Andric 85010b57cec5SDimitry Andric case LookupResult::NotFoundInCurrentInstantiation: 85020b57cec5SDimitry Andric return IER_Dependent; 85030b57cec5SDimitry Andric } 85040b57cec5SDimitry Andric 85050b57cec5SDimitry Andric llvm_unreachable("Invalid LookupResult Kind!"); 85060b57cec5SDimitry Andric } 85070b57cec5SDimitry Andric 85080b57cec5SDimitry Andric Sema::IfExistsResult 85090b57cec5SDimitry Andric Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 85100b57cec5SDimitry Andric bool IsIfExists, CXXScopeSpec &SS, 85110b57cec5SDimitry Andric UnqualifiedId &Name) { 85120b57cec5SDimitry Andric DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 85130b57cec5SDimitry Andric 85140b57cec5SDimitry Andric // Check for an unexpanded parameter pack. 85150b57cec5SDimitry Andric auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; 85160b57cec5SDimitry Andric if (DiagnoseUnexpandedParameterPack(SS, UPPC) || 85170b57cec5SDimitry Andric DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) 85180b57cec5SDimitry Andric return IER_Error; 85190b57cec5SDimitry Andric 85200b57cec5SDimitry Andric return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 85210b57cec5SDimitry Andric } 852255e4f9d5SDimitry Andric 852355e4f9d5SDimitry Andric concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { 852455e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/true, 852555e4f9d5SDimitry Andric /*NoexceptLoc=*/SourceLocation(), 852655e4f9d5SDimitry Andric /*ReturnTypeRequirement=*/{}); 852755e4f9d5SDimitry Andric } 852855e4f9d5SDimitry Andric 852955e4f9d5SDimitry Andric concepts::Requirement * 853055e4f9d5SDimitry Andric Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, 853155e4f9d5SDimitry Andric SourceLocation NameLoc, IdentifierInfo *TypeName, 853255e4f9d5SDimitry Andric TemplateIdAnnotation *TemplateId) { 853355e4f9d5SDimitry Andric assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && 853455e4f9d5SDimitry Andric "Exactly one of TypeName and TemplateId must be specified."); 853555e4f9d5SDimitry Andric TypeSourceInfo *TSI = nullptr; 853655e4f9d5SDimitry Andric if (TypeName) { 853755e4f9d5SDimitry Andric QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc, 853855e4f9d5SDimitry Andric SS.getWithLocInContext(Context), *TypeName, 853955e4f9d5SDimitry Andric NameLoc, &TSI, /*DeducedTypeContext=*/false); 854055e4f9d5SDimitry Andric if (T.isNull()) 854155e4f9d5SDimitry Andric return nullptr; 854255e4f9d5SDimitry Andric } else { 854355e4f9d5SDimitry Andric ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), 854455e4f9d5SDimitry Andric TemplateId->NumArgs); 854555e4f9d5SDimitry Andric TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS, 854655e4f9d5SDimitry Andric TemplateId->TemplateKWLoc, 854755e4f9d5SDimitry Andric TemplateId->Template, TemplateId->Name, 854855e4f9d5SDimitry Andric TemplateId->TemplateNameLoc, 854955e4f9d5SDimitry Andric TemplateId->LAngleLoc, ArgsPtr, 855055e4f9d5SDimitry Andric TemplateId->RAngleLoc); 855155e4f9d5SDimitry Andric if (T.isInvalid()) 855255e4f9d5SDimitry Andric return nullptr; 855355e4f9d5SDimitry Andric if (GetTypeFromParser(T.get(), &TSI).isNull()) 855455e4f9d5SDimitry Andric return nullptr; 855555e4f9d5SDimitry Andric } 855655e4f9d5SDimitry Andric return BuildTypeRequirement(TSI); 855755e4f9d5SDimitry Andric } 855855e4f9d5SDimitry Andric 855955e4f9d5SDimitry Andric concepts::Requirement * 856055e4f9d5SDimitry Andric Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { 856155e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, 856255e4f9d5SDimitry Andric /*ReturnTypeRequirement=*/{}); 856355e4f9d5SDimitry Andric } 856455e4f9d5SDimitry Andric 856555e4f9d5SDimitry Andric concepts::Requirement * 856655e4f9d5SDimitry Andric Sema::ActOnCompoundRequirement( 856755e4f9d5SDimitry Andric Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 856855e4f9d5SDimitry Andric TemplateIdAnnotation *TypeConstraint, unsigned Depth) { 856955e4f9d5SDimitry Andric // C++2a [expr.prim.req.compound] p1.3.3 857055e4f9d5SDimitry Andric // [..] the expression is deduced against an invented function template 857155e4f9d5SDimitry Andric // F [...] F is a void function template with a single type template 857255e4f9d5SDimitry Andric // parameter T declared with the constrained-parameter. Form a new 857355e4f9d5SDimitry Andric // cv-qualifier-seq cv by taking the union of const and volatile specifiers 857455e4f9d5SDimitry Andric // around the constrained-parameter. F has a single parameter whose 857555e4f9d5SDimitry Andric // type-specifier is cv T followed by the abstract-declarator. [...] 857655e4f9d5SDimitry Andric // 857755e4f9d5SDimitry Andric // The cv part is done in the calling function - we get the concept with 857855e4f9d5SDimitry Andric // arguments and the abstract declarator with the correct CV qualification and 857955e4f9d5SDimitry Andric // have to synthesize T and the single parameter of F. 858055e4f9d5SDimitry Andric auto &II = Context.Idents.get("expr-type"); 858155e4f9d5SDimitry Andric auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, 858255e4f9d5SDimitry Andric SourceLocation(), 858355e4f9d5SDimitry Andric SourceLocation(), Depth, 858455e4f9d5SDimitry Andric /*Index=*/0, &II, 858555e4f9d5SDimitry Andric /*Typename=*/true, 858655e4f9d5SDimitry Andric /*ParameterPack=*/false, 858755e4f9d5SDimitry Andric /*HasTypeConstraint=*/true); 858855e4f9d5SDimitry Andric 858955e4f9d5SDimitry Andric if (ActOnTypeConstraint(SS, TypeConstraint, TParam, 859055e4f9d5SDimitry Andric /*EllpsisLoc=*/SourceLocation())) 859155e4f9d5SDimitry Andric // Just produce a requirement with no type requirements. 859255e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {}); 859355e4f9d5SDimitry Andric 859455e4f9d5SDimitry Andric auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), 859555e4f9d5SDimitry Andric SourceLocation(), 859655e4f9d5SDimitry Andric ArrayRef<NamedDecl *>(TParam), 859755e4f9d5SDimitry Andric SourceLocation(), 859855e4f9d5SDimitry Andric /*RequiresClause=*/nullptr); 859955e4f9d5SDimitry Andric return BuildExprRequirement( 860055e4f9d5SDimitry Andric E, /*IsSimple=*/false, NoexceptLoc, 860155e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement(TPL)); 860255e4f9d5SDimitry Andric } 860355e4f9d5SDimitry Andric 860455e4f9d5SDimitry Andric concepts::ExprRequirement * 860555e4f9d5SDimitry Andric Sema::BuildExprRequirement( 860655e4f9d5SDimitry Andric Expr *E, bool IsSimple, SourceLocation NoexceptLoc, 860755e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 860855e4f9d5SDimitry Andric auto Status = concepts::ExprRequirement::SS_Satisfied; 860955e4f9d5SDimitry Andric ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; 861055e4f9d5SDimitry Andric if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent()) 861155e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_Dependent; 861255e4f9d5SDimitry Andric else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) 861355e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_NoexceptNotMet; 861455e4f9d5SDimitry Andric else if (ReturnTypeRequirement.isSubstitutionFailure()) 861555e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; 861655e4f9d5SDimitry Andric else if (ReturnTypeRequirement.isTypeConstraint()) { 861755e4f9d5SDimitry Andric // C++2a [expr.prim.req]p1.3.3 861855e4f9d5SDimitry Andric // The immediately-declared constraint ([temp]) of decltype((E)) shall 861955e4f9d5SDimitry Andric // be satisfied. 862055e4f9d5SDimitry Andric TemplateParameterList *TPL = 862155e4f9d5SDimitry Andric ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); 862255e4f9d5SDimitry Andric QualType MatchedType = 862355e4f9d5SDimitry Andric BuildDecltypeType(E, E->getBeginLoc()).getCanonicalType(); 862455e4f9d5SDimitry Andric llvm::SmallVector<TemplateArgument, 1> Args; 862555e4f9d5SDimitry Andric Args.push_back(TemplateArgument(MatchedType)); 862655e4f9d5SDimitry Andric TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args); 862755e4f9d5SDimitry Andric MultiLevelTemplateArgumentList MLTAL(TAL); 862855e4f9d5SDimitry Andric for (unsigned I = 0; I < TPL->getDepth(); ++I) 862955e4f9d5SDimitry Andric MLTAL.addOuterRetainedLevel(); 863055e4f9d5SDimitry Andric Expr *IDC = 863155e4f9d5SDimitry Andric cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint() 863255e4f9d5SDimitry Andric ->getImmediatelyDeclaredConstraint(); 863355e4f9d5SDimitry Andric ExprResult Constraint = SubstExpr(IDC, MLTAL); 863455e4f9d5SDimitry Andric assert(!Constraint.isInvalid() && 863555e4f9d5SDimitry Andric "Substitution cannot fail as it is simply putting a type template " 863655e4f9d5SDimitry Andric "argument into a concept specialization expression's parameter."); 863755e4f9d5SDimitry Andric 863855e4f9d5SDimitry Andric SubstitutedConstraintExpr = 863955e4f9d5SDimitry Andric cast<ConceptSpecializationExpr>(Constraint.get()); 864055e4f9d5SDimitry Andric if (!SubstitutedConstraintExpr->isSatisfied()) 864155e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; 864255e4f9d5SDimitry Andric } 864355e4f9d5SDimitry Andric return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, 864455e4f9d5SDimitry Andric ReturnTypeRequirement, Status, 864555e4f9d5SDimitry Andric SubstitutedConstraintExpr); 864655e4f9d5SDimitry Andric } 864755e4f9d5SDimitry Andric 864855e4f9d5SDimitry Andric concepts::ExprRequirement * 864955e4f9d5SDimitry Andric Sema::BuildExprRequirement( 865055e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, 865155e4f9d5SDimitry Andric bool IsSimple, SourceLocation NoexceptLoc, 865255e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 865355e4f9d5SDimitry Andric return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, 865455e4f9d5SDimitry Andric IsSimple, NoexceptLoc, 865555e4f9d5SDimitry Andric ReturnTypeRequirement); 865655e4f9d5SDimitry Andric } 865755e4f9d5SDimitry Andric 865855e4f9d5SDimitry Andric concepts::TypeRequirement * 865955e4f9d5SDimitry Andric Sema::BuildTypeRequirement(TypeSourceInfo *Type) { 866055e4f9d5SDimitry Andric return new (Context) concepts::TypeRequirement(Type); 866155e4f9d5SDimitry Andric } 866255e4f9d5SDimitry Andric 866355e4f9d5SDimitry Andric concepts::TypeRequirement * 866455e4f9d5SDimitry Andric Sema::BuildTypeRequirement( 866555e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 866655e4f9d5SDimitry Andric return new (Context) concepts::TypeRequirement(SubstDiag); 866755e4f9d5SDimitry Andric } 866855e4f9d5SDimitry Andric 866955e4f9d5SDimitry Andric concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { 867055e4f9d5SDimitry Andric return BuildNestedRequirement(Constraint); 867155e4f9d5SDimitry Andric } 867255e4f9d5SDimitry Andric 867355e4f9d5SDimitry Andric concepts::NestedRequirement * 867455e4f9d5SDimitry Andric Sema::BuildNestedRequirement(Expr *Constraint) { 867555e4f9d5SDimitry Andric ConstraintSatisfaction Satisfaction; 867655e4f9d5SDimitry Andric if (!Constraint->isInstantiationDependent() && 867713138422SDimitry Andric CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{}, 867813138422SDimitry Andric Constraint->getSourceRange(), Satisfaction)) 867955e4f9d5SDimitry Andric return nullptr; 868055e4f9d5SDimitry Andric return new (Context) concepts::NestedRequirement(Context, Constraint, 868155e4f9d5SDimitry Andric Satisfaction); 868255e4f9d5SDimitry Andric } 868355e4f9d5SDimitry Andric 868455e4f9d5SDimitry Andric concepts::NestedRequirement * 868555e4f9d5SDimitry Andric Sema::BuildNestedRequirement( 868655e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 868755e4f9d5SDimitry Andric return new (Context) concepts::NestedRequirement(SubstDiag); 868855e4f9d5SDimitry Andric } 868955e4f9d5SDimitry Andric 869055e4f9d5SDimitry Andric RequiresExprBodyDecl * 869155e4f9d5SDimitry Andric Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 869255e4f9d5SDimitry Andric ArrayRef<ParmVarDecl *> LocalParameters, 869355e4f9d5SDimitry Andric Scope *BodyScope) { 869455e4f9d5SDimitry Andric assert(BodyScope); 869555e4f9d5SDimitry Andric 869655e4f9d5SDimitry Andric RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext, 869755e4f9d5SDimitry Andric RequiresKWLoc); 869855e4f9d5SDimitry Andric 869955e4f9d5SDimitry Andric PushDeclContext(BodyScope, Body); 870055e4f9d5SDimitry Andric 870155e4f9d5SDimitry Andric for (ParmVarDecl *Param : LocalParameters) { 870255e4f9d5SDimitry Andric if (Param->hasDefaultArg()) 870355e4f9d5SDimitry Andric // C++2a [expr.prim.req] p4 870455e4f9d5SDimitry Andric // [...] A local parameter of a requires-expression shall not have a 870555e4f9d5SDimitry Andric // default argument. [...] 870655e4f9d5SDimitry Andric Diag(Param->getDefaultArgRange().getBegin(), 870755e4f9d5SDimitry Andric diag::err_requires_expr_local_parameter_default_argument); 870855e4f9d5SDimitry Andric // Ignore default argument and move on 870955e4f9d5SDimitry Andric 871055e4f9d5SDimitry Andric Param->setDeclContext(Body); 871155e4f9d5SDimitry Andric // If this has an identifier, add it to the scope stack. 871255e4f9d5SDimitry Andric if (Param->getIdentifier()) { 871355e4f9d5SDimitry Andric CheckShadow(BodyScope, Param); 871455e4f9d5SDimitry Andric PushOnScopeChains(Param, BodyScope); 871555e4f9d5SDimitry Andric } 871655e4f9d5SDimitry Andric } 871755e4f9d5SDimitry Andric return Body; 871855e4f9d5SDimitry Andric } 871955e4f9d5SDimitry Andric 872055e4f9d5SDimitry Andric void Sema::ActOnFinishRequiresExpr() { 872155e4f9d5SDimitry Andric assert(CurContext && "DeclContext imbalance!"); 872255e4f9d5SDimitry Andric CurContext = CurContext->getLexicalParent(); 872355e4f9d5SDimitry Andric assert(CurContext && "Popped translation unit!"); 872455e4f9d5SDimitry Andric } 872555e4f9d5SDimitry Andric 872655e4f9d5SDimitry Andric ExprResult 872755e4f9d5SDimitry Andric Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc, 872855e4f9d5SDimitry Andric RequiresExprBodyDecl *Body, 872955e4f9d5SDimitry Andric ArrayRef<ParmVarDecl *> LocalParameters, 873055e4f9d5SDimitry Andric ArrayRef<concepts::Requirement *> Requirements, 873155e4f9d5SDimitry Andric SourceLocation ClosingBraceLoc) { 8732e8d8bef9SDimitry Andric auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters, 873355e4f9d5SDimitry Andric Requirements, ClosingBraceLoc); 8734e8d8bef9SDimitry Andric if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) 8735e8d8bef9SDimitry Andric return ExprError(); 8736e8d8bef9SDimitry Andric return RE; 873755e4f9d5SDimitry Andric } 8738