Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp
35233 views
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// Implements semantic analysis for C++ expressions.10///11//===----------------------------------------------------------------------===//1213#include "TreeTransform.h"14#include "TypeLocBuilder.h"15#include "clang/AST/ASTContext.h"16#include "clang/AST/ASTLambda.h"17#include "clang/AST/CXXInheritance.h"18#include "clang/AST/CharUnits.h"19#include "clang/AST/DeclObjC.h"20#include "clang/AST/ExprCXX.h"21#include "clang/AST/ExprConcepts.h"22#include "clang/AST/ExprObjC.h"23#include "clang/AST/RecursiveASTVisitor.h"24#include "clang/AST/Type.h"25#include "clang/AST/TypeLoc.h"26#include "clang/Basic/AlignedAllocation.h"27#include "clang/Basic/DiagnosticSema.h"28#include "clang/Basic/PartialDiagnostic.h"29#include "clang/Basic/TargetInfo.h"30#include "clang/Basic/TokenKinds.h"31#include "clang/Basic/TypeTraits.h"32#include "clang/Lex/Preprocessor.h"33#include "clang/Sema/DeclSpec.h"34#include "clang/Sema/EnterExpressionEvaluationContext.h"35#include "clang/Sema/Initialization.h"36#include "clang/Sema/Lookup.h"37#include "clang/Sema/ParsedTemplate.h"38#include "clang/Sema/Scope.h"39#include "clang/Sema/ScopeInfo.h"40#include "clang/Sema/SemaCUDA.h"41#include "clang/Sema/SemaInternal.h"42#include "clang/Sema/SemaLambda.h"43#include "clang/Sema/SemaObjC.h"44#include "clang/Sema/SemaPPC.h"45#include "clang/Sema/Template.h"46#include "clang/Sema/TemplateDeduction.h"47#include "llvm/ADT/APInt.h"48#include "llvm/ADT/STLExtras.h"49#include "llvm/ADT/STLForwardCompat.h"50#include "llvm/ADT/StringExtras.h"51#include "llvm/Support/ErrorHandling.h"52#include "llvm/Support/TypeSize.h"53#include <optional>54using namespace clang;55using namespace sema;5657ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,58SourceLocation NameLoc,59const IdentifierInfo &Name) {60NestedNameSpecifier *NNS = SS.getScopeRep();6162// Convert the nested-name-specifier into a type.63QualType Type;64switch (NNS->getKind()) {65case NestedNameSpecifier::TypeSpec:66case NestedNameSpecifier::TypeSpecWithTemplate:67Type = QualType(NNS->getAsType(), 0);68break;6970case NestedNameSpecifier::Identifier:71// Strip off the last layer of the nested-name-specifier and build a72// typename type for it.73assert(NNS->getAsIdentifier() == &Name && "not a constructor name");74Type = Context.getDependentNameType(75ElaboratedTypeKeyword::None, NNS->getPrefix(), NNS->getAsIdentifier());76break;7778case NestedNameSpecifier::Global:79case NestedNameSpecifier::Super:80case NestedNameSpecifier::Namespace:81case NestedNameSpecifier::NamespaceAlias:82llvm_unreachable("Nested name specifier is not a type for inheriting ctor");83}8485// This reference to the type is located entirely at the location of the86// final identifier in the qualified-id.87return CreateParsedType(Type,88Context.getTrivialTypeSourceInfo(Type, NameLoc));89}9091ParsedType Sema::getConstructorName(const IdentifierInfo &II,92SourceLocation NameLoc, Scope *S,93CXXScopeSpec &SS, bool EnteringContext) {94CXXRecordDecl *CurClass = getCurrentClass(S, &SS);95assert(CurClass && &II == CurClass->getIdentifier() &&96"not a constructor name");9798// When naming a constructor as a member of a dependent context (eg, in a99// friend declaration or an inherited constructor declaration), form an100// unresolved "typename" type.101if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {102QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,103SS.getScopeRep(), &II);104return ParsedType::make(T);105}106107if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))108return ParsedType();109110// Find the injected-class-name declaration. Note that we make no attempt to111// diagnose cases where the injected-class-name is shadowed: the only112// declaration that can validly shadow the injected-class-name is a113// non-static data member, and if the class contains both a non-static data114// member and a constructor then it is ill-formed (we check that in115// CheckCompletedCXXClass).116CXXRecordDecl *InjectedClassName = nullptr;117for (NamedDecl *ND : CurClass->lookup(&II)) {118auto *RD = dyn_cast<CXXRecordDecl>(ND);119if (RD && RD->isInjectedClassName()) {120InjectedClassName = RD;121break;122}123}124if (!InjectedClassName) {125if (!CurClass->isInvalidDecl()) {126// FIXME: RequireCompleteDeclContext doesn't check dependent contexts127// properly. Work around it here for now.128Diag(SS.getLastQualifierNameLoc(),129diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();130}131return ParsedType();132}133134QualType T = Context.getTypeDeclType(InjectedClassName);135DiagnoseUseOfDecl(InjectedClassName, NameLoc);136MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);137138return ParsedType::make(T);139}140141ParsedType Sema::getDestructorName(const IdentifierInfo &II,142SourceLocation NameLoc, Scope *S,143CXXScopeSpec &SS, ParsedType ObjectTypePtr,144bool EnteringContext) {145// Determine where to perform name lookup.146147// FIXME: This area of the standard is very messy, and the current148// wording is rather unclear about which scopes we search for the149// destructor name; see core issues 399 and 555. Issue 399 in150// particular shows where the current description of destructor name151// lookup is completely out of line with existing practice, e.g.,152// this appears to be ill-formed:153//154// namespace N {155// template <typename T> struct S {156// ~S();157// };158// }159//160// void f(N::S<int>* s) {161// s->N::S<int>::~S();162// }163//164// See also PR6358 and PR6359.165//166// For now, we accept all the cases in which the name given could plausibly167// be interpreted as a correct destructor name, issuing off-by-default168// extension diagnostics on the cases that don't strictly conform to the169// C++20 rules. This basically means we always consider looking in the170// nested-name-specifier prefix, the complete nested-name-specifier, and171// the scope, and accept if we find the expected type in any of the three172// places.173174if (SS.isInvalid())175return nullptr;176177// Whether we've failed with a diagnostic already.178bool Failed = false;179180llvm::SmallVector<NamedDecl*, 8> FoundDecls;181llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;182183// If we have an object type, it's because we are in a184// pseudo-destructor-expression or a member access expression, and185// we know what type we're looking for.186QualType SearchType =187ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();188189auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {190auto IsAcceptableResult = [&](NamedDecl *D) -> bool {191auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());192if (!Type)193return false;194195if (SearchType.isNull() || SearchType->isDependentType())196return true;197198QualType T = Context.getTypeDeclType(Type);199return Context.hasSameUnqualifiedType(T, SearchType);200};201202unsigned NumAcceptableResults = 0;203for (NamedDecl *D : Found) {204if (IsAcceptableResult(D))205++NumAcceptableResults;206207// Don't list a class twice in the lookup failure diagnostic if it's208// found by both its injected-class-name and by the name in the enclosing209// scope.210if (auto *RD = dyn_cast<CXXRecordDecl>(D))211if (RD->isInjectedClassName())212D = cast<NamedDecl>(RD->getParent());213214if (FoundDeclSet.insert(D).second)215FoundDecls.push_back(D);216}217218// As an extension, attempt to "fix" an ambiguity by erasing all non-type219// results, and all non-matching results if we have a search type. It's not220// clear what the right behavior is if destructor lookup hits an ambiguity,221// but other compilers do generally accept at least some kinds of222// ambiguity.223if (Found.isAmbiguous() && NumAcceptableResults == 1) {224Diag(NameLoc, diag::ext_dtor_name_ambiguous);225LookupResult::Filter F = Found.makeFilter();226while (F.hasNext()) {227NamedDecl *D = F.next();228if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))229Diag(D->getLocation(), diag::note_destructor_type_here)230<< Context.getTypeDeclType(TD);231else232Diag(D->getLocation(), diag::note_destructor_nontype_here);233234if (!IsAcceptableResult(D))235F.erase();236}237F.done();238}239240if (Found.isAmbiguous())241Failed = true;242243if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {244if (IsAcceptableResult(Type)) {245QualType T = Context.getTypeDeclType(Type);246MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);247return CreateParsedType(248Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr, T),249Context.getTrivialTypeSourceInfo(T, NameLoc));250}251}252253return nullptr;254};255256bool IsDependent = false;257258auto LookupInObjectType = [&]() -> ParsedType {259if (Failed || SearchType.isNull())260return nullptr;261262IsDependent |= SearchType->isDependentType();263264LookupResult Found(*this, &II, NameLoc, LookupDestructorName);265DeclContext *LookupCtx = computeDeclContext(SearchType);266if (!LookupCtx)267return nullptr;268LookupQualifiedName(Found, LookupCtx);269return CheckLookupResult(Found);270};271272auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {273if (Failed)274return nullptr;275276IsDependent |= isDependentScopeSpecifier(LookupSS);277DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);278if (!LookupCtx)279return nullptr;280281LookupResult Found(*this, &II, NameLoc, LookupDestructorName);282if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {283Failed = true;284return nullptr;285}286LookupQualifiedName(Found, LookupCtx);287return CheckLookupResult(Found);288};289290auto LookupInScope = [&]() -> ParsedType {291if (Failed || !S)292return nullptr;293294LookupResult Found(*this, &II, NameLoc, LookupDestructorName);295LookupName(Found, S);296return CheckLookupResult(Found);297};298299// C++2a [basic.lookup.qual]p6:300// In a qualified-id of the form301//302// nested-name-specifier[opt] type-name :: ~ type-name303//304// the second type-name is looked up in the same scope as the first.305//306// We interpret this as meaning that if you do a dual-scope lookup for the307// first name, you also do a dual-scope lookup for the second name, per308// C++ [basic.lookup.classref]p4:309//310// If the id-expression in a class member access is a qualified-id of the311// form312//313// class-name-or-namespace-name :: ...314//315// the class-name-or-namespace-name following the . or -> is first looked316// up in the class of the object expression and the name, if found, is used.317// Otherwise, it is looked up in the context of the entire318// postfix-expression.319//320// This looks in the same scopes as for an unqualified destructor name:321//322// C++ [basic.lookup.classref]p3:323// If the unqualified-id is ~ type-name, the type-name is looked up324// in the context of the entire postfix-expression. If the type T325// of the object expression is of a class type C, the type-name is326// also looked up in the scope of class C. At least one of the327// lookups shall find a name that refers to cv T.328//329// FIXME: The intent is unclear here. Should type-name::~type-name look in330// the scope anyway if it finds a non-matching name declared in the class?331// If both lookups succeed and find a dependent result, which result should332// we retain? (Same question for p->~type-name().)333334if (NestedNameSpecifier *Prefix =335SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {336// This is337//338// nested-name-specifier type-name :: ~ type-name339//340// Look for the second type-name in the nested-name-specifier.341CXXScopeSpec PrefixSS;342PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));343if (ParsedType T = LookupInNestedNameSpec(PrefixSS))344return T;345} else {346// This is one of347//348// type-name :: ~ type-name349// ~ type-name350//351// Look in the scope and (if any) the object type.352if (ParsedType T = LookupInScope())353return T;354if (ParsedType T = LookupInObjectType())355return T;356}357358if (Failed)359return nullptr;360361if (IsDependent) {362// We didn't find our type, but that's OK: it's dependent anyway.363364// FIXME: What if we have no nested-name-specifier?365QualType T =366CheckTypenameType(ElaboratedTypeKeyword::None, SourceLocation(),367SS.getWithLocInContext(Context), II, NameLoc);368return ParsedType::make(T);369}370371// The remaining cases are all non-standard extensions imitating the behavior372// of various other compilers.373unsigned NumNonExtensionDecls = FoundDecls.size();374375if (SS.isSet()) {376// For compatibility with older broken C++ rules and existing code,377//378// nested-name-specifier :: ~ type-name379//380// also looks for type-name within the nested-name-specifier.381if (ParsedType T = LookupInNestedNameSpec(SS)) {382Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)383<< SS.getRange()384<< FixItHint::CreateInsertion(SS.getEndLoc(),385("::" + II.getName()).str());386return T;387}388389// For compatibility with other compilers and older versions of Clang,390//391// nested-name-specifier type-name :: ~ type-name392//393// also looks for type-name in the scope. Unfortunately, we can't394// reasonably apply this fallback for dependent nested-name-specifiers.395if (SS.isValid() && SS.getScopeRep()->getPrefix()) {396if (ParsedType T = LookupInScope()) {397Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)398<< FixItHint::CreateRemoval(SS.getRange());399Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)400<< GetTypeFromParser(T);401return T;402}403}404}405406// We didn't find anything matching; tell the user what we did find (if407// anything).408409// Don't tell the user about declarations we shouldn't have found.410FoundDecls.resize(NumNonExtensionDecls);411412// List types before non-types.413std::stable_sort(FoundDecls.begin(), FoundDecls.end(),414[](NamedDecl *A, NamedDecl *B) {415return isa<TypeDecl>(A->getUnderlyingDecl()) >416isa<TypeDecl>(B->getUnderlyingDecl());417});418419// Suggest a fixit to properly name the destroyed type.420auto MakeFixItHint = [&]{421const CXXRecordDecl *Destroyed = nullptr;422// FIXME: If we have a scope specifier, suggest its last component?423if (!SearchType.isNull())424Destroyed = SearchType->getAsCXXRecordDecl();425else if (S)426Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());427if (Destroyed)428return FixItHint::CreateReplacement(SourceRange(NameLoc),429Destroyed->getNameAsString());430return FixItHint();431};432433if (FoundDecls.empty()) {434// FIXME: Attempt typo-correction?435Diag(NameLoc, diag::err_undeclared_destructor_name)436<< &II << MakeFixItHint();437} else if (!SearchType.isNull() && FoundDecls.size() == 1) {438if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {439assert(!SearchType.isNull() &&440"should only reject a type result if we have a search type");441QualType T = Context.getTypeDeclType(TD);442Diag(NameLoc, diag::err_destructor_expr_type_mismatch)443<< T << SearchType << MakeFixItHint();444} else {445Diag(NameLoc, diag::err_destructor_expr_nontype)446<< &II << MakeFixItHint();447}448} else {449Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype450: diag::err_destructor_expr_mismatch)451<< &II << SearchType << MakeFixItHint();452}453454for (NamedDecl *FoundD : FoundDecls) {455if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))456Diag(FoundD->getLocation(), diag::note_destructor_type_here)457<< Context.getTypeDeclType(TD);458else459Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)460<< FoundD;461}462463return nullptr;464}465466ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,467ParsedType ObjectType) {468if (DS.getTypeSpecType() == DeclSpec::TST_error)469return nullptr;470471if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {472Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);473return nullptr;474}475476assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&477"unexpected type in getDestructorType");478QualType T = BuildDecltypeType(DS.getRepAsExpr());479480// If we know the type of the object, check that the correct destructor481// type was named now; we can give better diagnostics this way.482QualType SearchType = GetTypeFromParser(ObjectType);483if (!SearchType.isNull() && !SearchType->isDependentType() &&484!Context.hasSameUnqualifiedType(T, SearchType)) {485Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)486<< T << SearchType;487return nullptr;488}489490return ParsedType::make(T);491}492493bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,494const UnqualifiedId &Name, bool IsUDSuffix) {495assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);496if (!IsUDSuffix) {497// [over.literal] p8498//499// double operator""_Bq(long double); // OK: not a reserved identifier500// double operator"" _Bq(long double); // ill-formed, no diagnostic required501const IdentifierInfo *II = Name.Identifier;502ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());503SourceLocation Loc = Name.getEndLoc();504if (!PP.getSourceManager().isInSystemHeader(Loc)) {505if (auto Hint = FixItHint::CreateReplacement(506Name.getSourceRange(),507(StringRef("operator\"\"") + II->getName()).str());508isReservedInAllContexts(Status)) {509Diag(Loc, diag::warn_reserved_extern_symbol)510<< II << static_cast<int>(Status) << Hint;511} else {512Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;513}514}515}516517if (!SS.isValid())518return false;519520switch (SS.getScopeRep()->getKind()) {521case NestedNameSpecifier::Identifier:522case NestedNameSpecifier::TypeSpec:523case NestedNameSpecifier::TypeSpecWithTemplate:524// Per C++11 [over.literal]p2, literal operators can only be declared at525// namespace scope. Therefore, this unqualified-id cannot name anything.526// Reject it early, because we have no AST representation for this in the527// case where the scope is dependent.528Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)529<< SS.getScopeRep();530return true;531532case NestedNameSpecifier::Global:533case NestedNameSpecifier::Super:534case NestedNameSpecifier::Namespace:535case NestedNameSpecifier::NamespaceAlias:536return false;537}538539llvm_unreachable("unknown nested name specifier kind");540}541542ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,543SourceLocation TypeidLoc,544TypeSourceInfo *Operand,545SourceLocation RParenLoc) {546// C++ [expr.typeid]p4:547// The top-level cv-qualifiers of the lvalue expression or the type-id548// that is the operand of typeid are always ignored.549// If the type of the type-id is a class type or a reference to a class550// type, the class shall be completely-defined.551Qualifiers Quals;552QualType T553= Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),554Quals);555if (T->getAs<RecordType>() &&556RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))557return ExprError();558559if (T->isVariablyModifiedType())560return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);561562if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))563return ExprError();564565return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,566SourceRange(TypeidLoc, RParenLoc));567}568569ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,570SourceLocation TypeidLoc,571Expr *E,572SourceLocation RParenLoc) {573bool WasEvaluated = false;574if (E && !E->isTypeDependent()) {575if (E->hasPlaceholderType()) {576ExprResult result = CheckPlaceholderExpr(E);577if (result.isInvalid()) return ExprError();578E = result.get();579}580581QualType T = E->getType();582if (const RecordType *RecordT = T->getAs<RecordType>()) {583CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());584// C++ [expr.typeid]p3:585// [...] If the type of the expression is a class type, the class586// shall be completely-defined.587if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))588return ExprError();589590// C++ [expr.typeid]p3:591// When typeid is applied to an expression other than an glvalue of a592// polymorphic class type [...] [the] expression is an unevaluated593// operand. [...]594if (RecordD->isPolymorphic() && E->isGLValue()) {595if (isUnevaluatedContext()) {596// The operand was processed in unevaluated context, switch the597// context and recheck the subexpression.598ExprResult Result = TransformToPotentiallyEvaluated(E);599if (Result.isInvalid())600return ExprError();601E = Result.get();602}603604// We require a vtable to query the type at run time.605MarkVTableUsed(TypeidLoc, RecordD);606WasEvaluated = true;607}608}609610ExprResult Result = CheckUnevaluatedOperand(E);611if (Result.isInvalid())612return ExprError();613E = Result.get();614615// C++ [expr.typeid]p4:616// [...] If the type of the type-id is a reference to a possibly617// cv-qualified type, the result of the typeid expression refers to a618// std::type_info object representing the cv-unqualified referenced619// type.620Qualifiers Quals;621QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);622if (!Context.hasSameType(T, UnqualT)) {623T = UnqualT;624E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();625}626}627628if (E->getType()->isVariablyModifiedType())629return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)630<< E->getType());631else if (!inTemplateInstantiation() &&632E->HasSideEffects(Context, WasEvaluated)) {633// The expression operand for typeid is in an unevaluated expression634// context, so side effects could result in unintended consequences.635Diag(E->getExprLoc(), WasEvaluated636? diag::warn_side_effects_typeid637: diag::warn_side_effects_unevaluated_context);638}639640return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,641SourceRange(TypeidLoc, RParenLoc));642}643644/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);645ExprResult646Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,647bool isType, void *TyOrExpr, SourceLocation RParenLoc) {648// typeid is not supported in OpenCL.649if (getLangOpts().OpenCLCPlusPlus) {650return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)651<< "typeid");652}653654// Find the std::type_info type.655if (!getStdNamespace())656return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));657658if (!CXXTypeInfoDecl) {659IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");660LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);661LookupQualifiedName(R, getStdNamespace());662CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();663// Microsoft's typeinfo doesn't have type_info in std but in the global664// namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.665if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {666LookupQualifiedName(R, Context.getTranslationUnitDecl());667CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();668}669if (!CXXTypeInfoDecl)670return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));671}672673if (!getLangOpts().RTTI) {674return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));675}676677QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);678679if (isType) {680// The operand is a type; handle it as such.681TypeSourceInfo *TInfo = nullptr;682QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),683&TInfo);684if (T.isNull())685return ExprError();686687if (!TInfo)688TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);689690return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);691}692693// The operand is an expression.694ExprResult Result =695BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);696697if (!getLangOpts().RTTIData && !Result.isInvalid())698if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))699if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))700Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)701<< (getDiagnostics().getDiagnosticOptions().getFormat() ==702DiagnosticOptions::MSVC);703return Result;704}705706/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to707/// a single GUID.708static void709getUuidAttrOfType(Sema &SemaRef, QualType QT,710llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {711// Optionally remove one level of pointer, reference or array indirection.712const Type *Ty = QT.getTypePtr();713if (QT->isPointerType() || QT->isReferenceType())714Ty = QT->getPointeeType().getTypePtr();715else if (QT->isArrayType())716Ty = Ty->getBaseElementTypeUnsafe();717718const auto *TD = Ty->getAsTagDecl();719if (!TD)720return;721722if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {723UuidAttrs.insert(Uuid);724return;725}726727// __uuidof can grab UUIDs from template arguments.728if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {729const TemplateArgumentList &TAL = CTSD->getTemplateArgs();730for (const TemplateArgument &TA : TAL.asArray()) {731const UuidAttr *UuidForTA = nullptr;732if (TA.getKind() == TemplateArgument::Type)733getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);734else if (TA.getKind() == TemplateArgument::Declaration)735getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);736737if (UuidForTA)738UuidAttrs.insert(UuidForTA);739}740}741}742743ExprResult Sema::BuildCXXUuidof(QualType Type,744SourceLocation TypeidLoc,745TypeSourceInfo *Operand,746SourceLocation RParenLoc) {747MSGuidDecl *Guid = nullptr;748if (!Operand->getType()->isDependentType()) {749llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;750getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);751if (UuidAttrs.empty())752return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));753if (UuidAttrs.size() > 1)754return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));755Guid = UuidAttrs.back()->getGuidDecl();756}757758return new (Context)759CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));760}761762ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,763Expr *E, SourceLocation RParenLoc) {764MSGuidDecl *Guid = nullptr;765if (!E->getType()->isDependentType()) {766if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {767// A null pointer results in {00000000-0000-0000-0000-000000000000}.768Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});769} else {770llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;771getUuidAttrOfType(*this, E->getType(), UuidAttrs);772if (UuidAttrs.empty())773return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));774if (UuidAttrs.size() > 1)775return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));776Guid = UuidAttrs.back()->getGuidDecl();777}778}779780return new (Context)781CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));782}783784/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);785ExprResult786Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,787bool isType, void *TyOrExpr, SourceLocation RParenLoc) {788QualType GuidType = Context.getMSGuidType();789GuidType.addConst();790791if (isType) {792// The operand is a type; handle it as such.793TypeSourceInfo *TInfo = nullptr;794QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),795&TInfo);796if (T.isNull())797return ExprError();798799if (!TInfo)800TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);801802return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);803}804805// The operand is an expression.806return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);807}808809ExprResult810Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {811assert((Kind == tok::kw_true || Kind == tok::kw_false) &&812"Unknown C++ Boolean value!");813return new (Context)814CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);815}816817ExprResult818Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {819return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);820}821822ExprResult823Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {824bool IsThrownVarInScope = false;825if (Ex) {826// C++0x [class.copymove]p31:827// When certain criteria are met, an implementation is allowed to omit the828// copy/move construction of a class object [...]829//830// - in a throw-expression, when the operand is the name of a831// non-volatile automatic object (other than a function or catch-832// clause parameter) whose scope does not extend beyond the end of the833// innermost enclosing try-block (if there is one), the copy/move834// operation from the operand to the exception object (15.1) can be835// omitted by constructing the automatic object directly into the836// exception object837if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))838if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());839Var && Var->hasLocalStorage() &&840!Var->getType().isVolatileQualified()) {841for (; S; S = S->getParent()) {842if (S->isDeclScope(Var)) {843IsThrownVarInScope = true;844break;845}846847// FIXME: Many of the scope checks here seem incorrect.848if (S->getFlags() &849(Scope::FnScope | Scope::ClassScope | Scope::BlockScope |850Scope::ObjCMethodScope | Scope::TryScope))851break;852}853}854}855856return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);857}858859ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,860bool IsThrownVarInScope) {861const llvm::Triple &T = Context.getTargetInfo().getTriple();862const bool IsOpenMPGPUTarget =863getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());864// Don't report an error if 'throw' is used in system headers or in an OpenMP865// target region compiled for a GPU architecture.866if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&867!getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {868// Delay error emission for the OpenMP device code.869targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";870}871872// In OpenMP target regions, we replace 'throw' with a trap on GPU targets.873if (IsOpenMPGPUTarget)874targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();875876// Exceptions aren't allowed in CUDA device code.877if (getLangOpts().CUDA)878CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)879<< "throw" << llvm::to_underlying(CUDA().CurrentTarget());880881if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())882Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";883884// Exceptions that escape a compute construct are ill-formed.885if (getLangOpts().OpenACC && getCurScope() &&886getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))887Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)888<< /*throw*/ 2 << /*out of*/ 0;889890if (Ex && !Ex->isTypeDependent()) {891// Initialize the exception result. This implicitly weeds out892// abstract types or types with inaccessible copy constructors.893894// C++0x [class.copymove]p31:895// When certain criteria are met, an implementation is allowed to omit the896// copy/move construction of a class object [...]897//898// - in a throw-expression, when the operand is the name of a899// non-volatile automatic object (other than a function or900// catch-clause901// parameter) whose scope does not extend beyond the end of the902// innermost enclosing try-block (if there is one), the copy/move903// operation from the operand to the exception object (15.1) can be904// omitted by constructing the automatic object directly into the905// exception object906NamedReturnInfo NRInfo =907IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();908909QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());910if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))911return ExprError();912913InitializedEntity Entity =914InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);915ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);916if (Res.isInvalid())917return ExprError();918Ex = Res.get();919}920921// PPC MMA non-pointer types are not allowed as throw expr types.922if (Ex && Context.getTargetInfo().getTriple().isPPC64())923PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());924925return new (Context)926CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);927}928929static void930collectPublicBases(CXXRecordDecl *RD,931llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,932llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,933llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,934bool ParentIsPublic) {935for (const CXXBaseSpecifier &BS : RD->bases()) {936CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();937bool NewSubobject;938// Virtual bases constitute the same subobject. Non-virtual bases are939// always distinct subobjects.940if (BS.isVirtual())941NewSubobject = VBases.insert(BaseDecl).second;942else943NewSubobject = true;944945if (NewSubobject)946++SubobjectsSeen[BaseDecl];947948// Only add subobjects which have public access throughout the entire chain.949bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;950if (PublicPath)951PublicSubobjectsSeen.insert(BaseDecl);952953// Recurse on to each base subobject.954collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,955PublicPath);956}957}958959static void getUnambiguousPublicSubobjects(960CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {961llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;962llvm::SmallSet<CXXRecordDecl *, 2> VBases;963llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;964SubobjectsSeen[RD] = 1;965PublicSubobjectsSeen.insert(RD);966collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,967/*ParentIsPublic=*/true);968969for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {970// Skip ambiguous objects.971if (SubobjectsSeen[PublicSubobject] > 1)972continue;973974Objects.push_back(PublicSubobject);975}976}977978bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,979QualType ExceptionObjectTy, Expr *E) {980// If the type of the exception would be an incomplete type or a pointer981// to an incomplete type other than (cv) void the program is ill-formed.982QualType Ty = ExceptionObjectTy;983bool isPointer = false;984if (const PointerType* Ptr = Ty->getAs<PointerType>()) {985Ty = Ptr->getPointeeType();986isPointer = true;987}988989// Cannot throw WebAssembly reference type.990if (Ty.isWebAssemblyReferenceType()) {991Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();992return true;993}994995// Cannot throw WebAssembly table.996if (isPointer && Ty.isWebAssemblyReferenceType()) {997Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();998return true;999}10001001if (!isPointer || !Ty->isVoidType()) {1002if (RequireCompleteType(ThrowLoc, Ty,1003isPointer ? diag::err_throw_incomplete_ptr1004: diag::err_throw_incomplete,1005E->getSourceRange()))1006return true;10071008if (!isPointer && Ty->isSizelessType()) {1009Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();1010return true;1011}10121013if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,1014diag::err_throw_abstract_type, E))1015return true;1016}10171018// If the exception has class type, we need additional handling.1019CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();1020if (!RD)1021return false;10221023// If we are throwing a polymorphic class type or pointer thereof,1024// exception handling will make use of the vtable.1025MarkVTableUsed(ThrowLoc, RD);10261027// If a pointer is thrown, the referenced object will not be destroyed.1028if (isPointer)1029return false;10301031// If the class has a destructor, we must be able to call it.1032if (!RD->hasIrrelevantDestructor()) {1033if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {1034MarkFunctionReferenced(E->getExprLoc(), Destructor);1035CheckDestructorAccess(E->getExprLoc(), Destructor,1036PDiag(diag::err_access_dtor_exception) << Ty);1037if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))1038return true;1039}1040}10411042// The MSVC ABI creates a list of all types which can catch the exception1043// object. This list also references the appropriate copy constructor to call1044// if the object is caught by value and has a non-trivial copy constructor.1045if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {1046// We are only interested in the public, unambiguous bases contained within1047// the exception object. Bases which are ambiguous or otherwise1048// inaccessible are not catchable types.1049llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;1050getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);10511052for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {1053// Attempt to lookup the copy constructor. Various pieces of machinery1054// will spring into action, like template instantiation, which means this1055// cannot be a simple walk of the class's decls. Instead, we must perform1056// lookup and overload resolution.1057CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);1058if (!CD || CD->isDeleted())1059continue;10601061// Mark the constructor referenced as it is used by this throw expression.1062MarkFunctionReferenced(E->getExprLoc(), CD);10631064// Skip this copy constructor if it is trivial, we don't need to record it1065// in the catchable type data.1066if (CD->isTrivial())1067continue;10681069// The copy constructor is non-trivial, create a mapping from this class1070// type to this constructor.1071// N.B. The selection of copy constructor is not sensitive to this1072// particular throw-site. Lookup will be performed at the catch-site to1073// ensure that the copy constructor is, in fact, accessible (via1074// friendship or any other means).1075Context.addCopyConstructorForExceptionObject(Subobject, CD);10761077// We don't keep the instantiated default argument expressions around so1078// we must rebuild them here.1079for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {1080if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))1081return true;1082}1083}1084}10851086// Under the Itanium C++ ABI, memory for the exception object is allocated by1087// the runtime with no ability for the compiler to request additional1088// alignment. Warn if the exception type requires alignment beyond the minimum1089// guaranteed by the target C++ runtime.1090if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {1091CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);1092CharUnits ExnObjAlign = Context.getExnObjectAlignment();1093if (ExnObjAlign < TypeAlign) {1094Diag(ThrowLoc, diag::warn_throw_underaligned_obj);1095Diag(ThrowLoc, diag::note_throw_underaligned_obj)1096<< Ty << (unsigned)TypeAlign.getQuantity()1097<< (unsigned)ExnObjAlign.getQuantity();1098}1099}1100if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {1101if (CXXDestructorDecl *Dtor = RD->getDestructor()) {1102auto Ty = Dtor->getType();1103if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {1104if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&1105!FT->isNothrow())1106Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;1107}1108}1109}11101111return false;1112}11131114static QualType adjustCVQualifiersForCXXThisWithinLambda(1115ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,1116DeclContext *CurSemaContext, ASTContext &ASTCtx) {11171118QualType ClassType = ThisTy->getPointeeType();1119LambdaScopeInfo *CurLSI = nullptr;1120DeclContext *CurDC = CurSemaContext;11211122// Iterate through the stack of lambdas starting from the innermost lambda to1123// the outermost lambda, checking if '*this' is ever captured by copy - since1124// that could change the cv-qualifiers of the '*this' object.1125// The object referred to by '*this' starts out with the cv-qualifiers of its1126// member function. We then start with the innermost lambda and iterate1127// outward checking to see if any lambda performs a by-copy capture of '*this'1128// - and if so, any nested lambda must respect the 'constness' of that1129// capturing lamdbda's call operator.1130//11311132// Since the FunctionScopeInfo stack is representative of the lexical1133// nesting of the lambda expressions during initial parsing (and is the best1134// place for querying information about captures about lambdas that are1135// partially processed) and perhaps during instantiation of function templates1136// that contain lambda expressions that need to be transformed BUT not1137// necessarily during instantiation of a nested generic lambda's function call1138// operator (which might even be instantiated at the end of the TU) - at which1139// time the DeclContext tree is mature enough to query capture information1140// reliably - we use a two pronged approach to walk through all the lexically1141// enclosing lambda expressions:1142//1143// 1) Climb down the FunctionScopeInfo stack as long as each item represents1144// a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically1145// enclosed by the call-operator of the LSI below it on the stack (while1146// tracking the enclosing DC for step 2 if needed). Note the topmost LSI on1147// the stack represents the innermost lambda.1148//1149// 2) If we run out of enclosing LSI's, check if the enclosing DeclContext1150// represents a lambda's call operator. If it does, we must be instantiating1151// a generic lambda's call operator (represented by the Current LSI, and1152// should be the only scenario where an inconsistency between the LSI and the1153// DeclContext should occur), so climb out the DeclContexts if they1154// represent lambdas, while querying the corresponding closure types1155// regarding capture information.11561157// 1) Climb down the function scope info stack.1158for (int I = FunctionScopes.size();1159I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&1160(!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==1161cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);1162CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {1163CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);11641165if (!CurLSI->isCXXThisCaptured())1166continue;11671168auto C = CurLSI->getCXXThisCapture();11691170if (C.isCopyCapture()) {1171if (CurLSI->lambdaCaptureShouldBeConst())1172ClassType.addConst();1173return ASTCtx.getPointerType(ClassType);1174}1175}11761177// 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which1178// can happen during instantiation of its nested generic lambda call1179// operator); 2. if we're in a lambda scope (lambda body).1180if (CurLSI && isLambdaCallOperator(CurDC)) {1181assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&1182"While computing 'this' capture-type for a generic lambda, when we "1183"run out of enclosing LSI's, yet the enclosing DC is a "1184"lambda-call-operator we must be (i.e. Current LSI) in a generic "1185"lambda call oeprator");1186assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));11871188auto IsThisCaptured =1189[](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {1190IsConst = false;1191IsByCopy = false;1192for (auto &&C : Closure->captures()) {1193if (C.capturesThis()) {1194if (C.getCaptureKind() == LCK_StarThis)1195IsByCopy = true;1196if (Closure->getLambdaCallOperator()->isConst())1197IsConst = true;1198return true;1199}1200}1201return false;1202};12031204bool IsByCopyCapture = false;1205bool IsConstCapture = false;1206CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());1207while (Closure &&1208IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {1209if (IsByCopyCapture) {1210if (IsConstCapture)1211ClassType.addConst();1212return ASTCtx.getPointerType(ClassType);1213}1214Closure = isLambdaCallOperator(Closure->getParent())1215? cast<CXXRecordDecl>(Closure->getParent()->getParent())1216: nullptr;1217}1218}1219return ThisTy;1220}12211222QualType Sema::getCurrentThisType() {1223DeclContext *DC = getFunctionLevelDeclContext();1224QualType ThisTy = CXXThisTypeOverride;12251226if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {1227if (method && method->isImplicitObjectMemberFunction())1228ThisTy = method->getThisType().getNonReferenceType();1229}12301231if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(CurContext) &&1232inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {12331234// This is a lambda call operator that is being instantiated as a default1235// initializer. DC must point to the enclosing class type, so we can recover1236// the 'this' type from it.1237QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));1238// There are no cv-qualifiers for 'this' within default initializers,1239// per [expr.prim.general]p4.1240ThisTy = Context.getPointerType(ClassTy);1241}12421243// If we are within a lambda's call operator, the cv-qualifiers of 'this'1244// might need to be adjusted if the lambda or any of its enclosing lambda's1245// captures '*this' by copy.1246if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))1247return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,1248CurContext, Context);1249return ThisTy;1250}12511252Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,1253Decl *ContextDecl,1254Qualifiers CXXThisTypeQuals,1255bool Enabled)1256: S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)1257{1258if (!Enabled || !ContextDecl)1259return;12601261CXXRecordDecl *Record = nullptr;1262if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))1263Record = Template->getTemplatedDecl();1264else1265Record = cast<CXXRecordDecl>(ContextDecl);12661267QualType T = S.Context.getRecordType(Record);1268T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);12691270S.CXXThisTypeOverride =1271S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);12721273this->Enabled = true;1274}127512761277Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {1278if (Enabled) {1279S.CXXThisTypeOverride = OldCXXThisTypeOverride;1280}1281}12821283static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {1284SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();1285assert(!LSI->isCXXThisCaptured());1286// [=, this] {}; // until C++20: Error: this when = is the default1287if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&1288!Sema.getLangOpts().CPlusPlus20)1289return;1290Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)1291<< FixItHint::CreateInsertion(1292DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");1293}12941295bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,1296bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,1297const bool ByCopy) {1298// We don't need to capture this in an unevaluated context.1299if (isUnevaluatedContext() && !Explicit)1300return true;13011302assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");13031304const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt1305? *FunctionScopeIndexToStopAt1306: FunctionScopes.size() - 1;13071308// Check that we can capture the *enclosing object* (referred to by '*this')1309// by the capturing-entity/closure (lambda/block/etc) at1310// MaxFunctionScopesIndex-deep on the FunctionScopes stack.13111312// Note: The *enclosing object* can only be captured by-value by a1313// closure that is a lambda, using the explicit notation:1314// [*this] { ... }.1315// Every other capture of the *enclosing object* results in its by-reference1316// capture.13171318// For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes1319// stack), we can capture the *enclosing object* only if:1320// - 'L' has an explicit byref or byval capture of the *enclosing object*1321// - or, 'L' has an implicit capture.1322// AND1323// -- there is no enclosing closure1324// -- or, there is some enclosing closure 'E' that has already captured the1325// *enclosing object*, and every intervening closure (if any) between 'E'1326// and 'L' can implicitly capture the *enclosing object*.1327// -- or, every enclosing closure can implicitly capture the1328// *enclosing object*132913301331unsigned NumCapturingClosures = 0;1332for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {1333if (CapturingScopeInfo *CSI =1334dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {1335if (CSI->CXXThisCaptureIndex != 0) {1336// 'this' is already being captured; there isn't anything more to do.1337CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);1338break;1339}1340LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);1341if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {1342// This context can't implicitly capture 'this'; fail out.1343if (BuildAndDiagnose) {1344LSI->CallOperator->setInvalidDecl();1345Diag(Loc, diag::err_this_capture)1346<< (Explicit && idx == MaxFunctionScopesIndex);1347if (!Explicit)1348buildLambdaThisCaptureFixit(*this, LSI);1349}1350return true;1351}1352if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||1353CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||1354CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||1355CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||1356(Explicit && idx == MaxFunctionScopesIndex)) {1357// Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first1358// iteration through can be an explicit capture, all enclosing closures,1359// if any, must perform implicit captures.13601361// This closure can capture 'this'; continue looking upwards.1362NumCapturingClosures++;1363continue;1364}1365// This context can't implicitly capture 'this'; fail out.1366if (BuildAndDiagnose) {1367LSI->CallOperator->setInvalidDecl();1368Diag(Loc, diag::err_this_capture)1369<< (Explicit && idx == MaxFunctionScopesIndex);1370}1371if (!Explicit)1372buildLambdaThisCaptureFixit(*this, LSI);1373return true;1374}1375break;1376}1377if (!BuildAndDiagnose) return false;13781379// If we got here, then the closure at MaxFunctionScopesIndex on the1380// FunctionScopes stack, can capture the *enclosing object*, so capture it1381// (including implicit by-reference captures in any enclosing closures).13821383// In the loop below, respect the ByCopy flag only for the closure requesting1384// the capture (i.e. first iteration through the loop below). Ignore it for1385// all enclosing closure's up to NumCapturingClosures (since they must be1386// implicitly capturing the *enclosing object* by reference (see loop1387// above)).1388assert((!ByCopy ||1389isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&1390"Only a lambda can capture the enclosing object (referred to by "1391"*this) by copy");1392QualType ThisTy = getCurrentThisType();1393for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;1394--idx, --NumCapturingClosures) {1395CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);13961397// The type of the corresponding data member (not a 'this' pointer if 'by1398// copy').1399QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;14001401bool isNested = NumCapturingClosures > 1;1402CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);1403}1404return false;1405}14061407ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {1408// C++20 [expr.prim.this]p1:1409// The keyword this names a pointer to the object for which an1410// implicit object member function is invoked or a non-static1411// data member's initializer is evaluated.1412QualType ThisTy = getCurrentThisType();14131414if (CheckCXXThisType(Loc, ThisTy))1415return ExprError();14161417return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);1418}14191420bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) {1421if (!Type.isNull())1422return false;14231424// C++20 [expr.prim.this]p3:1425// If a declaration declares a member function or member function template1426// of a class X, the expression this is a prvalue of type1427// "pointer to cv-qualifier-seq X" wherever X is the current class between1428// the optional cv-qualifier-seq and the end of the function-definition,1429// member-declarator, or declarator. It shall not appear within the1430// declaration of either a static member function or an explicit object1431// member function of the current class (although its type and value1432// category are defined within such member functions as they are within1433// an implicit object member function).1434DeclContext *DC = getFunctionLevelDeclContext();1435const auto *Method = dyn_cast<CXXMethodDecl>(DC);1436if (Method && Method->isExplicitObjectMemberFunction()) {1437Diag(Loc, diag::err_invalid_this_use) << 1;1438} else if (Method && isLambdaCallWithExplicitObjectParameter(CurContext)) {1439Diag(Loc, diag::err_invalid_this_use) << 1;1440} else {1441Diag(Loc, diag::err_invalid_this_use) << 0;1442}1443return true;1444}14451446Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,1447bool IsImplicit) {1448auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);1449MarkThisReferenced(This);1450return This;1451}14521453void Sema::MarkThisReferenced(CXXThisExpr *This) {1454CheckCXXThisCapture(This->getExprLoc());1455if (This->isTypeDependent())1456return;14571458// Check if 'this' is captured by value in a lambda with a dependent explicit1459// object parameter, and mark it as type-dependent as well if so.1460auto IsDependent = [&]() {1461for (auto *Scope : llvm::reverse(FunctionScopes)) {1462auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);1463if (!LSI)1464continue;14651466if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&1467LSI->AfterParameterList)1468return false;14691470// If this lambda captures 'this' by value, then 'this' is dependent iff1471// this lambda has a dependent explicit object parameter. If we can't1472// determine whether it does (e.g. because the CXXMethodDecl's type is1473// null), assume it doesn't.1474if (LSI->isCXXThisCaptured()) {1475if (!LSI->getCXXThisCapture().isCopyCapture())1476continue;14771478const auto *MD = LSI->CallOperator;1479if (MD->getType().isNull())1480return false;14811482const auto *Ty = MD->getType()->getAs<FunctionProtoType>();1483return Ty && MD->isExplicitObjectMemberFunction() &&1484Ty->getParamType(0)->isDependentType();1485}1486}1487return false;1488}();14891490This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);1491}14921493bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {1494// If we're outside the body of a member function, then we'll have a specified1495// type for 'this'.1496if (CXXThisTypeOverride.isNull())1497return false;14981499// Determine whether we're looking into a class that's currently being1500// defined.1501CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();1502return Class && Class->isBeingDefined();1503}15041505ExprResult1506Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,1507SourceLocation LParenOrBraceLoc,1508MultiExprArg exprs,1509SourceLocation RParenOrBraceLoc,1510bool ListInitialization) {1511if (!TypeRep)1512return ExprError();15131514TypeSourceInfo *TInfo;1515QualType Ty = GetTypeFromParser(TypeRep, &TInfo);1516if (!TInfo)1517TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());15181519auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,1520RParenOrBraceLoc, ListInitialization);1521// Avoid creating a non-type-dependent expression that contains typos.1522// Non-type-dependent expressions are liable to be discarded without1523// checking for embedded typos.1524if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&1525!Result.get()->isTypeDependent())1526Result = CorrectDelayedTyposInExpr(Result.get());1527else if (Result.isInvalid())1528Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),1529RParenOrBraceLoc, exprs, Ty);1530return Result;1531}15321533ExprResult1534Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,1535SourceLocation LParenOrBraceLoc,1536MultiExprArg Exprs,1537SourceLocation RParenOrBraceLoc,1538bool ListInitialization) {1539QualType Ty = TInfo->getType();1540SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();15411542assert((!ListInitialization || Exprs.size() == 1) &&1543"List initialization must have exactly one expression.");1544SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);15451546InitializedEntity Entity =1547InitializedEntity::InitializeTemporary(Context, TInfo);1548InitializationKind Kind =1549Exprs.size()1550? ListInitialization1551? InitializationKind::CreateDirectList(1552TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)1553: InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,1554RParenOrBraceLoc)1555: InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,1556RParenOrBraceLoc);15571558// C++17 [expr.type.conv]p1:1559// If the type is a placeholder for a deduced class type, [...perform class1560// template argument deduction...]1561// C++23:1562// Otherwise, if the type contains a placeholder type, it is replaced by the1563// type determined by placeholder type deduction.1564DeducedType *Deduced = Ty->getContainedDeducedType();1565if (Deduced && !Deduced->isDeduced() &&1566isa<DeducedTemplateSpecializationType>(Deduced)) {1567Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,1568Kind, Exprs);1569if (Ty.isNull())1570return ExprError();1571Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);1572} else if (Deduced && !Deduced->isDeduced()) {1573MultiExprArg Inits = Exprs;1574if (ListInitialization) {1575auto *ILE = cast<InitListExpr>(Exprs[0]);1576Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());1577}15781579if (Inits.empty())1580return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)1581<< Ty << FullRange);1582if (Inits.size() > 1) {1583Expr *FirstBad = Inits[1];1584return ExprError(Diag(FirstBad->getBeginLoc(),1585diag::err_auto_expr_init_multiple_expressions)1586<< Ty << FullRange);1587}1588if (getLangOpts().CPlusPlus23) {1589if (Ty->getAs<AutoType>())1590Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;1591}1592Expr *Deduce = Inits[0];1593if (isa<InitListExpr>(Deduce))1594return ExprError(1595Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)1596<< ListInitialization << Ty << FullRange);1597QualType DeducedType;1598TemplateDeductionInfo Info(Deduce->getExprLoc());1599TemplateDeductionResult Result =1600DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);1601if (Result != TemplateDeductionResult::Success &&1602Result != TemplateDeductionResult::AlreadyDiagnosed)1603return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)1604<< Ty << Deduce->getType() << FullRange1605<< Deduce->getSourceRange());1606if (DeducedType.isNull()) {1607assert(Result == TemplateDeductionResult::AlreadyDiagnosed);1608return ExprError();1609}16101611Ty = DeducedType;1612Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);1613}16141615if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs))1616return CXXUnresolvedConstructExpr::Create(1617Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,1618RParenOrBraceLoc, ListInitialization);16191620// C++ [expr.type.conv]p1:1621// If the expression list is a parenthesized single expression, the type1622// conversion expression is equivalent (in definedness, and if defined in1623// meaning) to the corresponding cast expression.1624if (Exprs.size() == 1 && !ListInitialization &&1625!isa<InitListExpr>(Exprs[0])) {1626Expr *Arg = Exprs[0];1627return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,1628RParenOrBraceLoc);1629}16301631// For an expression of the form T(), T shall not be an array type.1632QualType ElemTy = Ty;1633if (Ty->isArrayType()) {1634if (!ListInitialization)1635return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)1636<< FullRange);1637ElemTy = Context.getBaseElementType(Ty);1638}16391640// Only construct objects with object types.1641// The standard doesn't explicitly forbid function types here, but that's an1642// obvious oversight, as there's no way to dynamically construct a function1643// in general.1644if (Ty->isFunctionType())1645return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)1646<< Ty << FullRange);16471648// C++17 [expr.type.conv]p2:1649// If the type is cv void and the initializer is (), the expression is a1650// prvalue of the specified type that performs no initialization.1651if (!Ty->isVoidType() &&1652RequireCompleteType(TyBeginLoc, ElemTy,1653diag::err_invalid_incomplete_type_use, FullRange))1654return ExprError();16551656// Otherwise, the expression is a prvalue of the specified type whose1657// result object is direct-initialized (11.6) with the initializer.1658InitializationSequence InitSeq(*this, Entity, Kind, Exprs);1659ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);16601661if (Result.isInvalid())1662return Result;16631664Expr *Inner = Result.get();1665if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))1666Inner = BTE->getSubExpr();1667if (auto *CE = dyn_cast<ConstantExpr>(Inner);1668CE && CE->isImmediateInvocation())1669Inner = CE->getSubExpr();1670if (!isa<CXXTemporaryObjectExpr>(Inner) &&1671!isa<CXXScalarValueInitExpr>(Inner)) {1672// If we created a CXXTemporaryObjectExpr, that node also represents the1673// functional cast. Otherwise, create an explicit cast to represent1674// the syntactic form of a functional-style cast that was used here.1675//1676// FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr1677// would give a more consistent AST representation than using a1678// CXXTemporaryObjectExpr. It's also weird that the functional cast1679// is sometimes handled by initialization and sometimes not.1680QualType ResultType = Result.get()->getType();1681SourceRange Locs = ListInitialization1682? SourceRange()1683: SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);1684Result = CXXFunctionalCastExpr::Create(1685Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,1686Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),1687Locs.getBegin(), Locs.getEnd());1688}16891690return Result;1691}16921693bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {1694// [CUDA] Ignore this function, if we can't call it.1695const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);1696if (getLangOpts().CUDA) {1697auto CallPreference = CUDA().IdentifyPreference(Caller, Method);1698// If it's not callable at all, it's not the right function.1699if (CallPreference < SemaCUDA::CFP_WrongSide)1700return false;1701if (CallPreference == SemaCUDA::CFP_WrongSide) {1702// Maybe. We have to check if there are better alternatives.1703DeclContext::lookup_result R =1704Method->getDeclContext()->lookup(Method->getDeclName());1705for (const auto *D : R) {1706if (const auto *FD = dyn_cast<FunctionDecl>(D)) {1707if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)1708return false;1709}1710}1711// We've found no better variants.1712}1713}17141715SmallVector<const FunctionDecl*, 4> PreventedBy;1716bool Result = Method->isUsualDeallocationFunction(PreventedBy);17171718if (Result || !getLangOpts().CUDA || PreventedBy.empty())1719return Result;17201721// In case of CUDA, return true if none of the 1-argument deallocator1722// functions are actually callable.1723return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {1724assert(FD->getNumParams() == 1 &&1725"Only single-operand functions should be in PreventedBy");1726return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;1727});1728}17291730/// Determine whether the given function is a non-placement1731/// deallocation function.1732static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {1733if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))1734return S.isUsualDeallocationFunction(Method);17351736if (FD->getOverloadedOperator() != OO_Delete &&1737FD->getOverloadedOperator() != OO_Array_Delete)1738return false;17391740unsigned UsualParams = 1;17411742if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&1743S.Context.hasSameUnqualifiedType(1744FD->getParamDecl(UsualParams)->getType(),1745S.Context.getSizeType()))1746++UsualParams;17471748if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&1749S.Context.hasSameUnqualifiedType(1750FD->getParamDecl(UsualParams)->getType(),1751S.Context.getTypeDeclType(S.getStdAlignValT())))1752++UsualParams;17531754return UsualParams == FD->getNumParams();1755}17561757namespace {1758struct UsualDeallocFnInfo {1759UsualDeallocFnInfo() : Found(), FD(nullptr) {}1760UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)1761: Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),1762Destroying(false), HasSizeT(false), HasAlignValT(false),1763CUDAPref(SemaCUDA::CFP_Native) {1764// A function template declaration is never a usual deallocation function.1765if (!FD)1766return;1767unsigned NumBaseParams = 1;1768if (FD->isDestroyingOperatorDelete()) {1769Destroying = true;1770++NumBaseParams;1771}17721773if (NumBaseParams < FD->getNumParams() &&1774S.Context.hasSameUnqualifiedType(1775FD->getParamDecl(NumBaseParams)->getType(),1776S.Context.getSizeType())) {1777++NumBaseParams;1778HasSizeT = true;1779}17801781if (NumBaseParams < FD->getNumParams() &&1782FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {1783++NumBaseParams;1784HasAlignValT = true;1785}17861787// In CUDA, determine how much we'd like / dislike to call this.1788if (S.getLangOpts().CUDA)1789CUDAPref = S.CUDA().IdentifyPreference(1790S.getCurFunctionDecl(/*AllowLambda=*/true), FD);1791}17921793explicit operator bool() const { return FD; }17941795bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,1796bool WantAlign) const {1797// C++ P0722:1798// A destroying operator delete is preferred over a non-destroying1799// operator delete.1800if (Destroying != Other.Destroying)1801return Destroying;18021803// C++17 [expr.delete]p10:1804// If the type has new-extended alignment, a function with a parameter1805// of type std::align_val_t is preferred; otherwise a function without1806// such a parameter is preferred1807if (HasAlignValT != Other.HasAlignValT)1808return HasAlignValT == WantAlign;18091810if (HasSizeT != Other.HasSizeT)1811return HasSizeT == WantSize;18121813// Use CUDA call preference as a tiebreaker.1814return CUDAPref > Other.CUDAPref;1815}18161817DeclAccessPair Found;1818FunctionDecl *FD;1819bool Destroying, HasSizeT, HasAlignValT;1820SemaCUDA::CUDAFunctionPreference CUDAPref;1821};1822}18231824/// Determine whether a type has new-extended alignment. This may be called when1825/// the type is incomplete (for a delete-expression with an incomplete pointee1826/// type), in which case it will conservatively return false if the alignment is1827/// not known.1828static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {1829return S.getLangOpts().AlignedAllocation &&1830S.getASTContext().getTypeAlignIfKnown(AllocType) >1831S.getASTContext().getTargetInfo().getNewAlign();1832}18331834/// Select the correct "usual" deallocation function to use from a selection of1835/// deallocation functions (either global or class-scope).1836static UsualDeallocFnInfo resolveDeallocationOverload(1837Sema &S, LookupResult &R, bool WantSize, bool WantAlign,1838llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {1839UsualDeallocFnInfo Best;18401841for (auto I = R.begin(), E = R.end(); I != E; ++I) {1842UsualDeallocFnInfo Info(S, I.getPair());1843if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||1844Info.CUDAPref == SemaCUDA::CFP_Never)1845continue;18461847if (!Best) {1848Best = Info;1849if (BestFns)1850BestFns->push_back(Info);1851continue;1852}18531854if (Best.isBetterThan(Info, WantSize, WantAlign))1855continue;18561857// If more than one preferred function is found, all non-preferred1858// functions are eliminated from further consideration.1859if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))1860BestFns->clear();18611862Best = Info;1863if (BestFns)1864BestFns->push_back(Info);1865}18661867return Best;1868}18691870/// Determine whether a given type is a class for which 'delete[]' would call1871/// a member 'operator delete[]' with a 'size_t' parameter. This implies that1872/// we need to store the array size (even if the type is1873/// trivially-destructible).1874static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,1875QualType allocType) {1876const RecordType *record =1877allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();1878if (!record) return false;18791880// Try to find an operator delete[] in class scope.18811882DeclarationName deleteName =1883S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);1884LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);1885S.LookupQualifiedName(ops, record->getDecl());18861887// We're just doing this for information.1888ops.suppressDiagnostics();18891890// Very likely: there's no operator delete[].1891if (ops.empty()) return false;18921893// If it's ambiguous, it should be illegal to call operator delete[]1894// on this thing, so it doesn't matter if we allocate extra space or not.1895if (ops.isAmbiguous()) return false;18961897// C++17 [expr.delete]p10:1898// If the deallocation functions have class scope, the one without a1899// parameter of type std::size_t is selected.1900auto Best = resolveDeallocationOverload(1901S, ops, /*WantSize*/false,1902/*WantAlign*/hasNewExtendedAlignment(S, allocType));1903return Best && Best.HasSizeT;1904}19051906ExprResult1907Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,1908SourceLocation PlacementLParen, MultiExprArg PlacementArgs,1909SourceLocation PlacementRParen, SourceRange TypeIdParens,1910Declarator &D, Expr *Initializer) {1911std::optional<Expr *> ArraySize;1912// If the specified type is an array, unwrap it and save the expression.1913if (D.getNumTypeObjects() > 0 &&1914D.getTypeObject(0).Kind == DeclaratorChunk::Array) {1915DeclaratorChunk &Chunk = D.getTypeObject(0);1916if (D.getDeclSpec().hasAutoTypeSpec())1917return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)1918<< D.getSourceRange());1919if (Chunk.Arr.hasStatic)1920return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)1921<< D.getSourceRange());1922if (!Chunk.Arr.NumElts && !Initializer)1923return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)1924<< D.getSourceRange());19251926ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);1927D.DropFirstTypeObject();1928}19291930// Every dimension shall be of constant size.1931if (ArraySize) {1932for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {1933if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)1934break;19351936DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;1937if (Expr *NumElts = (Expr *)Array.NumElts) {1938if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {1939// FIXME: GCC permits constant folding here. We should either do so consistently1940// or not do so at all, rather than changing behavior in C++14 onwards.1941if (getLangOpts().CPlusPlus14) {1942// C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator1943// shall be a converted constant expression (5.19) of type std::size_t1944// and shall evaluate to a strictly positive value.1945llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));1946Array.NumElts1947= CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,1948CCEK_ArrayBound)1949.get();1950} else {1951Array.NumElts =1952VerifyIntegerConstantExpression(1953NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)1954.get();1955}1956if (!Array.NumElts)1957return ExprError();1958}1959}1960}1961}19621963TypeSourceInfo *TInfo = GetTypeForDeclarator(D);1964QualType AllocType = TInfo->getType();1965if (D.isInvalidType())1966return ExprError();19671968SourceRange DirectInitRange;1969if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))1970DirectInitRange = List->getSourceRange();19711972return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,1973PlacementLParen, PlacementArgs, PlacementRParen,1974TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,1975Initializer);1976}19771978static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style,1979Expr *Init, bool IsCPlusPlus20) {1980if (!Init)1981return true;1982if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))1983return IsCPlusPlus20 || PLE->getNumExprs() == 0;1984if (isa<ImplicitValueInitExpr>(Init))1985return true;1986else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))1987return !CCE->isListInitialization() &&1988CCE->getConstructor()->isDefaultConstructor();1989else if (Style == CXXNewInitializationStyle::Braces) {1990assert(isa<InitListExpr>(Init) &&1991"Shouldn't create list CXXConstructExprs for arrays.");1992return true;1993}1994return false;1995}19961997bool1998Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {1999if (!getLangOpts().AlignedAllocationUnavailable)2000return false;2001if (FD.isDefined())2002return false;2003std::optional<unsigned> AlignmentParam;2004if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&2005AlignmentParam)2006return true;2007return false;2008}20092010// Emit a diagnostic if an aligned allocation/deallocation function that is not2011// implemented in the standard library is selected.2012void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,2013SourceLocation Loc) {2014if (isUnavailableAlignedAllocationFunction(FD)) {2015const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();2016StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(2017getASTContext().getTargetInfo().getPlatformName());2018VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());20192020OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();2021bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;2022Diag(Loc, diag::err_aligned_allocation_unavailable)2023<< IsDelete << FD.getType().getAsString() << OSName2024<< OSVersion.getAsString() << OSVersion.empty();2025Diag(Loc, diag::note_silence_aligned_allocation_unavailable);2026}2027}20282029ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,2030SourceLocation PlacementLParen,2031MultiExprArg PlacementArgs,2032SourceLocation PlacementRParen,2033SourceRange TypeIdParens, QualType AllocType,2034TypeSourceInfo *AllocTypeInfo,2035std::optional<Expr *> ArraySize,2036SourceRange DirectInitRange, Expr *Initializer) {2037SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();2038SourceLocation StartLoc = Range.getBegin();20392040CXXNewInitializationStyle InitStyle;2041if (DirectInitRange.isValid()) {2042assert(Initializer && "Have parens but no initializer.");2043InitStyle = CXXNewInitializationStyle::Parens;2044} else if (isa_and_nonnull<InitListExpr>(Initializer))2045InitStyle = CXXNewInitializationStyle::Braces;2046else {2047assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||2048isa<CXXConstructExpr>(Initializer)) &&2049"Initializer expression that cannot have been implicitly created.");2050InitStyle = CXXNewInitializationStyle::None;2051}20522053MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);2054if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {2055assert(InitStyle == CXXNewInitializationStyle::Parens &&2056"paren init for non-call init");2057Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());2058}20592060// C++11 [expr.new]p15:2061// A new-expression that creates an object of type T initializes that2062// object as follows:2063InitializationKind Kind = [&] {2064switch (InitStyle) {2065// - If the new-initializer is omitted, the object is default-2066// initialized (8.5); if no initialization is performed,2067// the object has indeterminate value2068case CXXNewInitializationStyle::None:2069return InitializationKind::CreateDefault(TypeRange.getBegin());2070// - Otherwise, the new-initializer is interpreted according to the2071// initialization rules of 8.5 for direct-initialization.2072case CXXNewInitializationStyle::Parens:2073return InitializationKind::CreateDirect(TypeRange.getBegin(),2074DirectInitRange.getBegin(),2075DirectInitRange.getEnd());2076case CXXNewInitializationStyle::Braces:2077return InitializationKind::CreateDirectList(TypeRange.getBegin(),2078Initializer->getBeginLoc(),2079Initializer->getEndLoc());2080}2081llvm_unreachable("Unknown initialization kind");2082}();20832084// C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.2085auto *Deduced = AllocType->getContainedDeducedType();2086if (Deduced && !Deduced->isDeduced() &&2087isa<DeducedTemplateSpecializationType>(Deduced)) {2088if (ArraySize)2089return ExprError(2090Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),2091diag::err_deduced_class_template_compound_type)2092<< /*array*/ 22093<< (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));20942095InitializedEntity Entity2096= InitializedEntity::InitializeNew(StartLoc, AllocType);2097AllocType = DeduceTemplateSpecializationFromInitializer(2098AllocTypeInfo, Entity, Kind, Exprs);2099if (AllocType.isNull())2100return ExprError();2101} else if (Deduced && !Deduced->isDeduced()) {2102MultiExprArg Inits = Exprs;2103bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);2104if (Braced) {2105auto *ILE = cast<InitListExpr>(Exprs[0]);2106Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());2107}21082109if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())2110return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)2111<< AllocType << TypeRange);2112if (Inits.size() > 1) {2113Expr *FirstBad = Inits[1];2114return ExprError(Diag(FirstBad->getBeginLoc(),2115diag::err_auto_new_ctor_multiple_expressions)2116<< AllocType << TypeRange);2117}2118if (Braced && !getLangOpts().CPlusPlus17)2119Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)2120<< AllocType << TypeRange;2121Expr *Deduce = Inits[0];2122if (isa<InitListExpr>(Deduce))2123return ExprError(2124Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)2125<< Braced << AllocType << TypeRange);2126QualType DeducedType;2127TemplateDeductionInfo Info(Deduce->getExprLoc());2128TemplateDeductionResult Result =2129DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);2130if (Result != TemplateDeductionResult::Success &&2131Result != TemplateDeductionResult::AlreadyDiagnosed)2132return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)2133<< AllocType << Deduce->getType() << TypeRange2134<< Deduce->getSourceRange());2135if (DeducedType.isNull()) {2136assert(Result == TemplateDeductionResult::AlreadyDiagnosed);2137return ExprError();2138}2139AllocType = DeducedType;2140}21412142// Per C++0x [expr.new]p5, the type being constructed may be a2143// typedef of an array type.2144if (!ArraySize) {2145if (const ConstantArrayType *Array2146= Context.getAsConstantArrayType(AllocType)) {2147ArraySize = IntegerLiteral::Create(Context, Array->getSize(),2148Context.getSizeType(),2149TypeRange.getEnd());2150AllocType = Array->getElementType();2151}2152}21532154if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))2155return ExprError();21562157if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))2158return ExprError();21592160// In ARC, infer 'retaining' for the allocated2161if (getLangOpts().ObjCAutoRefCount &&2162AllocType.getObjCLifetime() == Qualifiers::OCL_None &&2163AllocType->isObjCLifetimeType()) {2164AllocType = Context.getLifetimeQualifiedType(AllocType,2165AllocType->getObjCARCImplicitLifetime());2166}21672168QualType ResultType = Context.getPointerType(AllocType);21692170if (ArraySize && *ArraySize &&2171(*ArraySize)->getType()->isNonOverloadPlaceholderType()) {2172ExprResult result = CheckPlaceholderExpr(*ArraySize);2173if (result.isInvalid()) return ExprError();2174ArraySize = result.get();2175}2176// C++98 5.3.4p6: "The expression in a direct-new-declarator shall have2177// integral or enumeration type with a non-negative value."2178// C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped2179// enumeration type, or a class type for which a single non-explicit2180// conversion function to integral or unscoped enumeration type exists.2181// C++1y [expr.new]p6: The expression [...] is implicitly converted to2182// std::size_t.2183std::optional<uint64_t> KnownArraySize;2184if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {2185ExprResult ConvertedSize;2186if (getLangOpts().CPlusPlus14) {2187assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");21882189ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),2190AA_Converting);21912192if (!ConvertedSize.isInvalid() &&2193(*ArraySize)->getType()->getAs<RecordType>())2194// Diagnose the compatibility of this conversion.2195Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)2196<< (*ArraySize)->getType() << 0 << "'size_t'";2197} else {2198class SizeConvertDiagnoser : public ICEConvertDiagnoser {2199protected:2200Expr *ArraySize;22012202public:2203SizeConvertDiagnoser(Expr *ArraySize)2204: ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),2205ArraySize(ArraySize) {}22062207SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,2208QualType T) override {2209return S.Diag(Loc, diag::err_array_size_not_integral)2210<< S.getLangOpts().CPlusPlus11 << T;2211}22122213SemaDiagnosticBuilder diagnoseIncomplete(2214Sema &S, SourceLocation Loc, QualType T) override {2215return S.Diag(Loc, diag::err_array_size_incomplete_type)2216<< T << ArraySize->getSourceRange();2217}22182219SemaDiagnosticBuilder diagnoseExplicitConv(2220Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {2221return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;2222}22232224SemaDiagnosticBuilder noteExplicitConv(2225Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {2226return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)2227<< ConvTy->isEnumeralType() << ConvTy;2228}22292230SemaDiagnosticBuilder diagnoseAmbiguous(2231Sema &S, SourceLocation Loc, QualType T) override {2232return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;2233}22342235SemaDiagnosticBuilder noteAmbiguous(2236Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {2237return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)2238<< ConvTy->isEnumeralType() << ConvTy;2239}22402241SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,2242QualType T,2243QualType ConvTy) override {2244return S.Diag(Loc,2245S.getLangOpts().CPlusPlus112246? diag::warn_cxx98_compat_array_size_conversion2247: diag::ext_array_size_conversion)2248<< T << ConvTy->isEnumeralType() << ConvTy;2249}2250} SizeDiagnoser(*ArraySize);22512252ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,2253SizeDiagnoser);2254}2255if (ConvertedSize.isInvalid())2256return ExprError();22572258ArraySize = ConvertedSize.get();2259QualType SizeType = (*ArraySize)->getType();22602261if (!SizeType->isIntegralOrUnscopedEnumerationType())2262return ExprError();22632264// C++98 [expr.new]p7:2265// The expression in a direct-new-declarator shall have integral type2266// with a non-negative value.2267//2268// Let's see if this is a constant < 0. If so, we reject it out of hand,2269// per CWG1464. Otherwise, if it's not a constant, we must have an2270// unparenthesized array type.22712272// We've already performed any required implicit conversion to integer or2273// unscoped enumeration type.2274// FIXME: Per CWG1464, we are required to check the value prior to2275// converting to size_t. This will never find a negative array size in2276// C++14 onwards, because Value is always unsigned here!2277if (std::optional<llvm::APSInt> Value =2278(*ArraySize)->getIntegerConstantExpr(Context)) {2279if (Value->isSigned() && Value->isNegative()) {2280return ExprError(Diag((*ArraySize)->getBeginLoc(),2281diag::err_typecheck_negative_array_size)2282<< (*ArraySize)->getSourceRange());2283}22842285if (!AllocType->isDependentType()) {2286unsigned ActiveSizeBits =2287ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);2288if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))2289return ExprError(2290Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)2291<< toString(*Value, 10) << (*ArraySize)->getSourceRange());2292}22932294KnownArraySize = Value->getZExtValue();2295} else if (TypeIdParens.isValid()) {2296// Can't have dynamic array size when the type-id is in parentheses.2297Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)2298<< (*ArraySize)->getSourceRange()2299<< FixItHint::CreateRemoval(TypeIdParens.getBegin())2300<< FixItHint::CreateRemoval(TypeIdParens.getEnd());23012302TypeIdParens = SourceRange();2303}23042305// Note that we do *not* convert the argument in any way. It can2306// be signed, larger than size_t, whatever.2307}23082309FunctionDecl *OperatorNew = nullptr;2310FunctionDecl *OperatorDelete = nullptr;2311unsigned Alignment =2312AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);2313unsigned NewAlignment = Context.getTargetInfo().getNewAlign();2314bool PassAlignment = getLangOpts().AlignedAllocation &&2315Alignment > NewAlignment;23162317if (CheckArgsForPlaceholders(PlacementArgs))2318return ExprError();23192320AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;2321if (!AllocType->isDependentType() &&2322!Expr::hasAnyTypeDependentArguments(PlacementArgs) &&2323FindAllocationFunctions(2324StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,2325AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,2326OperatorNew, OperatorDelete))2327return ExprError();23282329// If this is an array allocation, compute whether the usual array2330// deallocation function for the type has a size_t parameter.2331bool UsualArrayDeleteWantsSize = false;2332if (ArraySize && !AllocType->isDependentType())2333UsualArrayDeleteWantsSize =2334doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);23352336SmallVector<Expr *, 8> AllPlaceArgs;2337if (OperatorNew) {2338auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();2339VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction2340: VariadicDoesNotApply;23412342// We've already converted the placement args, just fill in any default2343// arguments. Skip the first parameter because we don't have a corresponding2344// argument. Skip the second parameter too if we're passing in the2345// alignment; we've already filled it in.2346unsigned NumImplicitArgs = PassAlignment ? 2 : 1;2347if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,2348NumImplicitArgs, PlacementArgs, AllPlaceArgs,2349CallType))2350return ExprError();23512352if (!AllPlaceArgs.empty())2353PlacementArgs = AllPlaceArgs;23542355// We would like to perform some checking on the given `operator new` call,2356// but the PlacementArgs does not contain the implicit arguments,2357// namely allocation size and maybe allocation alignment,2358// so we need to conjure them.23592360QualType SizeTy = Context.getSizeType();2361unsigned SizeTyWidth = Context.getTypeSize(SizeTy);23622363llvm::APInt SingleEltSize(2364SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());23652366// How many bytes do we want to allocate here?2367std::optional<llvm::APInt> AllocationSize;2368if (!ArraySize && !AllocType->isDependentType()) {2369// For non-array operator new, we only want to allocate one element.2370AllocationSize = SingleEltSize;2371} else if (KnownArraySize && !AllocType->isDependentType()) {2372// For array operator new, only deal with static array size case.2373bool Overflow;2374AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)2375.umul_ov(SingleEltSize, Overflow);2376(void)Overflow;2377assert(2378!Overflow &&2379"Expected that all the overflows would have been handled already.");2380}23812382IntegerLiteral AllocationSizeLiteral(2383Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),2384SizeTy, SourceLocation());2385// Otherwise, if we failed to constant-fold the allocation size, we'll2386// just give up and pass-in something opaque, that isn't a null pointer.2387OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,2388OK_Ordinary, /*SourceExpr=*/nullptr);23892390// Let's synthesize the alignment argument in case we will need it.2391// Since we *really* want to allocate these on stack, this is slightly ugly2392// because there might not be a `std::align_val_t` type.2393EnumDecl *StdAlignValT = getStdAlignValT();2394QualType AlignValT =2395StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;2396IntegerLiteral AlignmentLiteral(2397Context,2398llvm::APInt(Context.getTypeSize(SizeTy),2399Alignment / Context.getCharWidth()),2400SizeTy, SourceLocation());2401ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,2402CK_IntegralCast, &AlignmentLiteral,2403VK_PRValue, FPOptionsOverride());24042405// Adjust placement args by prepending conjured size and alignment exprs.2406llvm::SmallVector<Expr *, 8> CallArgs;2407CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());2408CallArgs.emplace_back(AllocationSize2409? static_cast<Expr *>(&AllocationSizeLiteral)2410: &OpaqueAllocationSize);2411if (PassAlignment)2412CallArgs.emplace_back(&DesiredAlignment);2413CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());24142415DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);24162417checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,2418/*IsMemberFunction=*/false, StartLoc, Range, CallType);24192420// Warn if the type is over-aligned and is being allocated by (unaligned)2421// global operator new.2422if (PlacementArgs.empty() && !PassAlignment &&2423(OperatorNew->isImplicit() ||2424(OperatorNew->getBeginLoc().isValid() &&2425getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {2426if (Alignment > NewAlignment)2427Diag(StartLoc, diag::warn_overaligned_type)2428<< AllocType2429<< unsigned(Alignment / Context.getCharWidth())2430<< unsigned(NewAlignment / Context.getCharWidth());2431}2432}24332434// Array 'new' can't have any initializers except empty parentheses.2435// Initializer lists are also allowed, in C++11. Rely on the parser for the2436// dialect distinction.2437if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,2438getLangOpts().CPlusPlus20)) {2439SourceRange InitRange(Exprs.front()->getBeginLoc(),2440Exprs.back()->getEndLoc());2441Diag(StartLoc, diag::err_new_array_init_args) << InitRange;2442return ExprError();2443}24442445// If we can perform the initialization, and we've not already done so,2446// do it now.2447if (!AllocType->isDependentType() &&2448!Expr::hasAnyTypeDependentArguments(Exprs)) {2449// The type we initialize is the complete type, including the array bound.2450QualType InitType;2451if (KnownArraySize)2452InitType = Context.getConstantArrayType(2453AllocType,2454llvm::APInt(Context.getTypeSize(Context.getSizeType()),2455*KnownArraySize),2456*ArraySize, ArraySizeModifier::Normal, 0);2457else if (ArraySize)2458InitType = Context.getIncompleteArrayType(AllocType,2459ArraySizeModifier::Normal, 0);2460else2461InitType = AllocType;24622463InitializedEntity Entity2464= InitializedEntity::InitializeNew(StartLoc, InitType);2465InitializationSequence InitSeq(*this, Entity, Kind, Exprs);2466ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);2467if (FullInit.isInvalid())2468return ExprError();24692470// FullInit is our initializer; strip off CXXBindTemporaryExprs, because2471// we don't want the initialized object to be destructed.2472// FIXME: We should not create these in the first place.2473if (CXXBindTemporaryExpr *Binder =2474dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))2475FullInit = Binder->getSubExpr();24762477Initializer = FullInit.get();24782479// FIXME: If we have a KnownArraySize, check that the array bound of the2480// initializer is no greater than that constant value.24812482if (ArraySize && !*ArraySize) {2483auto *CAT = Context.getAsConstantArrayType(Initializer->getType());2484if (CAT) {2485// FIXME: Track that the array size was inferred rather than explicitly2486// specified.2487ArraySize = IntegerLiteral::Create(2488Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());2489} else {2490Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)2491<< Initializer->getSourceRange();2492}2493}2494}24952496// Mark the new and delete operators as referenced.2497if (OperatorNew) {2498if (DiagnoseUseOfDecl(OperatorNew, StartLoc))2499return ExprError();2500MarkFunctionReferenced(StartLoc, OperatorNew);2501}2502if (OperatorDelete) {2503if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))2504return ExprError();2505MarkFunctionReferenced(StartLoc, OperatorDelete);2506}25072508return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,2509PassAlignment, UsualArrayDeleteWantsSize,2510PlacementArgs, TypeIdParens, ArraySize, InitStyle,2511Initializer, ResultType, AllocTypeInfo, Range,2512DirectInitRange);2513}25142515bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,2516SourceRange R) {2517// C++ 5.3.4p1: "[The] type shall be a complete object type, but not an2518// abstract class type or array thereof.2519if (AllocType->isFunctionType())2520return Diag(Loc, diag::err_bad_new_type)2521<< AllocType << 0 << R;2522else if (AllocType->isReferenceType())2523return Diag(Loc, diag::err_bad_new_type)2524<< AllocType << 1 << R;2525else if (!AllocType->isDependentType() &&2526RequireCompleteSizedType(2527Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))2528return true;2529else if (RequireNonAbstractType(Loc, AllocType,2530diag::err_allocation_of_abstract_type))2531return true;2532else if (AllocType->isVariablyModifiedType())2533return Diag(Loc, diag::err_variably_modified_new_type)2534<< AllocType;2535else if (AllocType.getAddressSpace() != LangAS::Default &&2536!getLangOpts().OpenCLCPlusPlus)2537return Diag(Loc, diag::err_address_space_qualified_new)2538<< AllocType.getUnqualifiedType()2539<< AllocType.getQualifiers().getAddressSpaceAttributePrintValue();2540else if (getLangOpts().ObjCAutoRefCount) {2541if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {2542QualType BaseAllocType = Context.getBaseElementType(AT);2543if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&2544BaseAllocType->isObjCLifetimeType())2545return Diag(Loc, diag::err_arc_new_array_without_ownership)2546<< BaseAllocType;2547}2548}25492550return false;2551}25522553static bool resolveAllocationOverload(2554Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,2555bool &PassAlignment, FunctionDecl *&Operator,2556OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {2557OverloadCandidateSet Candidates(R.getNameLoc(),2558OverloadCandidateSet::CSK_Normal);2559for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();2560Alloc != AllocEnd; ++Alloc) {2561// Even member operator new/delete are implicitly treated as2562// static, so don't use AddMemberCandidate.2563NamedDecl *D = (*Alloc)->getUnderlyingDecl();25642565if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {2566S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),2567/*ExplicitTemplateArgs=*/nullptr, Args,2568Candidates,2569/*SuppressUserConversions=*/false);2570continue;2571}25722573FunctionDecl *Fn = cast<FunctionDecl>(D);2574S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,2575/*SuppressUserConversions=*/false);2576}25772578// Do the resolution.2579OverloadCandidateSet::iterator Best;2580switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {2581case OR_Success: {2582// Got one!2583FunctionDecl *FnDecl = Best->Function;2584if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),2585Best->FoundDecl) == Sema::AR_inaccessible)2586return true;25872588Operator = FnDecl;2589return false;2590}25912592case OR_No_Viable_Function:2593// C++17 [expr.new]p13:2594// If no matching function is found and the allocated object type has2595// new-extended alignment, the alignment argument is removed from the2596// argument list, and overload resolution is performed again.2597if (PassAlignment) {2598PassAlignment = false;2599AlignArg = Args[1];2600Args.erase(Args.begin() + 1);2601return resolveAllocationOverload(S, R, Range, Args, PassAlignment,2602Operator, &Candidates, AlignArg,2603Diagnose);2604}26052606// MSVC will fall back on trying to find a matching global operator new2607// if operator new[] cannot be found. Also, MSVC will leak by not2608// generating a call to operator delete or operator delete[], but we2609// will not replicate that bug.2610// FIXME: Find out how this interacts with the std::align_val_t fallback2611// once MSVC implements it.2612if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&2613S.Context.getLangOpts().MSVCCompat) {2614R.clear();2615R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));2616S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());2617// FIXME: This will give bad diagnostics pointing at the wrong functions.2618return resolveAllocationOverload(S, R, Range, Args, PassAlignment,2619Operator, /*Candidates=*/nullptr,2620/*AlignArg=*/nullptr, Diagnose);2621}26222623if (Diagnose) {2624// If this is an allocation of the form 'new (p) X' for some object2625// pointer p (or an expression that will decay to such a pointer),2626// diagnose the missing inclusion of <new>.2627if (!R.isClassLookup() && Args.size() == 2 &&2628(Args[1]->getType()->isObjectPointerType() ||2629Args[1]->getType()->isArrayType())) {2630S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)2631<< R.getLookupName() << Range;2632// Listing the candidates is unlikely to be useful; skip it.2633return true;2634}26352636// Finish checking all candidates before we note any. This checking can2637// produce additional diagnostics so can't be interleaved with our2638// emission of notes.2639//2640// For an aligned allocation, separately check the aligned and unaligned2641// candidates with their respective argument lists.2642SmallVector<OverloadCandidate*, 32> Cands;2643SmallVector<OverloadCandidate*, 32> AlignedCands;2644llvm::SmallVector<Expr*, 4> AlignedArgs;2645if (AlignedCandidates) {2646auto IsAligned = [](OverloadCandidate &C) {2647return C.Function->getNumParams() > 1 &&2648C.Function->getParamDecl(1)->getType()->isAlignValT();2649};2650auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };26512652AlignedArgs.reserve(Args.size() + 1);2653AlignedArgs.push_back(Args[0]);2654AlignedArgs.push_back(AlignArg);2655AlignedArgs.append(Args.begin() + 1, Args.end());2656AlignedCands = AlignedCandidates->CompleteCandidates(2657S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);26582659Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,2660R.getNameLoc(), IsUnaligned);2661} else {2662Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,2663R.getNameLoc());2664}26652666S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)2667<< R.getLookupName() << Range;2668if (AlignedCandidates)2669AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",2670R.getNameLoc());2671Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());2672}2673return true;26742675case OR_Ambiguous:2676if (Diagnose) {2677Candidates.NoteCandidates(2678PartialDiagnosticAt(R.getNameLoc(),2679S.PDiag(diag::err_ovl_ambiguous_call)2680<< R.getLookupName() << Range),2681S, OCD_AmbiguousCandidates, Args);2682}2683return true;26842685case OR_Deleted: {2686if (Diagnose)2687S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),2688Candidates, Best->Function, Args);2689return true;2690}2691}2692llvm_unreachable("Unreachable, bad result from BestViableFunction");2693}26942695bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,2696AllocationFunctionScope NewScope,2697AllocationFunctionScope DeleteScope,2698QualType AllocType, bool IsArray,2699bool &PassAlignment, MultiExprArg PlaceArgs,2700FunctionDecl *&OperatorNew,2701FunctionDecl *&OperatorDelete,2702bool Diagnose) {2703// --- Choosing an allocation function ---2704// C++ 5.3.4p8 - 14 & 182705// 1) If looking in AFS_Global scope for allocation functions, only look in2706// the global scope. Else, if AFS_Class, only look in the scope of the2707// allocated class. If AFS_Both, look in both.2708// 2) If an array size is given, look for operator new[], else look for2709// operator new.2710// 3) The first argument is always size_t. Append the arguments from the2711// placement form.27122713SmallVector<Expr*, 8> AllocArgs;2714AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());27152716// We don't care about the actual value of these arguments.2717// FIXME: Should the Sema create the expression and embed it in the syntax2718// tree? Or should the consumer just recalculate the value?2719// FIXME: Using a dummy value will interact poorly with attribute enable_if.2720QualType SizeTy = Context.getSizeType();2721unsigned SizeTyWidth = Context.getTypeSize(SizeTy);2722IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,2723SourceLocation());2724AllocArgs.push_back(&Size);27252726QualType AlignValT = Context.VoidTy;2727if (PassAlignment) {2728DeclareGlobalNewDelete();2729AlignValT = Context.getTypeDeclType(getStdAlignValT());2730}2731CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());2732if (PassAlignment)2733AllocArgs.push_back(&Align);27342735AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());27362737// C++ [expr.new]p8:2738// If the allocated type is a non-array type, the allocation2739// function's name is operator new and the deallocation function's2740// name is operator delete. If the allocated type is an array2741// type, the allocation function's name is operator new[] and the2742// deallocation function's name is operator delete[].2743DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(2744IsArray ? OO_Array_New : OO_New);27452746QualType AllocElemType = Context.getBaseElementType(AllocType);27472748// Find the allocation function.2749{2750LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);27512752// C++1z [expr.new]p9:2753// If the new-expression begins with a unary :: operator, the allocation2754// function's name is looked up in the global scope. Otherwise, if the2755// allocated type is a class type T or array thereof, the allocation2756// function's name is looked up in the scope of T.2757if (AllocElemType->isRecordType() && NewScope != AFS_Global)2758LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());27592760// We can see ambiguity here if the allocation function is found in2761// multiple base classes.2762if (R.isAmbiguous())2763return true;27642765// If this lookup fails to find the name, or if the allocated type is not2766// a class type, the allocation function's name is looked up in the2767// global scope.2768if (R.empty()) {2769if (NewScope == AFS_Class)2770return true;27712772LookupQualifiedName(R, Context.getTranslationUnitDecl());2773}27742775if (getLangOpts().OpenCLCPlusPlus && R.empty()) {2776if (PlaceArgs.empty()) {2777Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";2778} else {2779Diag(StartLoc, diag::err_openclcxx_placement_new);2780}2781return true;2782}27832784assert(!R.empty() && "implicitly declared allocation functions not found");2785assert(!R.isAmbiguous() && "global allocation functions are ambiguous");27862787// We do our own custom access checks below.2788R.suppressDiagnostics();27892790if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,2791OperatorNew, /*Candidates=*/nullptr,2792/*AlignArg=*/nullptr, Diagnose))2793return true;2794}27952796// We don't need an operator delete if we're running under -fno-exceptions.2797if (!getLangOpts().Exceptions) {2798OperatorDelete = nullptr;2799return false;2800}28012802// Note, the name of OperatorNew might have been changed from array to2803// non-array by resolveAllocationOverload.2804DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(2805OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New2806? OO_Array_Delete2807: OO_Delete);28082809// C++ [expr.new]p19:2810//2811// If the new-expression begins with a unary :: operator, the2812// deallocation function's name is looked up in the global2813// scope. Otherwise, if the allocated type is a class type T or an2814// array thereof, the deallocation function's name is looked up in2815// the scope of T. If this lookup fails to find the name, or if2816// the allocated type is not a class type or array thereof, the2817// deallocation function's name is looked up in the global scope.2818LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);2819if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {2820auto *RD =2821cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());2822LookupQualifiedName(FoundDelete, RD);2823}2824if (FoundDelete.isAmbiguous())2825return true; // FIXME: clean up expressions?28262827// Filter out any destroying operator deletes. We can't possibly call such a2828// function in this context, because we're handling the case where the object2829// was not successfully constructed.2830// FIXME: This is not covered by the language rules yet.2831{2832LookupResult::Filter Filter = FoundDelete.makeFilter();2833while (Filter.hasNext()) {2834auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());2835if (FD && FD->isDestroyingOperatorDelete())2836Filter.erase();2837}2838Filter.done();2839}28402841bool FoundGlobalDelete = FoundDelete.empty();2842if (FoundDelete.empty()) {2843FoundDelete.clear(LookupOrdinaryName);28442845if (DeleteScope == AFS_Class)2846return true;28472848DeclareGlobalNewDelete();2849LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());2850}28512852FoundDelete.suppressDiagnostics();28532854SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;28552856// Whether we're looking for a placement operator delete is dictated2857// by whether we selected a placement operator new, not by whether2858// we had explicit placement arguments. This matters for things like2859// struct A { void *operator new(size_t, int = 0); ... };2860// A *a = new A()2861//2862// We don't have any definition for what a "placement allocation function"2863// is, but we assume it's any allocation function whose2864// parameter-declaration-clause is anything other than (size_t).2865//2866// FIXME: Should (size_t, std::align_val_t) also be considered non-placement?2867// This affects whether an exception from the constructor of an overaligned2868// type uses the sized or non-sized form of aligned operator delete.2869bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||2870OperatorNew->isVariadic();28712872if (isPlacementNew) {2873// C++ [expr.new]p20:2874// A declaration of a placement deallocation function matches the2875// declaration of a placement allocation function if it has the2876// same number of parameters and, after parameter transformations2877// (8.3.5), all parameter types except the first are2878// identical. [...]2879//2880// To perform this comparison, we compute the function type that2881// the deallocation function should have, and use that type both2882// for template argument deduction and for comparison purposes.2883QualType ExpectedFunctionType;2884{2885auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();28862887SmallVector<QualType, 4> ArgTypes;2888ArgTypes.push_back(Context.VoidPtrTy);2889for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)2890ArgTypes.push_back(Proto->getParamType(I));28912892FunctionProtoType::ExtProtoInfo EPI;2893// FIXME: This is not part of the standard's rule.2894EPI.Variadic = Proto->isVariadic();28952896ExpectedFunctionType2897= Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);2898}28992900for (LookupResult::iterator D = FoundDelete.begin(),2901DEnd = FoundDelete.end();2902D != DEnd; ++D) {2903FunctionDecl *Fn = nullptr;2904if (FunctionTemplateDecl *FnTmpl =2905dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {2906// Perform template argument deduction to try to match the2907// expected function type.2908TemplateDeductionInfo Info(StartLoc);2909if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,2910Info) != TemplateDeductionResult::Success)2911continue;2912} else2913Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());29142915if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),2916ExpectedFunctionType,2917/*AdjustExcpetionSpec*/true),2918ExpectedFunctionType))2919Matches.push_back(std::make_pair(D.getPair(), Fn));2920}29212922if (getLangOpts().CUDA)2923CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),2924Matches);2925} else {2926// C++1y [expr.new]p22:2927// For a non-placement allocation function, the normal deallocation2928// function lookup is used2929//2930// Per [expr.delete]p10, this lookup prefers a member operator delete2931// without a size_t argument, but prefers a non-member operator delete2932// with a size_t where possible (which it always is in this case).2933llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;2934UsualDeallocFnInfo Selected = resolveDeallocationOverload(2935*this, FoundDelete, /*WantSize*/ FoundGlobalDelete,2936/*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),2937&BestDeallocFns);2938if (Selected)2939Matches.push_back(std::make_pair(Selected.Found, Selected.FD));2940else {2941// If we failed to select an operator, all remaining functions are viable2942// but ambiguous.2943for (auto Fn : BestDeallocFns)2944Matches.push_back(std::make_pair(Fn.Found, Fn.FD));2945}2946}29472948// C++ [expr.new]p20:2949// [...] If the lookup finds a single matching deallocation2950// function, that function will be called; otherwise, no2951// deallocation function will be called.2952if (Matches.size() == 1) {2953OperatorDelete = Matches[0].second;29542955// C++1z [expr.new]p23:2956// If the lookup finds a usual deallocation function (3.7.4.2)2957// with a parameter of type std::size_t and that function, considered2958// as a placement deallocation function, would have been2959// selected as a match for the allocation function, the program2960// is ill-formed.2961if (getLangOpts().CPlusPlus11 && isPlacementNew &&2962isNonPlacementDeallocationFunction(*this, OperatorDelete)) {2963UsualDeallocFnInfo Info(*this,2964DeclAccessPair::make(OperatorDelete, AS_public));2965// Core issue, per mail to core reflector, 2016-10-09:2966// If this is a member operator delete, and there is a corresponding2967// non-sized member operator delete, this isn't /really/ a sized2968// deallocation function, it just happens to have a size_t parameter.2969bool IsSizedDelete = Info.HasSizeT;2970if (IsSizedDelete && !FoundGlobalDelete) {2971auto NonSizedDelete =2972resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,2973/*WantAlign*/Info.HasAlignValT);2974if (NonSizedDelete && !NonSizedDelete.HasSizeT &&2975NonSizedDelete.HasAlignValT == Info.HasAlignValT)2976IsSizedDelete = false;2977}29782979if (IsSizedDelete) {2980SourceRange R = PlaceArgs.empty()2981? SourceRange()2982: SourceRange(PlaceArgs.front()->getBeginLoc(),2983PlaceArgs.back()->getEndLoc());2984Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;2985if (!OperatorDelete->isImplicit())2986Diag(OperatorDelete->getLocation(), diag::note_previous_decl)2987<< DeleteName;2988}2989}29902991CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),2992Matches[0].first);2993} else if (!Matches.empty()) {2994// We found multiple suitable operators. Per [expr.new]p20, that means we2995// call no 'operator delete' function, but we should at least warn the user.2996// FIXME: Suppress this warning if the construction cannot throw.2997Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)2998<< DeleteName << AllocElemType;29993000for (auto &Match : Matches)3001Diag(Match.second->getLocation(),3002diag::note_member_declared_here) << DeleteName;3003}30043005return false;3006}30073008void Sema::DeclareGlobalNewDelete() {3009if (GlobalNewDeleteDeclared)3010return;30113012// The implicitly declared new and delete operators3013// are not supported in OpenCL.3014if (getLangOpts().OpenCLCPlusPlus)3015return;30163017// C++ [basic.stc.dynamic.general]p2:3018// The library provides default definitions for the global allocation3019// and deallocation functions. Some global allocation and deallocation3020// functions are replaceable ([new.delete]); these are attached to the3021// global module ([module.unit]).3022if (getLangOpts().CPlusPlusModules && getCurrentModule())3023PushGlobalModuleFragment(SourceLocation());30243025// C++ [basic.std.dynamic]p2:3026// [...] The following allocation and deallocation functions (18.4) are3027// implicitly declared in global scope in each translation unit of a3028// program3029//3030// C++03:3031// void* operator new(std::size_t) throw(std::bad_alloc);3032// void* operator new[](std::size_t) throw(std::bad_alloc);3033// void operator delete(void*) throw();3034// void operator delete[](void*) throw();3035// C++11:3036// void* operator new(std::size_t);3037// void* operator new[](std::size_t);3038// void operator delete(void*) noexcept;3039// void operator delete[](void*) noexcept;3040// C++1y:3041// void* operator new(std::size_t);3042// void* operator new[](std::size_t);3043// void operator delete(void*) noexcept;3044// void operator delete[](void*) noexcept;3045// void operator delete(void*, std::size_t) noexcept;3046// void operator delete[](void*, std::size_t) noexcept;3047//3048// These implicit declarations introduce only the function names operator3049// new, operator new[], operator delete, operator delete[].3050//3051// Here, we need to refer to std::bad_alloc, so we will implicitly declare3052// "std" or "bad_alloc" as necessary to form the exception specification.3053// However, we do not make these implicit declarations visible to name3054// lookup.3055if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {3056// The "std::bad_alloc" class has not yet been declared, so build it3057// implicitly.3058StdBadAlloc = CXXRecordDecl::Create(3059Context, TagTypeKind::Class, getOrCreateStdNamespace(),3060SourceLocation(), SourceLocation(),3061&PP.getIdentifierTable().get("bad_alloc"), nullptr);3062getStdBadAlloc()->setImplicit(true);30633064// The implicitly declared "std::bad_alloc" should live in global module3065// fragment.3066if (TheGlobalModuleFragment) {3067getStdBadAlloc()->setModuleOwnershipKind(3068Decl::ModuleOwnershipKind::ReachableWhenImported);3069getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);3070}3071}3072if (!StdAlignValT && getLangOpts().AlignedAllocation) {3073// The "std::align_val_t" enum class has not yet been declared, so build it3074// implicitly.3075auto *AlignValT = EnumDecl::Create(3076Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),3077&PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);30783079// The implicitly declared "std::align_val_t" should live in global module3080// fragment.3081if (TheGlobalModuleFragment) {3082AlignValT->setModuleOwnershipKind(3083Decl::ModuleOwnershipKind::ReachableWhenImported);3084AlignValT->setLocalOwningModule(TheGlobalModuleFragment);3085}30863087AlignValT->setIntegerType(Context.getSizeType());3088AlignValT->setPromotionType(Context.getSizeType());3089AlignValT->setImplicit(true);30903091StdAlignValT = AlignValT;3092}30933094GlobalNewDeleteDeclared = true;30953096QualType VoidPtr = Context.getPointerType(Context.VoidTy);3097QualType SizeT = Context.getSizeType();30983099auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,3100QualType Return, QualType Param) {3101llvm::SmallVector<QualType, 3> Params;3102Params.push_back(Param);31033104// Create up to four variants of the function (sized/aligned).3105bool HasSizedVariant = getLangOpts().SizedDeallocation &&3106(Kind == OO_Delete || Kind == OO_Array_Delete);3107bool HasAlignedVariant = getLangOpts().AlignedAllocation;31083109int NumSizeVariants = (HasSizedVariant ? 2 : 1);3110int NumAlignVariants = (HasAlignedVariant ? 2 : 1);3111for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {3112if (Sized)3113Params.push_back(SizeT);31143115for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {3116if (Aligned)3117Params.push_back(Context.getTypeDeclType(getStdAlignValT()));31183119DeclareGlobalAllocationFunction(3120Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);31213122if (Aligned)3123Params.pop_back();3124}3125}3126};31273128DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);3129DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);3130DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);3131DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);31323133if (getLangOpts().CPlusPlusModules && getCurrentModule())3134PopGlobalModuleFragment();3135}31363137/// DeclareGlobalAllocationFunction - Declares a single implicit global3138/// allocation function if it doesn't already exist.3139void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,3140QualType Return,3141ArrayRef<QualType> Params) {3142DeclContext *GlobalCtx = Context.getTranslationUnitDecl();31433144// Check if this function is already declared.3145DeclContext::lookup_result R = GlobalCtx->lookup(Name);3146for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();3147Alloc != AllocEnd; ++Alloc) {3148// Only look at non-template functions, as it is the predefined,3149// non-templated allocation function we are trying to declare here.3150if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {3151if (Func->getNumParams() == Params.size()) {3152llvm::SmallVector<QualType, 3> FuncParams;3153for (auto *P : Func->parameters())3154FuncParams.push_back(3155Context.getCanonicalType(P->getType().getUnqualifiedType()));3156if (llvm::ArrayRef(FuncParams) == Params) {3157// Make the function visible to name lookup, even if we found it in3158// an unimported module. It either is an implicitly-declared global3159// allocation function, or is suppressing that function.3160Func->setVisibleDespiteOwningModule();3161return;3162}3163}3164}3165}31663167FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(3168/*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));31693170QualType BadAllocType;3171bool HasBadAllocExceptionSpec3172= (Name.getCXXOverloadedOperator() == OO_New ||3173Name.getCXXOverloadedOperator() == OO_Array_New);3174if (HasBadAllocExceptionSpec) {3175if (!getLangOpts().CPlusPlus11) {3176BadAllocType = Context.getTypeDeclType(getStdBadAlloc());3177assert(StdBadAlloc && "Must have std::bad_alloc declared");3178EPI.ExceptionSpec.Type = EST_Dynamic;3179EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);3180}3181if (getLangOpts().NewInfallible) {3182EPI.ExceptionSpec.Type = EST_DynamicNone;3183}3184} else {3185EPI.ExceptionSpec =3186getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;3187}31883189auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {3190QualType FnType = Context.getFunctionType(Return, Params, EPI);3191FunctionDecl *Alloc = FunctionDecl::Create(3192Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,3193/*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,3194true);3195Alloc->setImplicit();3196// Global allocation functions should always be visible.3197Alloc->setVisibleDespiteOwningModule();31983199if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&3200!getLangOpts().CheckNew)3201Alloc->addAttr(3202ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));32033204// C++ [basic.stc.dynamic.general]p2:3205// The library provides default definitions for the global allocation3206// and deallocation functions. Some global allocation and deallocation3207// functions are replaceable ([new.delete]); these are attached to the3208// global module ([module.unit]).3209//3210// In the language wording, these functions are attched to the global3211// module all the time. But in the implementation, the global module3212// is only meaningful when we're in a module unit. So here we attach3213// these allocation functions to global module conditionally.3214if (TheGlobalModuleFragment) {3215Alloc->setModuleOwnershipKind(3216Decl::ModuleOwnershipKind::ReachableWhenImported);3217Alloc->setLocalOwningModule(TheGlobalModuleFragment);3218}32193220if (LangOpts.hasGlobalAllocationFunctionVisibility())3221Alloc->addAttr(VisibilityAttr::CreateImplicit(3222Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility()3223? VisibilityAttr::Hidden3224: LangOpts.hasProtectedGlobalAllocationFunctionVisibility()3225? VisibilityAttr::Protected3226: VisibilityAttr::Default));32273228llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;3229for (QualType T : Params) {3230ParamDecls.push_back(ParmVarDecl::Create(3231Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,3232/*TInfo=*/nullptr, SC_None, nullptr));3233ParamDecls.back()->setImplicit();3234}3235Alloc->setParams(ParamDecls);3236if (ExtraAttr)3237Alloc->addAttr(ExtraAttr);3238AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);3239Context.getTranslationUnitDecl()->addDecl(Alloc);3240IdResolver.tryAddTopLevelDecl(Alloc, Name);3241};32423243if (!LangOpts.CUDA)3244CreateAllocationFunctionDecl(nullptr);3245else {3246// Host and device get their own declaration so each can be3247// defined or re-declared independently.3248CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));3249CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));3250}3251}32523253FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,3254bool CanProvideSize,3255bool Overaligned,3256DeclarationName Name) {3257DeclareGlobalNewDelete();32583259LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);3260LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());32613262// FIXME: It's possible for this to result in ambiguity, through a3263// user-declared variadic operator delete or the enable_if attribute. We3264// should probably not consider those cases to be usual deallocation3265// functions. But for now we just make an arbitrary choice in that case.3266auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,3267Overaligned);3268assert(Result.FD && "operator delete missing from global scope?");3269return Result.FD;3270}32713272FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,3273CXXRecordDecl *RD) {3274DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);32753276FunctionDecl *OperatorDelete = nullptr;3277if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))3278return nullptr;3279if (OperatorDelete)3280return OperatorDelete;32813282// If there's no class-specific operator delete, look up the global3283// non-array delete.3284return FindUsualDeallocationFunction(3285Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),3286Name);3287}32883289bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,3290DeclarationName Name,3291FunctionDecl *&Operator, bool Diagnose,3292bool WantSize, bool WantAligned) {3293LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);3294// Try to find operator delete/operator delete[] in class scope.3295LookupQualifiedName(Found, RD);32963297if (Found.isAmbiguous())3298return true;32993300Found.suppressDiagnostics();33013302bool Overaligned =3303WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));33043305// C++17 [expr.delete]p10:3306// If the deallocation functions have class scope, the one without a3307// parameter of type std::size_t is selected.3308llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;3309resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,3310/*WantAlign*/ Overaligned, &Matches);33113312// If we could find an overload, use it.3313if (Matches.size() == 1) {3314Operator = cast<CXXMethodDecl>(Matches[0].FD);33153316// FIXME: DiagnoseUseOfDecl?3317if (Operator->isDeleted()) {3318if (Diagnose) {3319StringLiteral *Msg = Operator->getDeletedMessage();3320Diag(StartLoc, diag::err_deleted_function_use)3321<< (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());3322NoteDeletedFunction(Operator);3323}3324return true;3325}33263327if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),3328Matches[0].Found, Diagnose) == AR_inaccessible)3329return true;33303331return false;3332}33333334// We found multiple suitable operators; complain about the ambiguity.3335// FIXME: The standard doesn't say to do this; it appears that the intent3336// is that this should never happen.3337if (!Matches.empty()) {3338if (Diagnose) {3339Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)3340<< Name << RD;3341for (auto &Match : Matches)3342Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;3343}3344return true;3345}33463347// We did find operator delete/operator delete[] declarations, but3348// none of them were suitable.3349if (!Found.empty()) {3350if (Diagnose) {3351Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)3352<< Name << RD;33533354for (NamedDecl *D : Found)3355Diag(D->getUnderlyingDecl()->getLocation(),3356diag::note_member_declared_here) << Name;3357}3358return true;3359}33603361Operator = nullptr;3362return false;3363}33643365namespace {3366/// Checks whether delete-expression, and new-expression used for3367/// initializing deletee have the same array form.3368class MismatchingNewDeleteDetector {3369public:3370enum MismatchResult {3371/// Indicates that there is no mismatch or a mismatch cannot be proven.3372NoMismatch,3373/// Indicates that variable is initialized with mismatching form of \a new.3374VarInitMismatches,3375/// Indicates that member is initialized with mismatching form of \a new.3376MemberInitMismatches,3377/// Indicates that 1 or more constructors' definitions could not been3378/// analyzed, and they will be checked again at the end of translation unit.3379AnalyzeLater3380};33813382/// \param EndOfTU True, if this is the final analysis at the end of3383/// translation unit. False, if this is the initial analysis at the point3384/// delete-expression was encountered.3385explicit MismatchingNewDeleteDetector(bool EndOfTU)3386: Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),3387HasUndefinedConstructors(false) {}33883389/// Checks whether pointee of a delete-expression is initialized with3390/// matching form of new-expression.3391///3392/// If return value is \c VarInitMismatches or \c MemberInitMismatches at the3393/// point where delete-expression is encountered, then a warning will be3394/// issued immediately. If return value is \c AnalyzeLater at the point where3395/// delete-expression is seen, then member will be analyzed at the end of3396/// translation unit. \c AnalyzeLater is returned iff at least one constructor3397/// couldn't be analyzed. If at least one constructor initializes the member3398/// with matching type of new, the return value is \c NoMismatch.3399MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);3400/// Analyzes a class member.3401/// \param Field Class member to analyze.3402/// \param DeleteWasArrayForm Array form-ness of the delete-expression used3403/// for deleting the \p Field.3404MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);3405FieldDecl *Field;3406/// List of mismatching new-expressions used for initialization of the pointee3407llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;3408/// Indicates whether delete-expression was in array form.3409bool IsArrayForm;34103411private:3412const bool EndOfTU;3413/// Indicates that there is at least one constructor without body.3414bool HasUndefinedConstructors;3415/// Returns \c CXXNewExpr from given initialization expression.3416/// \param E Expression used for initializing pointee in delete-expression.3417/// E can be a single-element \c InitListExpr consisting of new-expression.3418const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);3419/// Returns whether member is initialized with mismatching form of3420/// \c new either by the member initializer or in-class initialization.3421///3422/// If bodies of all constructors are not visible at the end of translation3423/// unit or at least one constructor initializes member with the matching3424/// form of \c new, mismatch cannot be proven, and this function will return3425/// \c NoMismatch.3426MismatchResult analyzeMemberExpr(const MemberExpr *ME);3427/// Returns whether variable is initialized with mismatching form of3428/// \c new.3429///3430/// If variable is initialized with matching form of \c new or variable is not3431/// initialized with a \c new expression, this function will return true.3432/// If variable is initialized with mismatching form of \c new, returns false.3433/// \param D Variable to analyze.3434bool hasMatchingVarInit(const DeclRefExpr *D);3435/// Checks whether the constructor initializes pointee with mismatching3436/// form of \c new.3437///3438/// Returns true, if member is initialized with matching form of \c new in3439/// member initializer list. Returns false, if member is initialized with the3440/// matching form of \c new in this constructor's initializer or given3441/// constructor isn't defined at the point where delete-expression is seen, or3442/// member isn't initialized by the constructor.3443bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);3444/// Checks whether member is initialized with matching form of3445/// \c new in member initializer list.3446bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);3447/// Checks whether member is initialized with mismatching form of \c new by3448/// in-class initializer.3449MismatchResult analyzeInClassInitializer();3450};3451}34523453MismatchingNewDeleteDetector::MismatchResult3454MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {3455NewExprs.clear();3456assert(DE && "Expected delete-expression");3457IsArrayForm = DE->isArrayForm();3458const Expr *E = DE->getArgument()->IgnoreParenImpCasts();3459if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {3460return analyzeMemberExpr(ME);3461} else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {3462if (!hasMatchingVarInit(D))3463return VarInitMismatches;3464}3465return NoMismatch;3466}34673468const CXXNewExpr *3469MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {3470assert(E != nullptr && "Expected a valid initializer expression");3471E = E->IgnoreParenImpCasts();3472if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {3473if (ILE->getNumInits() == 1)3474E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());3475}34763477return dyn_cast_or_null<const CXXNewExpr>(E);3478}34793480bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(3481const CXXCtorInitializer *CI) {3482const CXXNewExpr *NE = nullptr;3483if (Field == CI->getMember() &&3484(NE = getNewExprFromInitListOrExpr(CI->getInit()))) {3485if (NE->isArray() == IsArrayForm)3486return true;3487else3488NewExprs.push_back(NE);3489}3490return false;3491}34923493bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(3494const CXXConstructorDecl *CD) {3495if (CD->isImplicit())3496return false;3497const FunctionDecl *Definition = CD;3498if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {3499HasUndefinedConstructors = true;3500return EndOfTU;3501}3502for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {3503if (hasMatchingNewInCtorInit(CI))3504return true;3505}3506return false;3507}35083509MismatchingNewDeleteDetector::MismatchResult3510MismatchingNewDeleteDetector::analyzeInClassInitializer() {3511assert(Field != nullptr && "This should be called only for members");3512const Expr *InitExpr = Field->getInClassInitializer();3513if (!InitExpr)3514return EndOfTU ? NoMismatch : AnalyzeLater;3515if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {3516if (NE->isArray() != IsArrayForm) {3517NewExprs.push_back(NE);3518return MemberInitMismatches;3519}3520}3521return NoMismatch;3522}35233524MismatchingNewDeleteDetector::MismatchResult3525MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,3526bool DeleteWasArrayForm) {3527assert(Field != nullptr && "Analysis requires a valid class member.");3528this->Field = Field;3529IsArrayForm = DeleteWasArrayForm;3530const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());3531for (const auto *CD : RD->ctors()) {3532if (hasMatchingNewInCtor(CD))3533return NoMismatch;3534}3535if (HasUndefinedConstructors)3536return EndOfTU ? NoMismatch : AnalyzeLater;3537if (!NewExprs.empty())3538return MemberInitMismatches;3539return Field->hasInClassInitializer() ? analyzeInClassInitializer()3540: NoMismatch;3541}35423543MismatchingNewDeleteDetector::MismatchResult3544MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {3545assert(ME != nullptr && "Expected a member expression");3546if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))3547return analyzeField(F, IsArrayForm);3548return NoMismatch;3549}35503551bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {3552const CXXNewExpr *NE = nullptr;3553if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {3554if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&3555NE->isArray() != IsArrayForm) {3556NewExprs.push_back(NE);3557}3558}3559return NewExprs.empty();3560}35613562static void3563DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,3564const MismatchingNewDeleteDetector &Detector) {3565SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);3566FixItHint H;3567if (!Detector.IsArrayForm)3568H = FixItHint::CreateInsertion(EndOfDelete, "[]");3569else {3570SourceLocation RSquare = Lexer::findLocationAfterToken(3571DeleteLoc, tok::l_square, SemaRef.getSourceManager(),3572SemaRef.getLangOpts(), true);3573if (RSquare.isValid())3574H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));3575}3576SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)3577<< Detector.IsArrayForm << H;35783579for (const auto *NE : Detector.NewExprs)3580SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)3581<< Detector.IsArrayForm;3582}35833584void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {3585if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))3586return;3587MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);3588switch (Detector.analyzeDeleteExpr(DE)) {3589case MismatchingNewDeleteDetector::VarInitMismatches:3590case MismatchingNewDeleteDetector::MemberInitMismatches: {3591DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);3592break;3593}3594case MismatchingNewDeleteDetector::AnalyzeLater: {3595DeleteExprs[Detector.Field].push_back(3596std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));3597break;3598}3599case MismatchingNewDeleteDetector::NoMismatch:3600break;3601}3602}36033604void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,3605bool DeleteWasArrayForm) {3606MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);3607switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {3608case MismatchingNewDeleteDetector::VarInitMismatches:3609llvm_unreachable("This analysis should have been done for class members.");3610case MismatchingNewDeleteDetector::AnalyzeLater:3611llvm_unreachable("Analysis cannot be postponed any point beyond end of "3612"translation unit.");3613case MismatchingNewDeleteDetector::MemberInitMismatches:3614DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);3615break;3616case MismatchingNewDeleteDetector::NoMismatch:3617break;3618}3619}36203621ExprResult3622Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,3623bool ArrayForm, Expr *ExE) {3624// C++ [expr.delete]p1:3625// The operand shall have a pointer type, or a class type having a single3626// non-explicit conversion function to a pointer type. The result has type3627// void.3628//3629// DR599 amends "pointer type" to "pointer to object type" in both cases.36303631ExprResult Ex = ExE;3632FunctionDecl *OperatorDelete = nullptr;3633bool ArrayFormAsWritten = ArrayForm;3634bool UsualArrayDeleteWantsSize = false;36353636if (!Ex.get()->isTypeDependent()) {3637// Perform lvalue-to-rvalue cast, if needed.3638Ex = DefaultLvalueConversion(Ex.get());3639if (Ex.isInvalid())3640return ExprError();36413642QualType Type = Ex.get()->getType();36433644class DeleteConverter : public ContextualImplicitConverter {3645public:3646DeleteConverter() : ContextualImplicitConverter(false, true) {}36473648bool match(QualType ConvType) override {3649// FIXME: If we have an operator T* and an operator void*, we must pick3650// the operator T*.3651if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())3652if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())3653return true;3654return false;3655}36563657SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,3658QualType T) override {3659return S.Diag(Loc, diag::err_delete_operand) << T;3660}36613662SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,3663QualType T) override {3664return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;3665}36663667SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,3668QualType T,3669QualType ConvTy) override {3670return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;3671}36723673SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,3674QualType ConvTy) override {3675return S.Diag(Conv->getLocation(), diag::note_delete_conversion)3676<< ConvTy;3677}36783679SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,3680QualType T) override {3681return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;3682}36833684SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,3685QualType ConvTy) override {3686return S.Diag(Conv->getLocation(), diag::note_delete_conversion)3687<< ConvTy;3688}36893690SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,3691QualType T,3692QualType ConvTy) override {3693llvm_unreachable("conversion functions are permitted");3694}3695} Converter;36963697Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);3698if (Ex.isInvalid())3699return ExprError();3700Type = Ex.get()->getType();3701if (!Converter.match(Type))3702// FIXME: PerformContextualImplicitConversion should return ExprError3703// itself in this case.3704return ExprError();37053706QualType Pointee = Type->castAs<PointerType>()->getPointeeType();3707QualType PointeeElem = Context.getBaseElementType(Pointee);37083709if (Pointee.getAddressSpace() != LangAS::Default &&3710!getLangOpts().OpenCLCPlusPlus)3711return Diag(Ex.get()->getBeginLoc(),3712diag::err_address_space_qualified_delete)3713<< Pointee.getUnqualifiedType()3714<< Pointee.getQualifiers().getAddressSpaceAttributePrintValue();37153716CXXRecordDecl *PointeeRD = nullptr;3717if (Pointee->isVoidType() && !isSFINAEContext()) {3718// The C++ standard bans deleting a pointer to a non-object type, which3719// effectively bans deletion of "void*". However, most compilers support3720// this, so we treat it as a warning unless we're in a SFINAE context.3721// But we still prohibit this since C++26.3722Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete3723: diag::ext_delete_void_ptr_operand)3724<< (LangOpts.CPlusPlus26 ? Pointee : Type)3725<< Ex.get()->getSourceRange();3726} else if (Pointee->isFunctionType() || Pointee->isVoidType() ||3727Pointee->isSizelessType()) {3728return ExprError(Diag(StartLoc, diag::err_delete_operand)3729<< Type << Ex.get()->getSourceRange());3730} else if (!Pointee->isDependentType()) {3731// FIXME: This can result in errors if the definition was imported from a3732// module but is hidden.3733if (!RequireCompleteType(StartLoc, Pointee,3734LangOpts.CPlusPlus263735? diag::err_delete_incomplete3736: diag::warn_delete_incomplete,3737Ex.get())) {3738if (const RecordType *RT = PointeeElem->getAs<RecordType>())3739PointeeRD = cast<CXXRecordDecl>(RT->getDecl());3740}3741}37423743if (Pointee->isArrayType() && !ArrayForm) {3744Diag(StartLoc, diag::warn_delete_array_type)3745<< Type << Ex.get()->getSourceRange()3746<< FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");3747ArrayForm = true;3748}37493750DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(3751ArrayForm ? OO_Array_Delete : OO_Delete);37523753if (PointeeRD) {3754if (!UseGlobal &&3755FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,3756OperatorDelete))3757return ExprError();37583759// If we're allocating an array of records, check whether the3760// usual operator delete[] has a size_t parameter.3761if (ArrayForm) {3762// If the user specifically asked to use the global allocator,3763// we'll need to do the lookup into the class.3764if (UseGlobal)3765UsualArrayDeleteWantsSize =3766doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);37673768// Otherwise, the usual operator delete[] should be the3769// function we just found.3770else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete))3771UsualArrayDeleteWantsSize =3772UsualDeallocFnInfo(*this,3773DeclAccessPair::make(OperatorDelete, AS_public))3774.HasSizeT;3775}37763777if (!PointeeRD->hasIrrelevantDestructor())3778if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {3779MarkFunctionReferenced(StartLoc,3780const_cast<CXXDestructorDecl*>(Dtor));3781if (DiagnoseUseOfDecl(Dtor, StartLoc))3782return ExprError();3783}37843785CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,3786/*IsDelete=*/true, /*CallCanBeVirtual=*/true,3787/*WarnOnNonAbstractTypes=*/!ArrayForm,3788SourceLocation());3789}37903791if (!OperatorDelete) {3792if (getLangOpts().OpenCLCPlusPlus) {3793Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";3794return ExprError();3795}37963797bool IsComplete = isCompleteType(StartLoc, Pointee);3798bool CanProvideSize =3799IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||3800Pointee.isDestructedType());3801bool Overaligned = hasNewExtendedAlignment(*this, Pointee);38023803// Look for a global declaration.3804OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,3805Overaligned, DeleteName);3806}38073808MarkFunctionReferenced(StartLoc, OperatorDelete);38093810// Check access and ambiguity of destructor if we're going to call it.3811// Note that this is required even for a virtual delete.3812bool IsVirtualDelete = false;3813if (PointeeRD) {3814if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {3815CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,3816PDiag(diag::err_access_dtor) << PointeeElem);3817IsVirtualDelete = Dtor->isVirtual();3818}3819}38203821DiagnoseUseOfDecl(OperatorDelete, StartLoc);38223823// Convert the operand to the type of the first parameter of operator3824// delete. This is only necessary if we selected a destroying operator3825// delete that we are going to call (non-virtually); converting to void*3826// is trivial and left to AST consumers to handle.3827QualType ParamType = OperatorDelete->getParamDecl(0)->getType();3828if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {3829Qualifiers Qs = Pointee.getQualifiers();3830if (Qs.hasCVRQualifiers()) {3831// Qualifiers are irrelevant to this conversion; we're only looking3832// for access and ambiguity.3833Qs.removeCVRQualifiers();3834QualType Unqual = Context.getPointerType(3835Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));3836Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);3837}3838Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);3839if (Ex.isInvalid())3840return ExprError();3841}3842}38433844CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(3845Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,3846UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);3847AnalyzeDeleteExprMismatch(Result);3848return Result;3849}38503851static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,3852bool IsDelete,3853FunctionDecl *&Operator) {38543855DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(3856IsDelete ? OO_Delete : OO_New);38573858LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);3859S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());3860assert(!R.empty() && "implicitly declared allocation functions not found");3861assert(!R.isAmbiguous() && "global allocation functions are ambiguous");38623863// We do our own custom access checks below.3864R.suppressDiagnostics();38653866SmallVector<Expr *, 8> Args(TheCall->arguments());3867OverloadCandidateSet Candidates(R.getNameLoc(),3868OverloadCandidateSet::CSK_Normal);3869for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();3870FnOvl != FnOvlEnd; ++FnOvl) {3871// Even member operator new/delete are implicitly treated as3872// static, so don't use AddMemberCandidate.3873NamedDecl *D = (*FnOvl)->getUnderlyingDecl();38743875if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {3876S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),3877/*ExplicitTemplateArgs=*/nullptr, Args,3878Candidates,3879/*SuppressUserConversions=*/false);3880continue;3881}38823883FunctionDecl *Fn = cast<FunctionDecl>(D);3884S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,3885/*SuppressUserConversions=*/false);3886}38873888SourceRange Range = TheCall->getSourceRange();38893890// Do the resolution.3891OverloadCandidateSet::iterator Best;3892switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {3893case OR_Success: {3894// Got one!3895FunctionDecl *FnDecl = Best->Function;3896assert(R.getNamingClass() == nullptr &&3897"class members should not be considered");38983899if (!FnDecl->isReplaceableGlobalAllocationFunction()) {3900S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)3901<< (IsDelete ? 1 : 0) << Range;3902S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)3903<< R.getLookupName() << FnDecl->getSourceRange();3904return true;3905}39063907Operator = FnDecl;3908return false;3909}39103911case OR_No_Viable_Function:3912Candidates.NoteCandidates(3913PartialDiagnosticAt(R.getNameLoc(),3914S.PDiag(diag::err_ovl_no_viable_function_in_call)3915<< R.getLookupName() << Range),3916S, OCD_AllCandidates, Args);3917return true;39183919case OR_Ambiguous:3920Candidates.NoteCandidates(3921PartialDiagnosticAt(R.getNameLoc(),3922S.PDiag(diag::err_ovl_ambiguous_call)3923<< R.getLookupName() << Range),3924S, OCD_AmbiguousCandidates, Args);3925return true;39263927case OR_Deleted:3928S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),3929Candidates, Best->Function, Args);3930return true;3931}3932llvm_unreachable("Unreachable, bad result from BestViableFunction");3933}39343935ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,3936bool IsDelete) {3937CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());3938if (!getLangOpts().CPlusPlus) {3939Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)3940<< (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")3941<< "C++";3942return ExprError();3943}3944// CodeGen assumes it can find the global new and delete to call,3945// so ensure that they are declared.3946DeclareGlobalNewDelete();39473948FunctionDecl *OperatorNewOrDelete = nullptr;3949if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,3950OperatorNewOrDelete))3951return ExprError();3952assert(OperatorNewOrDelete && "should be found");39533954DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());3955MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);39563957TheCall->setType(OperatorNewOrDelete->getReturnType());3958for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {3959QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();3960InitializedEntity Entity =3961InitializedEntity::InitializeParameter(Context, ParamTy, false);3962ExprResult Arg = PerformCopyInitialization(3963Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));3964if (Arg.isInvalid())3965return ExprError();3966TheCall->setArg(i, Arg.get());3967}3968auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());3969assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&3970"Callee expected to be implicit cast to a builtin function pointer");3971Callee->setType(OperatorNewOrDelete->getType());39723973return TheCallResult;3974}39753976void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,3977bool IsDelete, bool CallCanBeVirtual,3978bool WarnOnNonAbstractTypes,3979SourceLocation DtorLoc) {3980if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())3981return;39823983// C++ [expr.delete]p3:3984// In the first alternative (delete object), if the static type of the3985// object to be deleted is different from its dynamic type, the static3986// type shall be a base class of the dynamic type of the object to be3987// deleted and the static type shall have a virtual destructor or the3988// behavior is undefined.3989//3990const CXXRecordDecl *PointeeRD = dtor->getParent();3991// Note: a final class cannot be derived from, no issue there3992if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())3993return;39943995// If the superclass is in a system header, there's nothing that can be done.3996// The `delete` (where we emit the warning) can be in a system header,3997// what matters for this warning is where the deleted type is defined.3998if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))3999return;40004001QualType ClassType = dtor->getFunctionObjectParameterType();4002if (PointeeRD->isAbstract()) {4003// If the class is abstract, we warn by default, because we're4004// sure the code has undefined behavior.4005Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)4006<< ClassType;4007} else if (WarnOnNonAbstractTypes) {4008// Otherwise, if this is not an array delete, it's a bit suspect,4009// but not necessarily wrong.4010Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)4011<< ClassType;4012}4013if (!IsDelete) {4014std::string TypeStr;4015ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());4016Diag(DtorLoc, diag::note_delete_non_virtual)4017<< FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");4018}4019}40204021Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,4022SourceLocation StmtLoc,4023ConditionKind CK) {4024ExprResult E =4025CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);4026if (E.isInvalid())4027return ConditionError();4028return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),4029CK == ConditionKind::ConstexprIf);4030}40314032ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,4033SourceLocation StmtLoc,4034ConditionKind CK) {4035if (ConditionVar->isInvalidDecl())4036return ExprError();40374038QualType T = ConditionVar->getType();40394040// C++ [stmt.select]p2:4041// The declarator shall not specify a function or an array.4042if (T->isFunctionType())4043return ExprError(Diag(ConditionVar->getLocation(),4044diag::err_invalid_use_of_function_type)4045<< ConditionVar->getSourceRange());4046else if (T->isArrayType())4047return ExprError(Diag(ConditionVar->getLocation(),4048diag::err_invalid_use_of_array_type)4049<< ConditionVar->getSourceRange());40504051ExprResult Condition = BuildDeclRefExpr(4052ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,4053ConditionVar->getLocation());40544055switch (CK) {4056case ConditionKind::Boolean:4057return CheckBooleanCondition(StmtLoc, Condition.get());40584059case ConditionKind::ConstexprIf:4060return CheckBooleanCondition(StmtLoc, Condition.get(), true);40614062case ConditionKind::Switch:4063return CheckSwitchCondition(StmtLoc, Condition.get());4064}40654066llvm_unreachable("unexpected condition kind");4067}40684069ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {4070// C++11 6.4p4:4071// The value of a condition that is an initialized declaration in a statement4072// other than a switch statement is the value of the declared variable4073// implicitly converted to type bool. If that conversion is ill-formed, the4074// program is ill-formed.4075// The value of a condition that is an expression is the value of the4076// expression, implicitly converted to bool.4077//4078// C++23 8.5.2p24079// If the if statement is of the form if constexpr, the value of the condition4080// is contextually converted to bool and the converted expression shall be4081// a constant expression.4082//40834084ExprResult E = PerformContextuallyConvertToBool(CondExpr);4085if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())4086return E;40874088// FIXME: Return this value to the caller so they don't need to recompute it.4089llvm::APSInt Cond;4090E = VerifyIntegerConstantExpression(4091E.get(), &Cond,4092diag::err_constexpr_if_condition_expression_is_not_constant);4093return E;4094}40954096bool4097Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {4098// Look inside the implicit cast, if it exists.4099if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))4100From = Cast->getSubExpr();41014102// A string literal (2.13.4) that is not a wide string literal can4103// be converted to an rvalue of type "pointer to char"; a wide4104// string literal can be converted to an rvalue of type "pointer4105// to wchar_t" (C++ 4.2p2).4106if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))4107if (const PointerType *ToPtrType = ToType->getAs<PointerType>())4108if (const BuiltinType *ToPointeeType4109= ToPtrType->getPointeeType()->getAs<BuiltinType>()) {4110// This conversion is considered only when there is an4111// explicit appropriate pointer target type (C++ 4.2p2).4112if (!ToPtrType->getPointeeType().hasQualifiers()) {4113switch (StrLit->getKind()) {4114case StringLiteralKind::UTF8:4115case StringLiteralKind::UTF16:4116case StringLiteralKind::UTF32:4117// We don't allow UTF literals to be implicitly converted4118break;4119case StringLiteralKind::Ordinary:4120return (ToPointeeType->getKind() == BuiltinType::Char_U ||4121ToPointeeType->getKind() == BuiltinType::Char_S);4122case StringLiteralKind::Wide:4123return Context.typesAreCompatible(Context.getWideCharType(),4124QualType(ToPointeeType, 0));4125case StringLiteralKind::Unevaluated:4126assert(false && "Unevaluated string literal in expression");4127break;4128}4129}4130}41314132return false;4133}41344135static ExprResult BuildCXXCastArgument(Sema &S,4136SourceLocation CastLoc,4137QualType Ty,4138CastKind Kind,4139CXXMethodDecl *Method,4140DeclAccessPair FoundDecl,4141bool HadMultipleCandidates,4142Expr *From) {4143switch (Kind) {4144default: llvm_unreachable("Unhandled cast kind!");4145case CK_ConstructorConversion: {4146CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);4147SmallVector<Expr*, 8> ConstructorArgs;41484149if (S.RequireNonAbstractType(CastLoc, Ty,4150diag::err_allocation_of_abstract_type))4151return ExprError();41524153if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,4154ConstructorArgs))4155return ExprError();41564157S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,4158InitializedEntity::InitializeTemporary(Ty));4159if (S.DiagnoseUseOfDecl(Method, CastLoc))4160return ExprError();41614162ExprResult Result = S.BuildCXXConstructExpr(4163CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),4164ConstructorArgs, HadMultipleCandidates,4165/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,4166CXXConstructionKind::Complete, SourceRange());4167if (Result.isInvalid())4168return ExprError();41694170return S.MaybeBindToTemporary(Result.getAs<Expr>());4171}41724173case CK_UserDefinedConversion: {4174assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");41754176S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);4177if (S.DiagnoseUseOfDecl(Method, CastLoc))4178return ExprError();41794180// Create an implicit call expr that calls it.4181CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);4182ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,4183HadMultipleCandidates);4184if (Result.isInvalid())4185return ExprError();4186// Record usage of conversion in an implicit cast.4187Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),4188CK_UserDefinedConversion, Result.get(),4189nullptr, Result.get()->getValueKind(),4190S.CurFPFeatureOverrides());41914192return S.MaybeBindToTemporary(Result.get());4193}4194}4195}41964197ExprResult4198Sema::PerformImplicitConversion(Expr *From, QualType ToType,4199const ImplicitConversionSequence &ICS,4200AssignmentAction Action,4201CheckedConversionKind CCK) {4202// C++ [over.match.oper]p7: [...] operands of class type are converted [...]4203if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp &&4204!From->getType()->isRecordType())4205return From;42064207switch (ICS.getKind()) {4208case ImplicitConversionSequence::StandardConversion: {4209ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,4210Action, CCK);4211if (Res.isInvalid())4212return ExprError();4213From = Res.get();4214break;4215}42164217case ImplicitConversionSequence::UserDefinedConversion: {42184219FunctionDecl *FD = ICS.UserDefined.ConversionFunction;4220CastKind CastKind;4221QualType BeforeToType;4222assert(FD && "no conversion function for user-defined conversion seq");4223if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {4224CastKind = CK_UserDefinedConversion;42254226// If the user-defined conversion is specified by a conversion function,4227// the initial standard conversion sequence converts the source type to4228// the implicit object parameter of the conversion function.4229BeforeToType = Context.getTagDeclType(Conv->getParent());4230} else {4231const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);4232CastKind = CK_ConstructorConversion;4233// Do no conversion if dealing with ... for the first conversion.4234if (!ICS.UserDefined.EllipsisConversion) {4235// If the user-defined conversion is specified by a constructor, the4236// initial standard conversion sequence converts the source type to4237// the type required by the argument of the constructor4238BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();4239}4240}4241// Watch out for ellipsis conversion.4242if (!ICS.UserDefined.EllipsisConversion) {4243ExprResult Res =4244PerformImplicitConversion(From, BeforeToType,4245ICS.UserDefined.Before, AA_Converting,4246CCK);4247if (Res.isInvalid())4248return ExprError();4249From = Res.get();4250}42514252ExprResult CastArg = BuildCXXCastArgument(4253*this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,4254cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,4255ICS.UserDefined.HadMultipleCandidates, From);42564257if (CastArg.isInvalid())4258return ExprError();42594260From = CastArg.get();42614262// C++ [over.match.oper]p7:4263// [...] the second standard conversion sequence of a user-defined4264// conversion sequence is not applied.4265if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp)4266return From;42674268return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,4269AA_Converting, CCK);4270}42714272case ImplicitConversionSequence::AmbiguousConversion:4273ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),4274PDiag(diag::err_typecheck_ambiguous_condition)4275<< From->getSourceRange());4276return ExprError();42774278case ImplicitConversionSequence::EllipsisConversion:4279case ImplicitConversionSequence::StaticObjectArgumentConversion:4280llvm_unreachable("bad conversion");42814282case ImplicitConversionSequence::BadConversion:4283Sema::AssignConvertType ConvTy =4284CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());4285bool Diagnosed = DiagnoseAssignmentResult(4286ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),4287ToType, From->getType(), From, Action);4288assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;4289return ExprError();4290}42914292// Everything went well.4293return From;4294}42954296// adjustVectorType - Compute the intermediate cast type casting elements of the4297// from type to the elements of the to type without resizing the vector.4298static QualType adjustVectorType(ASTContext &Context, QualType FromTy,4299QualType ToType, QualType *ElTy = nullptr) {4300auto *ToVec = ToType->castAs<VectorType>();4301QualType ElType = ToVec->getElementType();4302if (ElTy)4303*ElTy = ElType;4304if (!FromTy->isVectorType())4305return ElType;4306auto *FromVec = FromTy->castAs<VectorType>();4307return Context.getExtVectorType(ElType, FromVec->getNumElements());4308}43094310ExprResult4311Sema::PerformImplicitConversion(Expr *From, QualType ToType,4312const StandardConversionSequence& SCS,4313AssignmentAction Action,4314CheckedConversionKind CCK) {4315bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||4316CCK == CheckedConversionKind::FunctionalCast);43174318// Overall FIXME: we are recomputing too many types here and doing far too4319// much extra work. What this means is that we need to keep track of more4320// information that is computed when we try the implicit conversion initially,4321// so that we don't need to recompute anything here.4322QualType FromType = From->getType();43234324if (SCS.CopyConstructor) {4325// FIXME: When can ToType be a reference type?4326assert(!ToType->isReferenceType());4327if (SCS.Second == ICK_Derived_To_Base) {4328SmallVector<Expr*, 8> ConstructorArgs;4329if (CompleteConstructorCall(4330cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,4331/*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))4332return ExprError();4333return BuildCXXConstructExpr(4334/*FIXME:ConstructLoc*/ SourceLocation(), ToType,4335SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,4336/*HadMultipleCandidates*/ false,4337/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,4338CXXConstructionKind::Complete, SourceRange());4339}4340return BuildCXXConstructExpr(4341/*FIXME:ConstructLoc*/ SourceLocation(), ToType,4342SCS.FoundCopyConstructor, SCS.CopyConstructor, From,4343/*HadMultipleCandidates*/ false,4344/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,4345CXXConstructionKind::Complete, SourceRange());4346}43474348// Resolve overloaded function references.4349if (Context.hasSameType(FromType, Context.OverloadTy)) {4350DeclAccessPair Found;4351FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,4352true, Found);4353if (!Fn)4354return ExprError();43554356if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))4357return ExprError();43584359ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn);4360if (Res.isInvalid())4361return ExprError();43624363// We might get back another placeholder expression if we resolved to a4364// builtin.4365Res = CheckPlaceholderExpr(Res.get());4366if (Res.isInvalid())4367return ExprError();43684369From = Res.get();4370FromType = From->getType();4371}43724373// If we're converting to an atomic type, first convert to the corresponding4374// non-atomic type.4375QualType ToAtomicType;4376if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {4377ToAtomicType = ToType;4378ToType = ToAtomic->getValueType();4379}43804381QualType InitialFromType = FromType;4382// Perform the first implicit conversion.4383switch (SCS.First) {4384case ICK_Identity:4385if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {4386FromType = FromAtomic->getValueType().getUnqualifiedType();4387From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,4388From, /*BasePath=*/nullptr, VK_PRValue,4389FPOptionsOverride());4390}4391break;43924393case ICK_Lvalue_To_Rvalue: {4394assert(From->getObjectKind() != OK_ObjCProperty);4395ExprResult FromRes = DefaultLvalueConversion(From);4396if (FromRes.isInvalid())4397return ExprError();43984399From = FromRes.get();4400FromType = From->getType();4401break;4402}44034404case ICK_Array_To_Pointer:4405FromType = Context.getArrayDecayedType(FromType);4406From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,4407/*BasePath=*/nullptr, CCK)4408.get();4409break;44104411case ICK_HLSL_Array_RValue:4412FromType = Context.getArrayParameterType(FromType);4413From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,4414/*BasePath=*/nullptr, CCK)4415.get();4416break;44174418case ICK_Function_To_Pointer:4419FromType = Context.getPointerType(FromType);4420From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,4421VK_PRValue, /*BasePath=*/nullptr, CCK)4422.get();4423break;44244425default:4426llvm_unreachable("Improper first standard conversion");4427}44284429// Perform the second implicit conversion4430switch (SCS.Second) {4431case ICK_Identity:4432// C++ [except.spec]p5:4433// [For] assignment to and initialization of pointers to functions,4434// pointers to member functions, and references to functions: the4435// target entity shall allow at least the exceptions allowed by the4436// source value in the assignment or initialization.4437switch (Action) {4438case AA_Assigning:4439case AA_Initializing:4440// Note, function argument passing and returning are initialization.4441case AA_Passing:4442case AA_Returning:4443case AA_Sending:4444case AA_Passing_CFAudited:4445if (CheckExceptionSpecCompatibility(From, ToType))4446return ExprError();4447break;44484449case AA_Casting:4450case AA_Converting:4451// Casts and implicit conversions are not initialization, so are not4452// checked for exception specification mismatches.4453break;4454}4455// Nothing else to do.4456break;44574458case ICK_Integral_Promotion:4459case ICK_Integral_Conversion: {4460QualType ElTy = ToType;4461QualType StepTy = ToType;4462if (ToType->isVectorType())4463StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);4464if (ElTy->isBooleanType()) {4465assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&4466SCS.Second == ICK_Integral_Promotion &&4467"only enums with fixed underlying type can promote to bool");4468From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,4469/*BasePath=*/nullptr, CCK)4470.get();4471} else {4472From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,4473/*BasePath=*/nullptr, CCK)4474.get();4475}4476break;4477}44784479case ICK_Floating_Promotion:4480case ICK_Floating_Conversion: {4481QualType StepTy = ToType;4482if (ToType->isVectorType())4483StepTy = adjustVectorType(Context, FromType, ToType);4484From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,4485/*BasePath=*/nullptr, CCK)4486.get();4487break;4488}44894490case ICK_Complex_Promotion:4491case ICK_Complex_Conversion: {4492QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();4493QualType ToEl = ToType->castAs<ComplexType>()->getElementType();4494CastKind CK;4495if (FromEl->isRealFloatingType()) {4496if (ToEl->isRealFloatingType())4497CK = CK_FloatingComplexCast;4498else4499CK = CK_FloatingComplexToIntegralComplex;4500} else if (ToEl->isRealFloatingType()) {4501CK = CK_IntegralComplexToFloatingComplex;4502} else {4503CK = CK_IntegralComplexCast;4504}4505From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,4506CCK)4507.get();4508break;4509}45104511case ICK_Floating_Integral: {4512QualType ElTy = ToType;4513QualType StepTy = ToType;4514if (ToType->isVectorType())4515StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);4516if (ElTy->isRealFloatingType())4517From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,4518/*BasePath=*/nullptr, CCK)4519.get();4520else4521From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,4522/*BasePath=*/nullptr, CCK)4523.get();4524break;4525}45264527case ICK_Fixed_Point_Conversion:4528assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&4529"Attempting implicit fixed point conversion without a fixed "4530"point operand");4531if (FromType->isFloatingType())4532From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,4533VK_PRValue,4534/*BasePath=*/nullptr, CCK).get();4535else if (ToType->isFloatingType())4536From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,4537VK_PRValue,4538/*BasePath=*/nullptr, CCK).get();4539else if (FromType->isIntegralType(Context))4540From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,4541VK_PRValue,4542/*BasePath=*/nullptr, CCK).get();4543else if (ToType->isIntegralType(Context))4544From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,4545VK_PRValue,4546/*BasePath=*/nullptr, CCK).get();4547else if (ToType->isBooleanType())4548From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,4549VK_PRValue,4550/*BasePath=*/nullptr, CCK).get();4551else4552From = ImpCastExprToType(From, ToType, CK_FixedPointCast,4553VK_PRValue,4554/*BasePath=*/nullptr, CCK).get();4555break;45564557case ICK_Compatible_Conversion:4558From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),4559/*BasePath=*/nullptr, CCK).get();4560break;45614562case ICK_Writeback_Conversion:4563case ICK_Pointer_Conversion: {4564if (SCS.IncompatibleObjC && Action != AA_Casting) {4565// Diagnose incompatible Objective-C conversions4566if (Action == AA_Initializing || Action == AA_Assigning)4567Diag(From->getBeginLoc(),4568diag::ext_typecheck_convert_incompatible_pointer)4569<< ToType << From->getType() << Action << From->getSourceRange()4570<< 0;4571else4572Diag(From->getBeginLoc(),4573diag::ext_typecheck_convert_incompatible_pointer)4574<< From->getType() << ToType << Action << From->getSourceRange()4575<< 0;45764577if (From->getType()->isObjCObjectPointerType() &&4578ToType->isObjCObjectPointerType())4579ObjC().EmitRelatedResultTypeNote(From);4580} else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&4581!ObjC().CheckObjCARCUnavailableWeakConversion(ToType,4582From->getType())) {4583if (Action == AA_Initializing)4584Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);4585else4586Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)4587<< (Action == AA_Casting) << From->getType() << ToType4588<< From->getSourceRange();4589}45904591// Defer address space conversion to the third conversion.4592QualType FromPteeType = From->getType()->getPointeeType();4593QualType ToPteeType = ToType->getPointeeType();4594QualType NewToType = ToType;4595if (!FromPteeType.isNull() && !ToPteeType.isNull() &&4596FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {4597NewToType = Context.removeAddrSpaceQualType(ToPteeType);4598NewToType = Context.getAddrSpaceQualType(NewToType,4599FromPteeType.getAddressSpace());4600if (ToType->isObjCObjectPointerType())4601NewToType = Context.getObjCObjectPointerType(NewToType);4602else if (ToType->isBlockPointerType())4603NewToType = Context.getBlockPointerType(NewToType);4604else4605NewToType = Context.getPointerType(NewToType);4606}46074608CastKind Kind;4609CXXCastPath BasePath;4610if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))4611return ExprError();46124613// Make sure we extend blocks if necessary.4614// FIXME: doing this here is really ugly.4615if (Kind == CK_BlockPointerToObjCPointerCast) {4616ExprResult E = From;4617(void)ObjC().PrepareCastToObjCObjectPointer(E);4618From = E.get();4619}4620if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())4621ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);4622From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)4623.get();4624break;4625}46264627case ICK_Pointer_Member: {4628CastKind Kind;4629CXXCastPath BasePath;4630if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))4631return ExprError();4632if (CheckExceptionSpecCompatibility(From, ToType))4633return ExprError();46344635// We may not have been able to figure out what this member pointer resolved4636// to up until this exact point. Attempt to lock-in it's inheritance model.4637if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {4638(void)isCompleteType(From->getExprLoc(), From->getType());4639(void)isCompleteType(From->getExprLoc(), ToType);4640}46414642From =4643ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();4644break;4645}46464647case ICK_Boolean_Conversion: {4648// Perform half-to-boolean conversion via float.4649if (From->getType()->isHalfType()) {4650From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();4651FromType = Context.FloatTy;4652}4653QualType ElTy = FromType;4654QualType StepTy = ToType;4655if (FromType->isVectorType()) {4656if (getLangOpts().HLSL)4657StepTy = adjustVectorType(Context, FromType, ToType);4658ElTy = FromType->castAs<VectorType>()->getElementType();4659}46604661From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),4662VK_PRValue,4663/*BasePath=*/nullptr, CCK)4664.get();4665break;4666}46674668case ICK_Derived_To_Base: {4669CXXCastPath BasePath;4670if (CheckDerivedToBaseConversion(4671From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),4672From->getSourceRange(), &BasePath, CStyle))4673return ExprError();46744675From = ImpCastExprToType(From, ToType.getNonReferenceType(),4676CK_DerivedToBase, From->getValueKind(),4677&BasePath, CCK).get();4678break;4679}46804681case ICK_Vector_Conversion:4682From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,4683/*BasePath=*/nullptr, CCK)4684.get();4685break;46864687case ICK_SVE_Vector_Conversion:4688case ICK_RVV_Vector_Conversion:4689From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,4690/*BasePath=*/nullptr, CCK)4691.get();4692break;46934694case ICK_Vector_Splat: {4695// Vector splat from any arithmetic type to a vector.4696Expr *Elem = prepareVectorSplat(ToType, From).get();4697From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,4698/*BasePath=*/nullptr, CCK)4699.get();4700break;4701}47024703case ICK_Complex_Real:4704// Case 1. x -> _Complex y4705if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {4706QualType ElType = ToComplex->getElementType();4707bool isFloatingComplex = ElType->isRealFloatingType();47084709// x -> y4710if (Context.hasSameUnqualifiedType(ElType, From->getType())) {4711// do nothing4712} else if (From->getType()->isRealFloatingType()) {4713From = ImpCastExprToType(From, ElType,4714isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();4715} else {4716assert(From->getType()->isIntegerType());4717From = ImpCastExprToType(From, ElType,4718isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();4719}4720// y -> _Complex y4721From = ImpCastExprToType(From, ToType,4722isFloatingComplex ? CK_FloatingRealToComplex4723: CK_IntegralRealToComplex).get();47244725// Case 2. _Complex x -> y4726} else {4727auto *FromComplex = From->getType()->castAs<ComplexType>();4728QualType ElType = FromComplex->getElementType();4729bool isFloatingComplex = ElType->isRealFloatingType();47304731// _Complex x -> x4732From = ImpCastExprToType(From, ElType,4733isFloatingComplex ? CK_FloatingComplexToReal4734: CK_IntegralComplexToReal,4735VK_PRValue, /*BasePath=*/nullptr, CCK)4736.get();47374738// x -> y4739if (Context.hasSameUnqualifiedType(ElType, ToType)) {4740// do nothing4741} else if (ToType->isRealFloatingType()) {4742From = ImpCastExprToType(From, ToType,4743isFloatingComplex ? CK_FloatingCast4744: CK_IntegralToFloating,4745VK_PRValue, /*BasePath=*/nullptr, CCK)4746.get();4747} else {4748assert(ToType->isIntegerType());4749From = ImpCastExprToType(From, ToType,4750isFloatingComplex ? CK_FloatingToIntegral4751: CK_IntegralCast,4752VK_PRValue, /*BasePath=*/nullptr, CCK)4753.get();4754}4755}4756break;47574758case ICK_Block_Pointer_Conversion: {4759LangAS AddrSpaceL =4760ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();4761LangAS AddrSpaceR =4762FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();4763assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&4764"Invalid cast");4765CastKind Kind =4766AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;4767From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,4768VK_PRValue, /*BasePath=*/nullptr, CCK)4769.get();4770break;4771}47724773case ICK_TransparentUnionConversion: {4774ExprResult FromRes = From;4775Sema::AssignConvertType ConvTy =4776CheckTransparentUnionArgumentConstraints(ToType, FromRes);4777if (FromRes.isInvalid())4778return ExprError();4779From = FromRes.get();4780assert ((ConvTy == Sema::Compatible) &&4781"Improper transparent union conversion");4782(void)ConvTy;4783break;4784}47854786case ICK_Zero_Event_Conversion:4787case ICK_Zero_Queue_Conversion:4788From = ImpCastExprToType(From, ToType,4789CK_ZeroToOCLOpaqueType,4790From->getValueKind()).get();4791break;47924793case ICK_Lvalue_To_Rvalue:4794case ICK_Array_To_Pointer:4795case ICK_Function_To_Pointer:4796case ICK_Function_Conversion:4797case ICK_Qualification:4798case ICK_Num_Conversion_Kinds:4799case ICK_C_Only_Conversion:4800case ICK_Incompatible_Pointer_Conversion:4801case ICK_HLSL_Array_RValue:4802case ICK_HLSL_Vector_Truncation:4803case ICK_HLSL_Vector_Splat:4804llvm_unreachable("Improper second standard conversion");4805}48064807if (SCS.Dimension != ICK_Identity) {4808// If SCS.Element is not ICK_Identity the To and From types must be HLSL4809// vectors or matrices.48104811// TODO: Support HLSL matrices.4812assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&4813"Dimension conversion for matrix types is not implemented yet.");4814assert(ToType->isVectorType() &&4815"Dimension conversion is only supported for vector types.");4816switch (SCS.Dimension) {4817case ICK_HLSL_Vector_Splat: {4818// Vector splat from any arithmetic type to a vector.4819Expr *Elem = prepareVectorSplat(ToType, From).get();4820From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,4821/*BasePath=*/nullptr, CCK)4822.get();4823break;4824}4825case ICK_HLSL_Vector_Truncation: {4826// Note: HLSL built-in vectors are ExtVectors. Since this truncates a4827// vector to a smaller vector, this can only operate on arguments where4828// the source and destination types are ExtVectors.4829assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() &&4830"HLSL vector truncation should only apply to ExtVectors");4831auto *FromVec = From->getType()->castAs<VectorType>();4832auto *ToVec = ToType->castAs<VectorType>();4833QualType ElType = FromVec->getElementType();4834QualType TruncTy =4835Context.getExtVectorType(ElType, ToVec->getNumElements());4836From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,4837From->getValueKind())4838.get();4839break;4840}4841case ICK_Identity:4842default:4843llvm_unreachable("Improper element standard conversion");4844}4845}48464847switch (SCS.Third) {4848case ICK_Identity:4849// Nothing to do.4850break;48514852case ICK_Function_Conversion:4853// If both sides are functions (or pointers/references to them), there could4854// be incompatible exception declarations.4855if (CheckExceptionSpecCompatibility(From, ToType))4856return ExprError();48574858From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,4859/*BasePath=*/nullptr, CCK)4860.get();4861break;48624863case ICK_Qualification: {4864ExprValueKind VK = From->getValueKind();4865CastKind CK = CK_NoOp;48664867if (ToType->isReferenceType() &&4868ToType->getPointeeType().getAddressSpace() !=4869From->getType().getAddressSpace())4870CK = CK_AddressSpaceConversion;48714872if (ToType->isPointerType() &&4873ToType->getPointeeType().getAddressSpace() !=4874From->getType()->getPointeeType().getAddressSpace())4875CK = CK_AddressSpaceConversion;48764877if (!isCast(CCK) &&4878!ToType->getPointeeType().getQualifiers().hasUnaligned() &&4879From->getType()->getPointeeType().getQualifiers().hasUnaligned()) {4880Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)4881<< InitialFromType << ToType;4882}48834884From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,4885/*BasePath=*/nullptr, CCK)4886.get();48874888if (SCS.DeprecatedStringLiteralToCharPtr &&4889!getLangOpts().WritableStrings) {4890Diag(From->getBeginLoc(),4891getLangOpts().CPlusPlus114892? diag::ext_deprecated_string_literal_conversion4893: diag::warn_deprecated_string_literal_conversion)4894<< ToType.getNonReferenceType();4895}48964897break;4898}48994900default:4901llvm_unreachable("Improper third standard conversion");4902}49034904// If this conversion sequence involved a scalar -> atomic conversion, perform4905// that conversion now.4906if (!ToAtomicType.isNull()) {4907assert(Context.hasSameType(4908ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));4909From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,4910VK_PRValue, nullptr, CCK)4911.get();4912}49134914// Materialize a temporary if we're implicitly converting to a reference4915// type. This is not required by the C++ rules but is necessary to maintain4916// AST invariants.4917if (ToType->isReferenceType() && From->isPRValue()) {4918ExprResult Res = TemporaryMaterializationConversion(From);4919if (Res.isInvalid())4920return ExprError();4921From = Res.get();4922}49234924// If this conversion sequence succeeded and involved implicitly converting a4925// _Nullable type to a _Nonnull one, complain.4926if (!isCast(CCK))4927diagnoseNullableToNonnullConversion(ToType, InitialFromType,4928From->getBeginLoc());49294930return From;4931}49324933/// Checks that type T is not a VLA.4934///4935/// @returns @c true if @p T is VLA and a diagnostic was emitted,4936/// @c false otherwise.4937static bool DiagnoseVLAInCXXTypeTrait(Sema &S, const TypeSourceInfo *T,4938clang::tok::TokenKind TypeTraitID) {4939if (!T->getType()->isVariableArrayType())4940return false;49414942S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported)4943<< 1 << TypeTraitID;4944return true;4945}49464947/// Check the completeness of a type in a unary type trait.4948///4949/// If the particular type trait requires a complete type, tries to complete4950/// it. If completing the type fails, a diagnostic is emitted and false4951/// returned. If completing the type succeeds or no completion was required,4952/// returns true.4953static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,4954SourceLocation Loc,4955QualType ArgTy) {4956// C++0x [meta.unary.prop]p3:4957// For all of the class templates X declared in this Clause, instantiating4958// that template with a template argument that is a class template4959// specialization may result in the implicit instantiation of the template4960// argument if and only if the semantics of X require that the argument4961// must be a complete type.4962// We apply this rule to all the type trait expressions used to implement4963// these class templates. We also try to follow any GCC documented behavior4964// in these expressions to ensure portability of standard libraries.4965switch (UTT) {4966default: llvm_unreachable("not a UTT");4967// is_complete_type somewhat obviously cannot require a complete type.4968case UTT_IsCompleteType:4969// Fall-through49704971// These traits are modeled on the type predicates in C++0x4972// [meta.unary.cat] and [meta.unary.comp]. They are not specified as4973// requiring a complete type, as whether or not they return true cannot be4974// impacted by the completeness of the type.4975case UTT_IsVoid:4976case UTT_IsIntegral:4977case UTT_IsFloatingPoint:4978case UTT_IsArray:4979case UTT_IsBoundedArray:4980case UTT_IsPointer:4981case UTT_IsNullPointer:4982case UTT_IsReferenceable:4983case UTT_IsLvalueReference:4984case UTT_IsRvalueReference:4985case UTT_IsMemberFunctionPointer:4986case UTT_IsMemberObjectPointer:4987case UTT_IsEnum:4988case UTT_IsScopedEnum:4989case UTT_IsUnion:4990case UTT_IsClass:4991case UTT_IsFunction:4992case UTT_IsReference:4993case UTT_IsArithmetic:4994case UTT_IsFundamental:4995case UTT_IsObject:4996case UTT_IsScalar:4997case UTT_IsCompound:4998case UTT_IsMemberPointer:4999// Fall-through50005001// These traits are modeled on type predicates in C++0x [meta.unary.prop]5002// which requires some of its traits to have the complete type. However,5003// the completeness of the type cannot impact these traits' semantics, and5004// so they don't require it. This matches the comments on these traits in5005// Table 49.5006case UTT_IsConst:5007case UTT_IsVolatile:5008case UTT_IsSigned:5009case UTT_IsUnboundedArray:5010case UTT_IsUnsigned:50115012// This type trait always returns false, checking the type is moot.5013case UTT_IsInterfaceClass:5014return true;50155016// C++14 [meta.unary.prop]:5017// If T is a non-union class type, T shall be a complete type.5018case UTT_IsEmpty:5019case UTT_IsPolymorphic:5020case UTT_IsAbstract:5021if (const auto *RD = ArgTy->getAsCXXRecordDecl())5022if (!RD->isUnion())5023return !S.RequireCompleteType(5024Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);5025return true;50265027// C++14 [meta.unary.prop]:5028// If T is a class type, T shall be a complete type.5029case UTT_IsFinal:5030case UTT_IsSealed:5031if (ArgTy->getAsCXXRecordDecl())5032return !S.RequireCompleteType(5033Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);5034return true;50355036// LWG3823: T shall be an array type, a complete type, or cv void.5037case UTT_IsAggregate:5038if (ArgTy->isArrayType() || ArgTy->isVoidType())5039return true;50405041return !S.RequireCompleteType(5042Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);50435044// C++1z [meta.unary.prop]:5045// remove_all_extents_t<T> shall be a complete type or cv void.5046case UTT_IsTrivial:5047case UTT_IsTriviallyCopyable:5048case UTT_IsStandardLayout:5049case UTT_IsPOD:5050case UTT_IsLiteral:5051case UTT_IsBitwiseCloneable:5052// By analogy, is_trivially_relocatable and is_trivially_equality_comparable5053// impose the same constraints.5054case UTT_IsTriviallyRelocatable:5055case UTT_IsTriviallyEqualityComparable:5056case UTT_CanPassInRegs:5057// Per the GCC type traits documentation, T shall be a complete type, cv void,5058// or an array of unknown bound. But GCC actually imposes the same constraints5059// as above.5060case UTT_HasNothrowAssign:5061case UTT_HasNothrowMoveAssign:5062case UTT_HasNothrowConstructor:5063case UTT_HasNothrowCopy:5064case UTT_HasTrivialAssign:5065case UTT_HasTrivialMoveAssign:5066case UTT_HasTrivialDefaultConstructor:5067case UTT_HasTrivialMoveConstructor:5068case UTT_HasTrivialCopy:5069case UTT_HasTrivialDestructor:5070case UTT_HasVirtualDestructor:5071// has_unique_object_representations<T> when T is an array is defined in terms5072// of has_unique_object_representations<remove_all_extents_t<T>>, so the base5073// type needs to be complete even if the type is an incomplete array type.5074case UTT_HasUniqueObjectRepresentations:5075ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);5076[[fallthrough]];50775078// C++1z [meta.unary.prop]:5079// T shall be a complete type, cv void, or an array of unknown bound.5080case UTT_IsDestructible:5081case UTT_IsNothrowDestructible:5082case UTT_IsTriviallyDestructible:5083if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())5084return true;50855086return !S.RequireCompleteType(5087Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);5088}5089}50905091static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,5092Sema &Self, SourceLocation KeyLoc, ASTContext &C,5093bool (CXXRecordDecl::*HasTrivial)() const,5094bool (CXXRecordDecl::*HasNonTrivial)() const,5095bool (CXXMethodDecl::*IsDesiredOp)() const)5096{5097CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());5098if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())5099return true;51005101DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);5102DeclarationNameInfo NameInfo(Name, KeyLoc);5103LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);5104if (Self.LookupQualifiedName(Res, RD)) {5105bool FoundOperator = false;5106Res.suppressDiagnostics();5107for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();5108Op != OpEnd; ++Op) {5109if (isa<FunctionTemplateDecl>(*Op))5110continue;51115112CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);5113if((Operator->*IsDesiredOp)()) {5114FoundOperator = true;5115auto *CPT = Operator->getType()->castAs<FunctionProtoType>();5116CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);5117if (!CPT || !CPT->isNothrow())5118return false;5119}5120}5121return FoundOperator;5122}5123return false;5124}51255126static bool HasNonDeletedDefaultedEqualityComparison(Sema &S,5127const CXXRecordDecl *Decl,5128SourceLocation KeyLoc) {5129if (Decl->isUnion())5130return false;5131if (Decl->isLambda())5132return Decl->isCapturelessLambda();51335134{5135EnterExpressionEvaluationContext UnevaluatedContext(5136S, Sema::ExpressionEvaluationContext::Unevaluated);5137Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);5138Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());51395140// const ClassT& obj;5141OpaqueValueExpr Operand(5142KeyLoc,5143Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(),5144ExprValueKind::VK_LValue);5145UnresolvedSet<16> Functions;5146// obj == obj;5147S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions);51485149auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ,5150Functions, &Operand, &Operand);5151if (Result.isInvalid() || SFINAE.hasErrorOccurred())5152return false;51535154const auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(Result.get());5155if (!CallExpr)5156return false;5157const auto *Callee = CallExpr->getDirectCallee();5158auto ParamT = Callee->getParamDecl(0)->getType();5159if (!Callee->isDefaulted())5160return false;5161if (!ParamT->isReferenceType() && !Decl->isTriviallyCopyable())5162return false;5163if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() !=5164Decl->getTypeForDecl())5165return false;5166}51675168return llvm::all_of(Decl->bases(),5169[&](const CXXBaseSpecifier &BS) {5170if (const auto *RD = BS.getType()->getAsCXXRecordDecl())5171return HasNonDeletedDefaultedEqualityComparison(5172S, RD, KeyLoc);5173return true;5174}) &&5175llvm::all_of(Decl->fields(), [&](const FieldDecl *FD) {5176auto Type = FD->getType();5177if (Type->isArrayType())5178Type = Type->getBaseElementTypeUnsafe()5179->getCanonicalTypeUnqualified();51805181if (Type->isReferenceType() || Type->isEnumeralType())5182return false;5183if (const auto *RD = Type->getAsCXXRecordDecl())5184return HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc);5185return true;5186});5187}51885189static bool isTriviallyEqualityComparableType(Sema &S, QualType Type, SourceLocation KeyLoc) {5190QualType CanonicalType = Type.getCanonicalType();5191if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||5192CanonicalType->isEnumeralType() || CanonicalType->isArrayType())5193return false;51945195if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {5196if (!HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc))5197return false;5198}51995200return S.getASTContext().hasUniqueObjectRepresentations(5201CanonicalType, /*CheckIfTriviallyCopyable=*/false);5202}52035204static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,5205SourceLocation KeyLoc,5206TypeSourceInfo *TInfo) {5207QualType T = TInfo->getType();5208assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");52095210ASTContext &C = Self.Context;5211switch(UTT) {5212default: llvm_unreachable("not a UTT");5213// Type trait expressions corresponding to the primary type category5214// predicates in C++0x [meta.unary.cat].5215case UTT_IsVoid:5216return T->isVoidType();5217case UTT_IsIntegral:5218return T->isIntegralType(C);5219case UTT_IsFloatingPoint:5220return T->isFloatingType();5221case UTT_IsArray:5222// Zero-sized arrays aren't considered arrays in partial specializations,5223// so __is_array shouldn't consider them arrays either.5224if (const auto *CAT = C.getAsConstantArrayType(T))5225return CAT->getSize() != 0;5226return T->isArrayType();5227case UTT_IsBoundedArray:5228if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array))5229return false;5230// Zero-sized arrays aren't considered arrays in partial specializations,5231// so __is_bounded_array shouldn't consider them arrays either.5232if (const auto *CAT = C.getAsConstantArrayType(T))5233return CAT->getSize() != 0;5234return T->isArrayType() && !T->isIncompleteArrayType();5235case UTT_IsUnboundedArray:5236if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array))5237return false;5238return T->isIncompleteArrayType();5239case UTT_IsPointer:5240return T->isAnyPointerType();5241case UTT_IsNullPointer:5242return T->isNullPtrType();5243case UTT_IsLvalueReference:5244return T->isLValueReferenceType();5245case UTT_IsRvalueReference:5246return T->isRValueReferenceType();5247case UTT_IsMemberFunctionPointer:5248return T->isMemberFunctionPointerType();5249case UTT_IsMemberObjectPointer:5250return T->isMemberDataPointerType();5251case UTT_IsEnum:5252return T->isEnumeralType();5253case UTT_IsScopedEnum:5254return T->isScopedEnumeralType();5255case UTT_IsUnion:5256return T->isUnionType();5257case UTT_IsClass:5258return T->isClassType() || T->isStructureType() || T->isInterfaceType();5259case UTT_IsFunction:5260return T->isFunctionType();52615262// Type trait expressions which correspond to the convenient composition5263// predicates in C++0x [meta.unary.comp].5264case UTT_IsReference:5265return T->isReferenceType();5266case UTT_IsArithmetic:5267return T->isArithmeticType() && !T->isEnumeralType();5268case UTT_IsFundamental:5269return T->isFundamentalType();5270case UTT_IsObject:5271return T->isObjectType();5272case UTT_IsScalar:5273// Note: semantic analysis depends on Objective-C lifetime types to be5274// considered scalar types. However, such types do not actually behave5275// like scalar types at run time (since they may require retain/release5276// operations), so we report them as non-scalar.5277if (T->isObjCLifetimeType()) {5278switch (T.getObjCLifetime()) {5279case Qualifiers::OCL_None:5280case Qualifiers::OCL_ExplicitNone:5281return true;52825283case Qualifiers::OCL_Strong:5284case Qualifiers::OCL_Weak:5285case Qualifiers::OCL_Autoreleasing:5286return false;5287}5288}52895290return T->isScalarType();5291case UTT_IsCompound:5292return T->isCompoundType();5293case UTT_IsMemberPointer:5294return T->isMemberPointerType();52955296// Type trait expressions which correspond to the type property predicates5297// in C++0x [meta.unary.prop].5298case UTT_IsConst:5299return T.isConstQualified();5300case UTT_IsVolatile:5301return T.isVolatileQualified();5302case UTT_IsTrivial:5303return T.isTrivialType(C);5304case UTT_IsTriviallyCopyable:5305return T.isTriviallyCopyableType(C);5306case UTT_IsStandardLayout:5307return T->isStandardLayoutType();5308case UTT_IsPOD:5309return T.isPODType(C);5310case UTT_IsLiteral:5311return T->isLiteralType(C);5312case UTT_IsEmpty:5313if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())5314return !RD->isUnion() && RD->isEmpty();5315return false;5316case UTT_IsPolymorphic:5317if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())5318return !RD->isUnion() && RD->isPolymorphic();5319return false;5320case UTT_IsAbstract:5321if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())5322return !RD->isUnion() && RD->isAbstract();5323return false;5324case UTT_IsAggregate:5325// Report vector extensions and complex types as aggregates because they5326// support aggregate initialization. GCC mirrors this behavior for vectors5327// but not _Complex.5328return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||5329T->isAnyComplexType();5330// __is_interface_class only returns true when CL is invoked in /CLR mode and5331// even then only when it is used with the 'interface struct ...' syntax5332// Clang doesn't support /CLR which makes this type trait moot.5333case UTT_IsInterfaceClass:5334return false;5335case UTT_IsFinal:5336case UTT_IsSealed:5337if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())5338return RD->hasAttr<FinalAttr>();5339return false;5340case UTT_IsSigned:5341// Enum types should always return false.5342// Floating points should always return true.5343return T->isFloatingType() ||5344(T->isSignedIntegerType() && !T->isEnumeralType());5345case UTT_IsUnsigned:5346// Enum types should always return false.5347return T->isUnsignedIntegerType() && !T->isEnumeralType();53485349// Type trait expressions which query classes regarding their construction,5350// destruction, and copying. Rather than being based directly on the5351// related type predicates in the standard, they are specified by both5352// GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those5353// specifications.5354//5355// 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html5356// 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index5357//5358// Note that these builtins do not behave as documented in g++: if a class5359// has both a trivial and a non-trivial special member of a particular kind,5360// they return false! For now, we emulate this behavior.5361// FIXME: This appears to be a g++ bug: more complex cases reveal that it5362// does not correctly compute triviality in the presence of multiple special5363// members of the same kind. Revisit this once the g++ bug is fixed.5364case UTT_HasTrivialDefaultConstructor:5365// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:5366// If __is_pod (type) is true then the trait is true, else if type is5367// a cv class or union type (or array thereof) with a trivial default5368// constructor ([class.ctor]) then the trait is true, else it is false.5369if (T.isPODType(C))5370return true;5371if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())5372return RD->hasTrivialDefaultConstructor() &&5373!RD->hasNonTrivialDefaultConstructor();5374return false;5375case UTT_HasTrivialMoveConstructor:5376// This trait is implemented by MSVC 2012 and needed to parse the5377// standard library headers. Specifically this is used as the logic5378// behind std::is_trivially_move_constructible (20.9.4.3).5379if (T.isPODType(C))5380return true;5381if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())5382return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();5383return false;5384case UTT_HasTrivialCopy:5385// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:5386// If __is_pod (type) is true or type is a reference type then5387// the trait is true, else if type is a cv class or union type5388// with a trivial copy constructor ([class.copy]) then the trait5389// is true, else it is false.5390if (T.isPODType(C) || T->isReferenceType())5391return true;5392if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())5393return RD->hasTrivialCopyConstructor() &&5394!RD->hasNonTrivialCopyConstructor();5395return false;5396case UTT_HasTrivialMoveAssign:5397// This trait is implemented by MSVC 2012 and needed to parse the5398// standard library headers. Specifically it is used as the logic5399// behind std::is_trivially_move_assignable (20.9.4.3)5400if (T.isPODType(C))5401return true;5402if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())5403return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();5404return false;5405case UTT_HasTrivialAssign:5406// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:5407// If type is const qualified or is a reference type then the5408// trait is false. Otherwise if __is_pod (type) is true then the5409// trait is true, else if type is a cv class or union type with5410// a trivial copy assignment ([class.copy]) then the trait is5411// true, else it is false.5412// Note: the const and reference restrictions are interesting,5413// given that const and reference members don't prevent a class5414// from having a trivial copy assignment operator (but do cause5415// errors if the copy assignment operator is actually used, q.v.5416// [class.copy]p12).54175418if (T.isConstQualified())5419return false;5420if (T.isPODType(C))5421return true;5422if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())5423return RD->hasTrivialCopyAssignment() &&5424!RD->hasNonTrivialCopyAssignment();5425return false;5426case UTT_IsDestructible:5427case UTT_IsTriviallyDestructible:5428case UTT_IsNothrowDestructible:5429// C++14 [meta.unary.prop]:5430// For reference types, is_destructible<T>::value is true.5431if (T->isReferenceType())5432return true;54335434// Objective-C++ ARC: autorelease types don't require destruction.5435if (T->isObjCLifetimeType() &&5436T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)5437return true;54385439// C++14 [meta.unary.prop]:5440// For incomplete types and function types, is_destructible<T>::value is5441// false.5442if (T->isIncompleteType() || T->isFunctionType())5443return false;54445445// A type that requires destruction (via a non-trivial destructor or ARC5446// lifetime semantics) is not trivially-destructible.5447if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())5448return false;54495450// C++14 [meta.unary.prop]:5451// For object types and given U equal to remove_all_extents_t<T>, if the5452// expression std::declval<U&>().~U() is well-formed when treated as an5453// unevaluated operand (Clause 5), then is_destructible<T>::value is true5454if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {5455CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);5456if (!Destructor)5457return false;5458// C++14 [dcl.fct.def.delete]p2:5459// A program that refers to a deleted function implicitly or5460// explicitly, other than to declare it, is ill-formed.5461if (Destructor->isDeleted())5462return false;5463if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)5464return false;5465if (UTT == UTT_IsNothrowDestructible) {5466auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();5467CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);5468if (!CPT || !CPT->isNothrow())5469return false;5470}5471}5472return true;54735474case UTT_HasTrivialDestructor:5475// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html5476// If __is_pod (type) is true or type is a reference type5477// then the trait is true, else if type is a cv class or union5478// type (or array thereof) with a trivial destructor5479// ([class.dtor]) then the trait is true, else it is5480// false.5481if (T.isPODType(C) || T->isReferenceType())5482return true;54835484// Objective-C++ ARC: autorelease types don't require destruction.5485if (T->isObjCLifetimeType() &&5486T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)5487return true;54885489if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())5490return RD->hasTrivialDestructor();5491return false;5492// TODO: Propagate nothrowness for implicitly declared special members.5493case UTT_HasNothrowAssign:5494// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:5495// If type is const qualified or is a reference type then the5496// trait is false. Otherwise if __has_trivial_assign (type)5497// is true then the trait is true, else if type is a cv class5498// or union type with copy assignment operators that are known5499// not to throw an exception then the trait is true, else it is5500// false.5501if (C.getBaseElementType(T).isConstQualified())5502return false;5503if (T->isReferenceType())5504return false;5505if (T.isPODType(C) || T->isObjCLifetimeType())5506return true;55075508if (const RecordType *RT = T->getAs<RecordType>())5509return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,5510&CXXRecordDecl::hasTrivialCopyAssignment,5511&CXXRecordDecl::hasNonTrivialCopyAssignment,5512&CXXMethodDecl::isCopyAssignmentOperator);5513return false;5514case UTT_HasNothrowMoveAssign:5515// This trait is implemented by MSVC 2012 and needed to parse the5516// standard library headers. Specifically this is used as the logic5517// behind std::is_nothrow_move_assignable (20.9.4.3).5518if (T.isPODType(C))5519return true;55205521if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())5522return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,5523&CXXRecordDecl::hasTrivialMoveAssignment,5524&CXXRecordDecl::hasNonTrivialMoveAssignment,5525&CXXMethodDecl::isMoveAssignmentOperator);5526return false;5527case UTT_HasNothrowCopy:5528// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:5529// If __has_trivial_copy (type) is true then the trait is true, else5530// if type is a cv class or union type with copy constructors that are5531// known not to throw an exception then the trait is true, else it is5532// false.5533if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())5534return true;5535if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {5536if (RD->hasTrivialCopyConstructor() &&5537!RD->hasNonTrivialCopyConstructor())5538return true;55395540bool FoundConstructor = false;5541unsigned FoundTQs;5542for (const auto *ND : Self.LookupConstructors(RD)) {5543// A template constructor is never a copy constructor.5544// FIXME: However, it may actually be selected at the actual overload5545// resolution point.5546if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))5547continue;5548// UsingDecl itself is not a constructor5549if (isa<UsingDecl>(ND))5550continue;5551auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());5552if (Constructor->isCopyConstructor(FoundTQs)) {5553FoundConstructor = true;5554auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();5555CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);5556if (!CPT)5557return false;5558// TODO: check whether evaluating default arguments can throw.5559// For now, we'll be conservative and assume that they can throw.5560if (!CPT->isNothrow() || CPT->getNumParams() > 1)5561return false;5562}5563}55645565return FoundConstructor;5566}5567return false;5568case UTT_HasNothrowConstructor:5569// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html5570// If __has_trivial_constructor (type) is true then the trait is5571// true, else if type is a cv class or union type (or array5572// thereof) with a default constructor that is known not to5573// throw an exception then the trait is true, else it is false.5574if (T.isPODType(C) || T->isObjCLifetimeType())5575return true;5576if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {5577if (RD->hasTrivialDefaultConstructor() &&5578!RD->hasNonTrivialDefaultConstructor())5579return true;55805581bool FoundConstructor = false;5582for (const auto *ND : Self.LookupConstructors(RD)) {5583// FIXME: In C++0x, a constructor template can be a default constructor.5584if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))5585continue;5586// UsingDecl itself is not a constructor5587if (isa<UsingDecl>(ND))5588continue;5589auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());5590if (Constructor->isDefaultConstructor()) {5591FoundConstructor = true;5592auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();5593CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);5594if (!CPT)5595return false;5596// FIXME: check whether evaluating default arguments can throw.5597// For now, we'll be conservative and assume that they can throw.5598if (!CPT->isNothrow() || CPT->getNumParams() > 0)5599return false;5600}5601}5602return FoundConstructor;5603}5604return false;5605case UTT_HasVirtualDestructor:5606// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:5607// If type is a class type with a virtual destructor ([class.dtor])5608// then the trait is true, else it is false.5609if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())5610if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))5611return Destructor->isVirtual();5612return false;56135614// These type trait expressions are modeled on the specifications for the5615// Embarcadero C++0x type trait functions:5616// http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index5617case UTT_IsCompleteType:5618// http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):5619// Returns True if and only if T is a complete type at the point of the5620// function call.5621return !T->isIncompleteType();5622case UTT_HasUniqueObjectRepresentations:5623return C.hasUniqueObjectRepresentations(T);5624case UTT_IsTriviallyRelocatable:5625return T.isTriviallyRelocatableType(C);5626case UTT_IsBitwiseCloneable:5627return T.isBitwiseCloneableType(C);5628case UTT_IsReferenceable:5629return T.isReferenceable();5630case UTT_CanPassInRegs:5631if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())5632return RD->canPassInRegisters();5633Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;5634return false;5635case UTT_IsTriviallyEqualityComparable:5636return isTriviallyEqualityComparableType(Self, T, KeyLoc);5637}5638}56395640static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,5641const TypeSourceInfo *Rhs, SourceLocation KeyLoc);56425643static ExprResult CheckConvertibilityForTypeTraits(5644Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs,5645SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator) {56465647QualType LhsT = Lhs->getType();5648QualType RhsT = Rhs->getType();56495650// C++0x [meta.rel]p4:5651// Given the following function prototype:5652//5653// template <class T>5654// typename add_rvalue_reference<T>::type create();5655//5656// the predicate condition for a template specialization5657// is_convertible<From, To> shall be satisfied if and only if5658// the return expression in the following code would be5659// well-formed, including any implicit conversions to the return5660// type of the function:5661//5662// To test() {5663// return create<From>();5664// }5665//5666// Access checking is performed as if in a context unrelated to To and5667// From. Only the validity of the immediate context of the expression5668// of the return-statement (including conversions to the return type)5669// is considered.5670//5671// We model the initialization as a copy-initialization of a temporary5672// of the appropriate type, which for this expression is identical to the5673// return statement (since NRVO doesn't apply).56745675// Functions aren't allowed to return function or array types.5676if (RhsT->isFunctionType() || RhsT->isArrayType())5677return ExprError();56785679// A function definition requires a complete, non-abstract return type.5680if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||5681Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))5682return ExprError();56835684// Compute the result of add_rvalue_reference.5685if (LhsT->isObjectType() || LhsT->isFunctionType())5686LhsT = Self.Context.getRValueReferenceType(LhsT);56875688// Build a fake source and destination for initialization.5689InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));5690Expr *From = new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())5691OpaqueValueExpr(KeyLoc, LhsT.getNonLValueExprType(Self.Context),5692Expr::getValueKindForType(LhsT));5693InitializationKind Kind =5694InitializationKind::CreateCopy(KeyLoc, SourceLocation());56955696// Perform the initialization in an unevaluated context within a SFINAE5697// trap at translation unit scope.5698EnterExpressionEvaluationContext Unevaluated(5699Self, Sema::ExpressionEvaluationContext::Unevaluated);5700Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);5701Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());5702InitializationSequence Init(Self, To, Kind, From);5703if (Init.Failed())5704return ExprError();57055706ExprResult Result = Init.Perform(Self, To, Kind, From);5707if (Result.isInvalid() || SFINAE.hasErrorOccurred())5708return ExprError();57095710return Result;5711}57125713static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait Kind,5714SourceLocation KWLoc,5715ArrayRef<TypeSourceInfo *> Args,5716SourceLocation RParenLoc,5717bool IsDependent) {5718if (IsDependent)5719return false;57205721if (Kind <= UTT_Last)5722return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]);57235724// Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary5725// alongside the IsConstructible traits to avoid duplication.5726if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary &&5727Kind != BTT_ReferenceConstructsFromTemporary &&5728Kind != BTT_ReferenceConvertsFromTemporary)5729return EvaluateBinaryTypeTrait(S, Kind, Args[0],5730Args[1], RParenLoc);57315732switch (Kind) {5733case clang::BTT_ReferenceBindsToTemporary:5734case clang::BTT_ReferenceConstructsFromTemporary:5735case clang::BTT_ReferenceConvertsFromTemporary:5736case clang::TT_IsConstructible:5737case clang::TT_IsNothrowConstructible:5738case clang::TT_IsTriviallyConstructible: {5739// C++11 [meta.unary.prop]:5740// is_trivially_constructible is defined as:5741//5742// is_constructible<T, Args...>::value is true and the variable5743// definition for is_constructible, as defined below, is known to call5744// no operation that is not trivial.5745//5746// The predicate condition for a template specialization5747// is_constructible<T, Args...> shall be satisfied if and only if the5748// following variable definition would be well-formed for some invented5749// variable t:5750//5751// T t(create<Args>()...);5752assert(!Args.empty());57535754// Precondition: T and all types in the parameter pack Args shall be5755// complete types, (possibly cv-qualified) void, or arrays of5756// unknown bound.5757for (const auto *TSI : Args) {5758QualType ArgTy = TSI->getType();5759if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())5760continue;57615762if (S.RequireCompleteType(KWLoc, ArgTy,5763diag::err_incomplete_type_used_in_type_trait_expr))5764return false;5765}57665767// Make sure the first argument is not incomplete nor a function type.5768QualType T = Args[0]->getType();5769if (T->isIncompleteType() || T->isFunctionType())5770return false;57715772// Make sure the first argument is not an abstract type.5773CXXRecordDecl *RD = T->getAsCXXRecordDecl();5774if (RD && RD->isAbstract())5775return false;57765777llvm::BumpPtrAllocator OpaqueExprAllocator;5778SmallVector<Expr *, 2> ArgExprs;5779ArgExprs.reserve(Args.size() - 1);5780for (unsigned I = 1, N = Args.size(); I != N; ++I) {5781QualType ArgTy = Args[I]->getType();5782if (ArgTy->isObjectType() || ArgTy->isFunctionType())5783ArgTy = S.Context.getRValueReferenceType(ArgTy);5784ArgExprs.push_back(5785new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())5786OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),5787ArgTy.getNonLValueExprType(S.Context),5788Expr::getValueKindForType(ArgTy)));5789}57905791// Perform the initialization in an unevaluated context within a SFINAE5792// trap at translation unit scope.5793EnterExpressionEvaluationContext Unevaluated(5794S, Sema::ExpressionEvaluationContext::Unevaluated);5795Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);5796Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());5797InitializedEntity To(5798InitializedEntity::InitializeTemporary(S.Context, Args[0]));5799InitializationKind InitKind(5800Kind == clang::BTT_ReferenceConvertsFromTemporary5801? InitializationKind::CreateCopy(KWLoc, KWLoc)5802: InitializationKind::CreateDirect(KWLoc, KWLoc, RParenLoc));5803InitializationSequence Init(S, To, InitKind, ArgExprs);5804if (Init.Failed())5805return false;58065807ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);5808if (Result.isInvalid() || SFINAE.hasErrorOccurred())5809return false;58105811if (Kind == clang::TT_IsConstructible)5812return true;58135814if (Kind == clang::BTT_ReferenceBindsToTemporary ||5815Kind == clang::BTT_ReferenceConstructsFromTemporary ||5816Kind == clang::BTT_ReferenceConvertsFromTemporary) {5817if (!T->isReferenceType())5818return false;58195820if (!Init.isDirectReferenceBinding())5821return true;58225823if (Kind == clang::BTT_ReferenceBindsToTemporary)5824return false;58255826QualType U = Args[1]->getType();5827if (U->isReferenceType())5828return false;58295830TypeSourceInfo *TPtr = S.Context.CreateTypeSourceInfo(5831S.Context.getPointerType(T.getNonReferenceType()));5832TypeSourceInfo *UPtr = S.Context.CreateTypeSourceInfo(5833S.Context.getPointerType(U.getNonReferenceType()));5834return !CheckConvertibilityForTypeTraits(S, UPtr, TPtr, RParenLoc,5835OpaqueExprAllocator)5836.isInvalid();5837}58385839if (Kind == clang::TT_IsNothrowConstructible)5840return S.canThrow(Result.get()) == CT_Cannot;58415842if (Kind == clang::TT_IsTriviallyConstructible) {5843// Under Objective-C ARC and Weak, if the destination has non-trivial5844// Objective-C lifetime, this is a non-trivial construction.5845if (T.getNonReferenceType().hasNonTrivialObjCLifetime())5846return false;58475848// The initialization succeeded; now make sure there are no non-trivial5849// calls.5850return !Result.get()->hasNonTrivialCall(S.Context);5851}58525853llvm_unreachable("unhandled type trait");5854return false;5855}5856default: llvm_unreachable("not a TT");5857}58585859return false;5860}58615862namespace {5863void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,5864SourceLocation KWLoc) {5865TypeTrait Replacement;5866switch (Kind) {5867case UTT_HasNothrowAssign:5868case UTT_HasNothrowMoveAssign:5869Replacement = BTT_IsNothrowAssignable;5870break;5871case UTT_HasNothrowCopy:5872case UTT_HasNothrowConstructor:5873Replacement = TT_IsNothrowConstructible;5874break;5875case UTT_HasTrivialAssign:5876case UTT_HasTrivialMoveAssign:5877Replacement = BTT_IsTriviallyAssignable;5878break;5879case UTT_HasTrivialCopy:5880Replacement = UTT_IsTriviallyCopyable;5881break;5882case UTT_HasTrivialDefaultConstructor:5883case UTT_HasTrivialMoveConstructor:5884Replacement = TT_IsTriviallyConstructible;5885break;5886case UTT_HasTrivialDestructor:5887Replacement = UTT_IsTriviallyDestructible;5888break;5889default:5890return;5891}5892S.Diag(KWLoc, diag::warn_deprecated_builtin)5893<< getTraitSpelling(Kind) << getTraitSpelling(Replacement);5894}5895}58965897bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {5898if (Arity && N != Arity) {5899Diag(Loc, diag::err_type_trait_arity)5900<< Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);5901return false;5902}59035904if (!Arity && N == 0) {5905Diag(Loc, diag::err_type_trait_arity)5906<< 1 << 1 << 1 << (int)N << SourceRange(Loc);5907return false;5908}5909return true;5910}59115912enum class TypeTraitReturnType {5913Bool,5914};59155916static TypeTraitReturnType GetReturnType(TypeTrait Kind) {5917return TypeTraitReturnType::Bool;5918}59195920ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,5921ArrayRef<TypeSourceInfo *> Args,5922SourceLocation RParenLoc) {5923if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))5924return ExprError();59255926if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(5927*this, Kind, KWLoc, Args[0]->getType()))5928return ExprError();59295930DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);59315932bool Dependent = false;5933for (unsigned I = 0, N = Args.size(); I != N; ++I) {5934if (Args[I]->getType()->isDependentType()) {5935Dependent = true;5936break;5937}5938}59395940switch (GetReturnType(Kind)) {5941case TypeTraitReturnType::Bool: {5942bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,5943Dependent);5944return TypeTraitExpr::Create(Context, Context.getLogicalOperationType(),5945KWLoc, Kind, Args, RParenLoc, Result);5946}5947}5948llvm_unreachable("unhandled type trait return type");5949}59505951ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,5952ArrayRef<ParsedType> Args,5953SourceLocation RParenLoc) {5954SmallVector<TypeSourceInfo *, 4> ConvertedArgs;5955ConvertedArgs.reserve(Args.size());59565957for (unsigned I = 0, N = Args.size(); I != N; ++I) {5958TypeSourceInfo *TInfo;5959QualType T = GetTypeFromParser(Args[I], &TInfo);5960if (!TInfo)5961TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);59625963ConvertedArgs.push_back(TInfo);5964}59655966return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);5967}59685969static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,5970const TypeSourceInfo *Rhs, SourceLocation KeyLoc) {5971QualType LhsT = Lhs->getType();5972QualType RhsT = Rhs->getType();59735974assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&5975"Cannot evaluate traits of dependent types");59765977switch(BTT) {5978case BTT_IsBaseOf: {5979// C++0x [meta.rel]p25980// Base is a base class of Derived without regard to cv-qualifiers or5981// Base and Derived are not unions and name the same class type without5982// regard to cv-qualifiers.59835984const RecordType *lhsRecord = LhsT->getAs<RecordType>();5985const RecordType *rhsRecord = RhsT->getAs<RecordType>();5986if (!rhsRecord || !lhsRecord) {5987const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();5988const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();5989if (!LHSObjTy || !RHSObjTy)5990return false;59915992ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();5993ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();5994if (!BaseInterface || !DerivedInterface)5995return false;59965997if (Self.RequireCompleteType(5998Rhs->getTypeLoc().getBeginLoc(), RhsT,5999diag::err_incomplete_type_used_in_type_trait_expr))6000return false;60016002return BaseInterface->isSuperClassOf(DerivedInterface);6003}60046005assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)6006== (lhsRecord == rhsRecord));60076008// Unions are never base classes, and never have base classes.6009// It doesn't matter if they are complete or not. See PR#418436010if (lhsRecord && lhsRecord->getDecl()->isUnion())6011return false;6012if (rhsRecord && rhsRecord->getDecl()->isUnion())6013return false;60146015if (lhsRecord == rhsRecord)6016return true;60176018// C++0x [meta.rel]p2:6019// If Base and Derived are class types and are different types6020// (ignoring possible cv-qualifiers) then Derived shall be a6021// complete type.6022if (Self.RequireCompleteType(6023Rhs->getTypeLoc().getBeginLoc(), RhsT,6024diag::err_incomplete_type_used_in_type_trait_expr))6025return false;60266027return cast<CXXRecordDecl>(rhsRecord->getDecl())6028->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));6029}6030case BTT_IsSame:6031return Self.Context.hasSameType(LhsT, RhsT);6032case BTT_TypeCompatible: {6033// GCC ignores cv-qualifiers on arrays for this builtin.6034Qualifiers LhsQuals, RhsQuals;6035QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);6036QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);6037return Self.Context.typesAreCompatible(Lhs, Rhs);6038}6039case BTT_IsConvertible:6040case BTT_IsConvertibleTo:6041case BTT_IsNothrowConvertible: {6042if (RhsT->isVoidType())6043return LhsT->isVoidType();6044llvm::BumpPtrAllocator OpaqueExprAllocator;6045ExprResult Result = CheckConvertibilityForTypeTraits(Self, Lhs, Rhs, KeyLoc,6046OpaqueExprAllocator);6047if (Result.isInvalid())6048return false;60496050if (BTT != BTT_IsNothrowConvertible)6051return true;60526053return Self.canThrow(Result.get()) == CT_Cannot;6054}60556056case BTT_IsAssignable:6057case BTT_IsNothrowAssignable:6058case BTT_IsTriviallyAssignable: {6059// C++11 [meta.unary.prop]p3:6060// is_trivially_assignable is defined as:6061// is_assignable<T, U>::value is true and the assignment, as defined by6062// is_assignable, is known to call no operation that is not trivial6063//6064// is_assignable is defined as:6065// The expression declval<T>() = declval<U>() is well-formed when6066// treated as an unevaluated operand (Clause 5).6067//6068// For both, T and U shall be complete types, (possibly cv-qualified)6069// void, or arrays of unknown bound.6070if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&6071Self.RequireCompleteType(6072Lhs->getTypeLoc().getBeginLoc(), LhsT,6073diag::err_incomplete_type_used_in_type_trait_expr))6074return false;6075if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&6076Self.RequireCompleteType(6077Rhs->getTypeLoc().getBeginLoc(), RhsT,6078diag::err_incomplete_type_used_in_type_trait_expr))6079return false;60806081// cv void is never assignable.6082if (LhsT->isVoidType() || RhsT->isVoidType())6083return false;60846085// Build expressions that emulate the effect of declval<T>() and6086// declval<U>().6087if (LhsT->isObjectType() || LhsT->isFunctionType())6088LhsT = Self.Context.getRValueReferenceType(LhsT);6089if (RhsT->isObjectType() || RhsT->isFunctionType())6090RhsT = Self.Context.getRValueReferenceType(RhsT);6091OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),6092Expr::getValueKindForType(LhsT));6093OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),6094Expr::getValueKindForType(RhsT));60956096// Attempt the assignment in an unevaluated context within a SFINAE6097// trap at translation unit scope.6098EnterExpressionEvaluationContext Unevaluated(6099Self, Sema::ExpressionEvaluationContext::Unevaluated);6100Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);6101Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());6102ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,6103&Rhs);6104if (Result.isInvalid())6105return false;61066107// Treat the assignment as unused for the purpose of -Wdeprecated-volatile.6108Self.CheckUnusedVolatileAssignment(Result.get());61096110if (SFINAE.hasErrorOccurred())6111return false;61126113if (BTT == BTT_IsAssignable)6114return true;61156116if (BTT == BTT_IsNothrowAssignable)6117return Self.canThrow(Result.get()) == CT_Cannot;61186119if (BTT == BTT_IsTriviallyAssignable) {6120// Under Objective-C ARC and Weak, if the destination has non-trivial6121// Objective-C lifetime, this is a non-trivial assignment.6122if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())6123return false;61246125return !Result.get()->hasNonTrivialCall(Self.Context);6126}61276128llvm_unreachable("unhandled type trait");6129return false;6130}6131case BTT_IsLayoutCompatible: {6132if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())6133Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,6134diag::err_incomplete_type);6135if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())6136Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,6137diag::err_incomplete_type);61386139DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible);6140DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible);61416142return Self.IsLayoutCompatible(LhsT, RhsT);6143}6144case BTT_IsPointerInterconvertibleBaseOf: {6145if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() &&6146!Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) {6147Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,6148diag::err_incomplete_type);6149}61506151DiagnoseVLAInCXXTypeTrait(Self, Lhs,6152tok::kw___is_pointer_interconvertible_base_of);6153DiagnoseVLAInCXXTypeTrait(Self, Rhs,6154tok::kw___is_pointer_interconvertible_base_of);61556156return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);6157}6158case BTT_IsDeducible: {6159const auto *TSTToBeDeduced = cast<DeducedTemplateSpecializationType>(LhsT);6160sema::TemplateDeductionInfo Info(KeyLoc);6161return Self.DeduceTemplateArgumentsFromType(6162TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT,6163Info) == TemplateDeductionResult::Success;6164}6165default:6166llvm_unreachable("not a BTT");6167}6168llvm_unreachable("Unknown type trait or not implemented");6169}61706171ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,6172SourceLocation KWLoc,6173ParsedType Ty,6174Expr* DimExpr,6175SourceLocation RParen) {6176TypeSourceInfo *TSInfo;6177QualType T = GetTypeFromParser(Ty, &TSInfo);6178if (!TSInfo)6179TSInfo = Context.getTrivialTypeSourceInfo(T);61806181return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);6182}61836184static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,6185QualType T, Expr *DimExpr,6186SourceLocation KeyLoc) {6187assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");61886189switch(ATT) {6190case ATT_ArrayRank:6191if (T->isArrayType()) {6192unsigned Dim = 0;6193while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {6194++Dim;6195T = AT->getElementType();6196}6197return Dim;6198}6199return 0;62006201case ATT_ArrayExtent: {6202llvm::APSInt Value;6203uint64_t Dim;6204if (Self.VerifyIntegerConstantExpression(6205DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)6206.isInvalid())6207return 0;6208if (Value.isSigned() && Value.isNegative()) {6209Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)6210<< DimExpr->getSourceRange();6211return 0;6212}6213Dim = Value.getLimitedValue();62146215if (T->isArrayType()) {6216unsigned D = 0;6217bool Matched = false;6218while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {6219if (Dim == D) {6220Matched = true;6221break;6222}6223++D;6224T = AT->getElementType();6225}62266227if (Matched && T->isArrayType()) {6228if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))6229return CAT->getLimitedSize();6230}6231}6232return 0;6233}6234}6235llvm_unreachable("Unknown type trait or not implemented");6236}62376238ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,6239SourceLocation KWLoc,6240TypeSourceInfo *TSInfo,6241Expr* DimExpr,6242SourceLocation RParen) {6243QualType T = TSInfo->getType();62446245// FIXME: This should likely be tracked as an APInt to remove any host6246// assumptions about the width of size_t on the target.6247uint64_t Value = 0;6248if (!T->isDependentType())6249Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);62506251// While the specification for these traits from the Embarcadero C++6252// compiler's documentation says the return type is 'unsigned int', Clang6253// returns 'size_t'. On Windows, the primary platform for the Embarcadero6254// compiler, there is no difference. On several other platforms this is an6255// important distinction.6256return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,6257RParen, Context.getSizeType());6258}62596260ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,6261SourceLocation KWLoc,6262Expr *Queried,6263SourceLocation RParen) {6264// If error parsing the expression, ignore.6265if (!Queried)6266return ExprError();62676268ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);62696270return Result;6271}62726273static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {6274switch (ET) {6275case ET_IsLValueExpr: return E->isLValue();6276case ET_IsRValueExpr:6277return E->isPRValue();6278}6279llvm_unreachable("Expression trait not covered by switch");6280}62816282ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,6283SourceLocation KWLoc,6284Expr *Queried,6285SourceLocation RParen) {6286if (Queried->isTypeDependent()) {6287// Delay type-checking for type-dependent expressions.6288} else if (Queried->hasPlaceholderType()) {6289ExprResult PE = CheckPlaceholderExpr(Queried);6290if (PE.isInvalid()) return ExprError();6291return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);6292}62936294bool Value = EvaluateExpressionTrait(ET, Queried);62956296return new (Context)6297ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);6298}62996300QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,6301ExprValueKind &VK,6302SourceLocation Loc,6303bool isIndirect) {6304assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&6305"placeholders should have been weeded out by now");63066307// The LHS undergoes lvalue conversions if this is ->*, and undergoes the6308// temporary materialization conversion otherwise.6309if (isIndirect)6310LHS = DefaultLvalueConversion(LHS.get());6311else if (LHS.get()->isPRValue())6312LHS = TemporaryMaterializationConversion(LHS.get());6313if (LHS.isInvalid())6314return QualType();63156316// The RHS always undergoes lvalue conversions.6317RHS = DefaultLvalueConversion(RHS.get());6318if (RHS.isInvalid()) return QualType();63196320const char *OpSpelling = isIndirect ? "->*" : ".*";6321// C++ 5.5p26322// The binary operator .* [p3: ->*] binds its second operand, which shall6323// be of type "pointer to member of T" (where T is a completely-defined6324// class type) [...]6325QualType RHSType = RHS.get()->getType();6326const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();6327if (!MemPtr) {6328Diag(Loc, diag::err_bad_memptr_rhs)6329<< OpSpelling << RHSType << RHS.get()->getSourceRange();6330return QualType();6331}63326333QualType Class(MemPtr->getClass(), 0);63346335// Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the6336// member pointer points must be completely-defined. However, there is no6337// reason for this semantic distinction, and the rule is not enforced by6338// other compilers. Therefore, we do not check this property, as it is6339// likely to be considered a defect.63406341// C++ 5.5p26342// [...] to its first operand, which shall be of class T or of a class of6343// which T is an unambiguous and accessible base class. [p3: a pointer to6344// such a class]6345QualType LHSType = LHS.get()->getType();6346if (isIndirect) {6347if (const PointerType *Ptr = LHSType->getAs<PointerType>())6348LHSType = Ptr->getPointeeType();6349else {6350Diag(Loc, diag::err_bad_memptr_lhs)6351<< OpSpelling << 1 << LHSType6352<< FixItHint::CreateReplacement(SourceRange(Loc), ".*");6353return QualType();6354}6355}63566357if (!Context.hasSameUnqualifiedType(Class, LHSType)) {6358// If we want to check the hierarchy, we need a complete type.6359if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,6360OpSpelling, (int)isIndirect)) {6361return QualType();6362}63636364if (!IsDerivedFrom(Loc, LHSType, Class)) {6365Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling6366<< (int)isIndirect << LHS.get()->getType();6367return QualType();6368}63696370CXXCastPath BasePath;6371if (CheckDerivedToBaseConversion(6372LHSType, Class, Loc,6373SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),6374&BasePath))6375return QualType();63766377// Cast LHS to type of use.6378QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());6379if (isIndirect)6380UseType = Context.getPointerType(UseType);6381ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();6382LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,6383&BasePath);6384}63856386if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {6387// Diagnose use of pointer-to-member type which when used as6388// the functional cast in a pointer-to-member expression.6389Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;6390return QualType();6391}63926393// C++ 5.5p26394// The result is an object or a function of the type specified by the6395// second operand.6396// The cv qualifiers are the union of those in the pointer and the left side,6397// in accordance with 5.5p5 and 5.2.5.6398QualType Result = MemPtr->getPointeeType();6399Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());64006401// C++0x [expr.mptr.oper]p6:6402// In a .* expression whose object expression is an rvalue, the program is6403// ill-formed if the second operand is a pointer to member function with6404// ref-qualifier &. In a ->* expression or in a .* expression whose object6405// expression is an lvalue, the program is ill-formed if the second operand6406// is a pointer to member function with ref-qualifier &&.6407if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {6408switch (Proto->getRefQualifier()) {6409case RQ_None:6410// Do nothing6411break;64126413case RQ_LValue:6414if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {6415// C++2a allows functions with ref-qualifier & if their cv-qualifier-seq6416// is (exactly) 'const'.6417if (Proto->isConst() && !Proto->isVolatile())6418Diag(Loc, getLangOpts().CPlusPlus206419? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue6420: diag::ext_pointer_to_const_ref_member_on_rvalue);6421else6422Diag(Loc, diag::err_pointer_to_member_oper_value_classify)6423<< RHSType << 1 << LHS.get()->getSourceRange();6424}6425break;64266427case RQ_RValue:6428if (isIndirect || !LHS.get()->Classify(Context).isRValue())6429Diag(Loc, diag::err_pointer_to_member_oper_value_classify)6430<< RHSType << 0 << LHS.get()->getSourceRange();6431break;6432}6433}64346435// C++ [expr.mptr.oper]p6:6436// The result of a .* expression whose second operand is a pointer6437// to a data member is of the same value category as its6438// first operand. The result of a .* expression whose second6439// operand is a pointer to a member function is a prvalue. The6440// result of an ->* expression is an lvalue if its second operand6441// is a pointer to data member and a prvalue otherwise.6442if (Result->isFunctionType()) {6443VK = VK_PRValue;6444return Context.BoundMemberTy;6445} else if (isIndirect) {6446VK = VK_LValue;6447} else {6448VK = LHS.get()->getValueKind();6449}64506451return Result;6452}64536454/// Try to convert a type to another according to C++11 5.16p3.6455///6456/// This is part of the parameter validation for the ? operator. If either6457/// value operand is a class type, the two operands are attempted to be6458/// converted to each other. This function does the conversion in one direction.6459/// It returns true if the program is ill-formed and has already been diagnosed6460/// as such.6461static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,6462SourceLocation QuestionLoc,6463bool &HaveConversion,6464QualType &ToType) {6465HaveConversion = false;6466ToType = To->getType();64676468InitializationKind Kind =6469InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());6470// C++11 5.16p36471// The process for determining whether an operand expression E1 of type T16472// can be converted to match an operand expression E2 of type T2 is defined6473// as follows:6474// -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be6475// implicitly converted to type "lvalue reference to T2", subject to the6476// constraint that in the conversion the reference must bind directly to6477// an lvalue.6478// -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be6479// implicitly converted to the type "rvalue reference to R2", subject to6480// the constraint that the reference must bind directly.6481if (To->isGLValue()) {6482QualType T = Self.Context.getReferenceQualifiedType(To);6483InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);64846485InitializationSequence InitSeq(Self, Entity, Kind, From);6486if (InitSeq.isDirectReferenceBinding()) {6487ToType = T;6488HaveConversion = true;6489return false;6490}64916492if (InitSeq.isAmbiguous())6493return InitSeq.Diagnose(Self, Entity, Kind, From);6494}64956496// -- If E2 is an rvalue, or if the conversion above cannot be done:6497// -- if E1 and E2 have class type, and the underlying class types are6498// the same or one is a base class of the other:6499QualType FTy = From->getType();6500QualType TTy = To->getType();6501const RecordType *FRec = FTy->getAs<RecordType>();6502const RecordType *TRec = TTy->getAs<RecordType>();6503bool FDerivedFromT = FRec && TRec && FRec != TRec &&6504Self.IsDerivedFrom(QuestionLoc, FTy, TTy);6505if (FRec && TRec && (FRec == TRec || FDerivedFromT ||6506Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {6507// E1 can be converted to match E2 if the class of T2 is the6508// same type as, or a base class of, the class of T1, and6509// [cv2 > cv1].6510if (FRec == TRec || FDerivedFromT) {6511if (TTy.isAtLeastAsQualifiedAs(FTy)) {6512InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);6513InitializationSequence InitSeq(Self, Entity, Kind, From);6514if (InitSeq) {6515HaveConversion = true;6516return false;6517}65186519if (InitSeq.isAmbiguous())6520return InitSeq.Diagnose(Self, Entity, Kind, From);6521}6522}65236524return false;6525}65266527// -- Otherwise: E1 can be converted to match E2 if E1 can be6528// implicitly converted to the type that expression E2 would have6529// if E2 were converted to an rvalue (or the type it has, if E2 is6530// an rvalue).6531//6532// This actually refers very narrowly to the lvalue-to-rvalue conversion, not6533// to the array-to-pointer or function-to-pointer conversions.6534TTy = TTy.getNonLValueExprType(Self.Context);65356536InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);6537InitializationSequence InitSeq(Self, Entity, Kind, From);6538HaveConversion = !InitSeq.Failed();6539ToType = TTy;6540if (InitSeq.isAmbiguous())6541return InitSeq.Diagnose(Self, Entity, Kind, From);65426543return false;6544}65456546/// Try to find a common type for two according to C++0x 5.16p5.6547///6548/// This is part of the parameter validation for the ? operator. If either6549/// value operand is a class type, overload resolution is used to find a6550/// conversion to a common type.6551static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,6552SourceLocation QuestionLoc) {6553Expr *Args[2] = { LHS.get(), RHS.get() };6554OverloadCandidateSet CandidateSet(QuestionLoc,6555OverloadCandidateSet::CSK_Operator);6556Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,6557CandidateSet);65586559OverloadCandidateSet::iterator Best;6560switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {6561case OR_Success: {6562// We found a match. Perform the conversions on the arguments and move on.6563ExprResult LHSRes = Self.PerformImplicitConversion(6564LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],6565Sema::AA_Converting);6566if (LHSRes.isInvalid())6567break;6568LHS = LHSRes;65696570ExprResult RHSRes = Self.PerformImplicitConversion(6571RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],6572Sema::AA_Converting);6573if (RHSRes.isInvalid())6574break;6575RHS = RHSRes;6576if (Best->Function)6577Self.MarkFunctionReferenced(QuestionLoc, Best->Function);6578return false;6579}65806581case OR_No_Viable_Function:65826583// Emit a better diagnostic if one of the expressions is a null pointer6584// constant and the other is a pointer type. In this case, the user most6585// likely forgot to take the address of the other expression.6586if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))6587return true;65886589Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)6590<< LHS.get()->getType() << RHS.get()->getType()6591<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();6592return true;65936594case OR_Ambiguous:6595Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)6596<< LHS.get()->getType() << RHS.get()->getType()6597<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();6598// FIXME: Print the possible common types by printing the return types of6599// the viable candidates.6600break;66016602case OR_Deleted:6603llvm_unreachable("Conditional operator has only built-in overloads");6604}6605return true;6606}66076608/// Perform an "extended" implicit conversion as returned by6609/// TryClassUnification.6610static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {6611InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);6612InitializationKind Kind =6613InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());6614Expr *Arg = E.get();6615InitializationSequence InitSeq(Self, Entity, Kind, Arg);6616ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);6617if (Result.isInvalid())6618return true;66196620E = Result;6621return false;6622}66236624// Check the condition operand of ?: to see if it is valid for the GCC6625// extension.6626static bool isValidVectorForConditionalCondition(ASTContext &Ctx,6627QualType CondTy) {6628if (!CondTy->isVectorType() && !CondTy->isExtVectorType())6629return false;6630const QualType EltTy =6631cast<VectorType>(CondTy.getCanonicalType())->getElementType();6632assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");6633return EltTy->isIntegralType(Ctx);6634}66356636static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx,6637QualType CondTy) {6638if (!CondTy->isSveVLSBuiltinType())6639return false;6640const QualType EltTy =6641cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);6642assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");6643return EltTy->isIntegralType(Ctx);6644}66456646QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,6647ExprResult &RHS,6648SourceLocation QuestionLoc) {6649LHS = DefaultFunctionArrayLvalueConversion(LHS.get());6650RHS = DefaultFunctionArrayLvalueConversion(RHS.get());66516652QualType CondType = Cond.get()->getType();6653const auto *CondVT = CondType->castAs<VectorType>();6654QualType CondElementTy = CondVT->getElementType();6655unsigned CondElementCount = CondVT->getNumElements();6656QualType LHSType = LHS.get()->getType();6657const auto *LHSVT = LHSType->getAs<VectorType>();6658QualType RHSType = RHS.get()->getType();6659const auto *RHSVT = RHSType->getAs<VectorType>();66606661QualType ResultType;666266636664if (LHSVT && RHSVT) {6665if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {6666Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)6667<< /*isExtVector*/ isa<ExtVectorType>(CondVT);6668return {};6669}66706671// If both are vector types, they must be the same type.6672if (!Context.hasSameType(LHSType, RHSType)) {6673Diag(QuestionLoc, diag::err_conditional_vector_mismatched)6674<< LHSType << RHSType;6675return {};6676}6677ResultType = Context.getCommonSugaredType(LHSType, RHSType);6678} else if (LHSVT || RHSVT) {6679ResultType = CheckVectorOperands(6680LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,6681/*AllowBoolConversions*/ false,6682/*AllowBoolOperation*/ true,6683/*ReportInvalid*/ true);6684if (ResultType.isNull())6685return {};6686} else {6687// Both are scalar.6688LHSType = LHSType.getUnqualifiedType();6689RHSType = RHSType.getUnqualifiedType();6690QualType ResultElementTy =6691Context.hasSameType(LHSType, RHSType)6692? Context.getCommonSugaredType(LHSType, RHSType)6693: UsualArithmeticConversions(LHS, RHS, QuestionLoc,6694ACK_Conditional);66956696if (ResultElementTy->isEnumeralType()) {6697Diag(QuestionLoc, diag::err_conditional_vector_operand_type)6698<< ResultElementTy;6699return {};6700}6701if (CondType->isExtVectorType())6702ResultType =6703Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());6704else6705ResultType = Context.getVectorType(6706ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);67076708LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);6709RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);6710}67116712assert(!ResultType.isNull() && ResultType->isVectorType() &&6713(!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&6714"Result should have been a vector type");6715auto *ResultVectorTy = ResultType->castAs<VectorType>();6716QualType ResultElementTy = ResultVectorTy->getElementType();6717unsigned ResultElementCount = ResultVectorTy->getNumElements();67186719if (ResultElementCount != CondElementCount) {6720Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType6721<< ResultType;6722return {};6723}67246725if (Context.getTypeSize(ResultElementTy) !=6726Context.getTypeSize(CondElementTy)) {6727Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType6728<< ResultType;6729return {};6730}67316732return ResultType;6733}67346735QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond,6736ExprResult &LHS,6737ExprResult &RHS,6738SourceLocation QuestionLoc) {6739LHS = DefaultFunctionArrayLvalueConversion(LHS.get());6740RHS = DefaultFunctionArrayLvalueConversion(RHS.get());67416742QualType CondType = Cond.get()->getType();6743const auto *CondBT = CondType->castAs<BuiltinType>();6744QualType CondElementTy = CondBT->getSveEltType(Context);6745llvm::ElementCount CondElementCount =6746Context.getBuiltinVectorTypeInfo(CondBT).EC;67476748QualType LHSType = LHS.get()->getType();6749const auto *LHSBT =6750LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;6751QualType RHSType = RHS.get()->getType();6752const auto *RHSBT =6753RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;67546755QualType ResultType;67566757if (LHSBT && RHSBT) {6758// If both are sizeless vector types, they must be the same type.6759if (!Context.hasSameType(LHSType, RHSType)) {6760Diag(QuestionLoc, diag::err_conditional_vector_mismatched)6761<< LHSType << RHSType;6762return QualType();6763}6764ResultType = LHSType;6765} else if (LHSBT || RHSBT) {6766ResultType = CheckSizelessVectorOperands(6767LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);6768if (ResultType.isNull())6769return QualType();6770} else {6771// Both are scalar so splat6772QualType ResultElementTy;6773LHSType = LHSType.getCanonicalType().getUnqualifiedType();6774RHSType = RHSType.getCanonicalType().getUnqualifiedType();67756776if (Context.hasSameType(LHSType, RHSType))6777ResultElementTy = LHSType;6778else6779ResultElementTy =6780UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);67816782if (ResultElementTy->isEnumeralType()) {6783Diag(QuestionLoc, diag::err_conditional_vector_operand_type)6784<< ResultElementTy;6785return QualType();6786}67876788ResultType = Context.getScalableVectorType(6789ResultElementTy, CondElementCount.getKnownMinValue());67906791LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);6792RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);6793}67946795assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&6796"Result should have been a vector type");6797auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();6798QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);6799llvm::ElementCount ResultElementCount =6800Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;68016802if (ResultElementCount != CondElementCount) {6803Diag(QuestionLoc, diag::err_conditional_vector_size)6804<< CondType << ResultType;6805return QualType();6806}68076808if (Context.getTypeSize(ResultElementTy) !=6809Context.getTypeSize(CondElementTy)) {6810Diag(QuestionLoc, diag::err_conditional_vector_element_size)6811<< CondType << ResultType;6812return QualType();6813}68146815return ResultType;6816}68176818QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,6819ExprResult &RHS, ExprValueKind &VK,6820ExprObjectKind &OK,6821SourceLocation QuestionLoc) {6822// FIXME: Handle C99's complex types, block pointers and Obj-C++ interface6823// pointers.68246825// Assume r-value.6826VK = VK_PRValue;6827OK = OK_Ordinary;6828bool IsVectorConditional =6829isValidVectorForConditionalCondition(Context, Cond.get()->getType());68306831bool IsSizelessVectorConditional =6832isValidSizelessVectorForConditionalCondition(Context,6833Cond.get()->getType());68346835// C++11 [expr.cond]p16836// The first expression is contextually converted to bool.6837if (!Cond.get()->isTypeDependent()) {6838ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional6839? DefaultFunctionArrayLvalueConversion(Cond.get())6840: CheckCXXBooleanCondition(Cond.get());6841if (CondRes.isInvalid())6842return QualType();6843Cond = CondRes;6844} else {6845// To implement C++, the first expression typically doesn't alter the result6846// type of the conditional, however the GCC compatible vector extension6847// changes the result type to be that of the conditional. Since we cannot6848// know if this is a vector extension here, delay the conversion of the6849// LHS/RHS below until later.6850return Context.DependentTy;6851}685268536854// Either of the arguments dependent?6855if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())6856return Context.DependentTy;68576858// C++11 [expr.cond]p26859// If either the second or the third operand has type (cv) void, ...6860QualType LTy = LHS.get()->getType();6861QualType RTy = RHS.get()->getType();6862bool LVoid = LTy->isVoidType();6863bool RVoid = RTy->isVoidType();6864if (LVoid || RVoid) {6865// ... one of the following shall hold:6866// -- The second or the third operand (but not both) is a (possibly6867// parenthesized) throw-expression; the result is of the type6868// and value category of the other.6869bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());6870bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());68716872// Void expressions aren't legal in the vector-conditional expressions.6873if (IsVectorConditional) {6874SourceRange DiagLoc =6875LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();6876bool IsThrow = LVoid ? LThrow : RThrow;6877Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)6878<< DiagLoc << IsThrow;6879return QualType();6880}68816882if (LThrow != RThrow) {6883Expr *NonThrow = LThrow ? RHS.get() : LHS.get();6884VK = NonThrow->getValueKind();6885// DR (no number yet): the result is a bit-field if the6886// non-throw-expression operand is a bit-field.6887OK = NonThrow->getObjectKind();6888return NonThrow->getType();6889}68906891// -- Both the second and third operands have type void; the result is of6892// type void and is a prvalue.6893if (LVoid && RVoid)6894return Context.getCommonSugaredType(LTy, RTy);68956896// Neither holds, error.6897Diag(QuestionLoc, diag::err_conditional_void_nonvoid)6898<< (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)6899<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();6900return QualType();6901}69026903// Neither is void.6904if (IsVectorConditional)6905return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);69066907if (IsSizelessVectorConditional)6908return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);69096910// WebAssembly tables are not allowed as conditional LHS or RHS.6911if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {6912Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)6913<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();6914return QualType();6915}69166917// C++11 [expr.cond]p36918// Otherwise, if the second and third operand have different types, and6919// either has (cv) class type [...] an attempt is made to convert each of6920// those operands to the type of the other.6921if (!Context.hasSameType(LTy, RTy) &&6922(LTy->isRecordType() || RTy->isRecordType())) {6923// These return true if a single direction is already ambiguous.6924QualType L2RType, R2LType;6925bool HaveL2R, HaveR2L;6926if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))6927return QualType();6928if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))6929return QualType();69306931// If both can be converted, [...] the program is ill-formed.6932if (HaveL2R && HaveR2L) {6933Diag(QuestionLoc, diag::err_conditional_ambiguous)6934<< LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();6935return QualType();6936}69376938// If exactly one conversion is possible, that conversion is applied to6939// the chosen operand and the converted operands are used in place of the6940// original operands for the remainder of this section.6941if (HaveL2R) {6942if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())6943return QualType();6944LTy = LHS.get()->getType();6945} else if (HaveR2L) {6946if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())6947return QualType();6948RTy = RHS.get()->getType();6949}6950}69516952// C++11 [expr.cond]p36953// if both are glvalues of the same value category and the same type except6954// for cv-qualification, an attempt is made to convert each of those6955// operands to the type of the other.6956// FIXME:6957// Resolving a defect in P0012R1: we extend this to cover all cases where6958// one of the operands is reference-compatible with the other, in order6959// to support conditionals between functions differing in noexcept. This6960// will similarly cover difference in array bounds after P0388R4.6961// FIXME: If LTy and RTy have a composite pointer type, should we convert to6962// that instead?6963ExprValueKind LVK = LHS.get()->getValueKind();6964ExprValueKind RVK = RHS.get()->getValueKind();6965if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {6966// DerivedToBase was already handled by the class-specific case above.6967// FIXME: Should we allow ObjC conversions here?6968const ReferenceConversions AllowedConversions =6969ReferenceConversions::Qualification |6970ReferenceConversions::NestedQualification |6971ReferenceConversions::Function;69726973ReferenceConversions RefConv;6974if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==6975Ref_Compatible &&6976!(RefConv & ~AllowedConversions) &&6977// [...] subject to the constraint that the reference must bind6978// directly [...]6979!RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {6980RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);6981RTy = RHS.get()->getType();6982} else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==6983Ref_Compatible &&6984!(RefConv & ~AllowedConversions) &&6985!LHS.get()->refersToBitField() &&6986!LHS.get()->refersToVectorElement()) {6987LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);6988LTy = LHS.get()->getType();6989}6990}69916992// C++11 [expr.cond]p46993// If the second and third operands are glvalues of the same value6994// category and have the same type, the result is of that type and6995// value category and it is a bit-field if the second or the third6996// operand is a bit-field, or if both are bit-fields.6997// We only extend this to bitfields, not to the crazy other kinds of6998// l-values.6999bool Same = Context.hasSameType(LTy, RTy);7000if (Same && LVK == RVK && LVK != VK_PRValue &&7001LHS.get()->isOrdinaryOrBitFieldObject() &&7002RHS.get()->isOrdinaryOrBitFieldObject()) {7003VK = LHS.get()->getValueKind();7004if (LHS.get()->getObjectKind() == OK_BitField ||7005RHS.get()->getObjectKind() == OK_BitField)7006OK = OK_BitField;7007return Context.getCommonSugaredType(LTy, RTy);7008}70097010// C++11 [expr.cond]p57011// Otherwise, the result is a prvalue. If the second and third operands7012// do not have the same type, and either has (cv) class type, ...7013if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {7014// ... overload resolution is used to determine the conversions (if any)7015// to be applied to the operands. If the overload resolution fails, the7016// program is ill-formed.7017if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))7018return QualType();7019}70207021// C++11 [expr.cond]p67022// Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard7023// conversions are performed on the second and third operands.7024LHS = DefaultFunctionArrayLvalueConversion(LHS.get());7025RHS = DefaultFunctionArrayLvalueConversion(RHS.get());7026if (LHS.isInvalid() || RHS.isInvalid())7027return QualType();7028LTy = LHS.get()->getType();7029RTy = RHS.get()->getType();70307031// After those conversions, one of the following shall hold:7032// -- The second and third operands have the same type; the result7033// is of that type. If the operands have class type, the result7034// is a prvalue temporary of the result type, which is7035// copy-initialized from either the second operand or the third7036// operand depending on the value of the first operand.7037if (Context.hasSameType(LTy, RTy)) {7038if (LTy->isRecordType()) {7039// The operands have class type. Make a temporary copy.7040ExprResult LHSCopy = PerformCopyInitialization(7041InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS);7042if (LHSCopy.isInvalid())7043return QualType();70447045ExprResult RHSCopy = PerformCopyInitialization(7046InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS);7047if (RHSCopy.isInvalid())7048return QualType();70497050LHS = LHSCopy;7051RHS = RHSCopy;7052}7053return Context.getCommonSugaredType(LTy, RTy);7054}70557056// Extension: conditional operator involving vector types.7057if (LTy->isVectorType() || RTy->isVectorType())7058return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,7059/*AllowBothBool*/ true,7060/*AllowBoolConversions*/ false,7061/*AllowBoolOperation*/ false,7062/*ReportInvalid*/ true);70637064// -- The second and third operands have arithmetic or enumeration type;7065// the usual arithmetic conversions are performed to bring them to a7066// common type, and the result is of that type.7067if (LTy->isArithmeticType() && RTy->isArithmeticType()) {7068QualType ResTy =7069UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);7070if (LHS.isInvalid() || RHS.isInvalid())7071return QualType();7072if (ResTy.isNull()) {7073Diag(QuestionLoc,7074diag::err_typecheck_cond_incompatible_operands) << LTy << RTy7075<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();7076return QualType();7077}70787079LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));7080RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));70817082return ResTy;7083}70847085// -- The second and third operands have pointer type, or one has pointer7086// type and the other is a null pointer constant, or both are null7087// pointer constants, at least one of which is non-integral; pointer7088// conversions and qualification conversions are performed to bring them7089// to their composite pointer type. The result is of the composite7090// pointer type.7091// -- The second and third operands have pointer to member type, or one has7092// pointer to member type and the other is a null pointer constant;7093// pointer to member conversions and qualification conversions are7094// performed to bring them to a common type, whose cv-qualification7095// shall match the cv-qualification of either the second or the third7096// operand. The result is of the common type.7097QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);7098if (!Composite.isNull())7099return Composite;71007101// Similarly, attempt to find composite type of two objective-c pointers.7102Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);7103if (LHS.isInvalid() || RHS.isInvalid())7104return QualType();7105if (!Composite.isNull())7106return Composite;71077108// Check if we are using a null with a non-pointer type.7109if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))7110return QualType();71117112Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)7113<< LHS.get()->getType() << RHS.get()->getType()7114<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();7115return QualType();7116}71177118QualType Sema::FindCompositePointerType(SourceLocation Loc,7119Expr *&E1, Expr *&E2,7120bool ConvertArgs) {7121assert(getLangOpts().CPlusPlus && "This function assumes C++");71227123// C++1z [expr]p14:7124// The composite pointer type of two operands p1 and p2 having types T17125// and T27126QualType T1 = E1->getType(), T2 = E2->getType();71277128// where at least one is a pointer or pointer to member type or7129// std::nullptr_t is:7130bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||7131T1->isNullPtrType();7132bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||7133T2->isNullPtrType();7134if (!T1IsPointerLike && !T2IsPointerLike)7135return QualType();71367137// - if both p1 and p2 are null pointer constants, std::nullptr_t;7138// This can't actually happen, following the standard, but we also use this7139// to implement the end of [expr.conv], which hits this case.7140//7141// - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;7142if (T1IsPointerLike &&7143E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {7144if (ConvertArgs)7145E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()7146? CK_NullToMemberPointer7147: CK_NullToPointer).get();7148return T1;7149}7150if (T2IsPointerLike &&7151E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {7152if (ConvertArgs)7153E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()7154? CK_NullToMemberPointer7155: CK_NullToPointer).get();7156return T2;7157}71587159// Now both have to be pointers or member pointers.7160if (!T1IsPointerLike || !T2IsPointerLike)7161return QualType();7162assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&7163"nullptr_t should be a null pointer constant");71647165struct Step {7166enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;7167// Qualifiers to apply under the step kind.7168Qualifiers Quals;7169/// The class for a pointer-to-member; a constant array type with a bound7170/// (if any) for an array.7171const Type *ClassOrBound;71727173Step(Kind K, const Type *ClassOrBound = nullptr)7174: K(K), ClassOrBound(ClassOrBound) {}7175QualType rebuild(ASTContext &Ctx, QualType T) const {7176T = Ctx.getQualifiedType(T, Quals);7177switch (K) {7178case Pointer:7179return Ctx.getPointerType(T);7180case MemberPointer:7181return Ctx.getMemberPointerType(T, ClassOrBound);7182case ObjCPointer:7183return Ctx.getObjCObjectPointerType(T);7184case Array:7185if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))7186return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,7187ArraySizeModifier::Normal, 0);7188else7189return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);7190}7191llvm_unreachable("unknown step kind");7192}7193};71947195SmallVector<Step, 8> Steps;71967197// - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C17198// is reference-related to C2 or C2 is reference-related to C1 (8.6.3),7199// the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,7200// respectively;7201// - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer7202// to member of C2 of type cv2 U2" for some non-function type U, where7203// C1 is reference-related to C2 or C2 is reference-related to C1, the7204// cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,7205// respectively;7206// - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and7207// T2;7208//7209// Dismantle T1 and T2 to simultaneously determine whether they are similar7210// and to prepare to form the cv-combined type if so.7211QualType Composite1 = T1;7212QualType Composite2 = T2;7213unsigned NeedConstBefore = 0;7214while (true) {7215assert(!Composite1.isNull() && !Composite2.isNull());72167217Qualifiers Q1, Q2;7218Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);7219Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);72207221// Top-level qualifiers are ignored. Merge at all lower levels.7222if (!Steps.empty()) {7223// Find the qualifier union: (approximately) the unique minimal set of7224// qualifiers that is compatible with both types.7225Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |7226Q2.getCVRUQualifiers());72277228// Under one level of pointer or pointer-to-member, we can change to an7229// unambiguous compatible address space.7230if (Q1.getAddressSpace() == Q2.getAddressSpace()) {7231Quals.setAddressSpace(Q1.getAddressSpace());7232} else if (Steps.size() == 1) {7233bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);7234bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);7235if (MaybeQ1 == MaybeQ2) {7236// Exception for ptr size address spaces. Should be able to choose7237// either address space during comparison.7238if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||7239isPtrSizeAddressSpace(Q2.getAddressSpace()))7240MaybeQ1 = true;7241else7242return QualType(); // No unique best address space.7243}7244Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()7245: Q2.getAddressSpace());7246} else {7247return QualType();7248}72497250// FIXME: In C, we merge __strong and none to __strong at the top level.7251if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())7252Quals.setObjCGCAttr(Q1.getObjCGCAttr());7253else if (T1->isVoidPointerType() || T2->isVoidPointerType())7254assert(Steps.size() == 1);7255else7256return QualType();72577258// Mismatched lifetime qualifiers never compatibly include each other.7259if (Q1.getObjCLifetime() == Q2.getObjCLifetime())7260Quals.setObjCLifetime(Q1.getObjCLifetime());7261else if (T1->isVoidPointerType() || T2->isVoidPointerType())7262assert(Steps.size() == 1);7263else7264return QualType();72657266Steps.back().Quals = Quals;7267if (Q1 != Quals || Q2 != Quals)7268NeedConstBefore = Steps.size() - 1;7269}72707271// FIXME: Can we unify the following with UnwrapSimilarTypes?72727273const ArrayType *Arr1, *Arr2;7274if ((Arr1 = Context.getAsArrayType(Composite1)) &&7275(Arr2 = Context.getAsArrayType(Composite2))) {7276auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);7277auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);7278if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {7279Composite1 = Arr1->getElementType();7280Composite2 = Arr2->getElementType();7281Steps.emplace_back(Step::Array, CAT1);7282continue;7283}7284bool IAT1 = isa<IncompleteArrayType>(Arr1);7285bool IAT2 = isa<IncompleteArrayType>(Arr2);7286if ((IAT1 && IAT2) ||7287(getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&7288((bool)CAT1 != (bool)CAT2) &&7289(Steps.empty() || Steps.back().K != Step::Array))) {7290// In C++20 onwards, we can unify an array of N T with an array of7291// a different or unknown bound. But we can't form an array whose7292// element type is an array of unknown bound by doing so.7293Composite1 = Arr1->getElementType();7294Composite2 = Arr2->getElementType();7295Steps.emplace_back(Step::Array);7296if (CAT1 || CAT2)7297NeedConstBefore = Steps.size();7298continue;7299}7300}73017302const PointerType *Ptr1, *Ptr2;7303if ((Ptr1 = Composite1->getAs<PointerType>()) &&7304(Ptr2 = Composite2->getAs<PointerType>())) {7305Composite1 = Ptr1->getPointeeType();7306Composite2 = Ptr2->getPointeeType();7307Steps.emplace_back(Step::Pointer);7308continue;7309}73107311const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;7312if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&7313(ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {7314Composite1 = ObjPtr1->getPointeeType();7315Composite2 = ObjPtr2->getPointeeType();7316Steps.emplace_back(Step::ObjCPointer);7317continue;7318}73197320const MemberPointerType *MemPtr1, *MemPtr2;7321if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&7322(MemPtr2 = Composite2->getAs<MemberPointerType>())) {7323Composite1 = MemPtr1->getPointeeType();7324Composite2 = MemPtr2->getPointeeType();73257326// At the top level, we can perform a base-to-derived pointer-to-member7327// conversion:7328//7329// - [...] where C1 is reference-related to C2 or C2 is7330// reference-related to C17331//7332// (Note that the only kinds of reference-relatedness in scope here are7333// "same type or derived from".) At any other level, the class must7334// exactly match.7335const Type *Class = nullptr;7336QualType Cls1(MemPtr1->getClass(), 0);7337QualType Cls2(MemPtr2->getClass(), 0);7338if (Context.hasSameType(Cls1, Cls2))7339Class = MemPtr1->getClass();7340else if (Steps.empty())7341Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :7342IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;7343if (!Class)7344return QualType();73457346Steps.emplace_back(Step::MemberPointer, Class);7347continue;7348}73497350// Special case: at the top level, we can decompose an Objective-C pointer7351// and a 'cv void *'. Unify the qualifiers.7352if (Steps.empty() && ((Composite1->isVoidPointerType() &&7353Composite2->isObjCObjectPointerType()) ||7354(Composite1->isObjCObjectPointerType() &&7355Composite2->isVoidPointerType()))) {7356Composite1 = Composite1->getPointeeType();7357Composite2 = Composite2->getPointeeType();7358Steps.emplace_back(Step::Pointer);7359continue;7360}73617362// FIXME: block pointer types?73637364// Cannot unwrap any more types.7365break;7366}73677368// - if T1 or T2 is "pointer to noexcept function" and the other type is7369// "pointer to function", where the function types are otherwise the same,7370// "pointer to function";7371// - if T1 or T2 is "pointer to member of C1 of type function", the other7372// type is "pointer to member of C2 of type noexcept function", and C17373// is reference-related to C2 or C2 is reference-related to C1, where7374// the function types are otherwise the same, "pointer to member of C2 of7375// type function" or "pointer to member of C1 of type function",7376// respectively;7377//7378// We also support 'noreturn' here, so as a Clang extension we generalize the7379// above to:7380//7381// - [Clang] If T1 and T2 are both of type "pointer to function" or7382// "pointer to member function" and the pointee types can be unified7383// by a function pointer conversion, that conversion is applied7384// before checking the following rules.7385//7386// We've already unwrapped down to the function types, and we want to merge7387// rather than just convert, so do this ourselves rather than calling7388// IsFunctionConversion.7389//7390// FIXME: In order to match the standard wording as closely as possible, we7391// currently only do this under a single level of pointers. Ideally, we would7392// allow this in general, and set NeedConstBefore to the relevant depth on7393// the side(s) where we changed anything. If we permit that, we should also7394// consider this conversion when determining type similarity and model it as7395// a qualification conversion.7396if (Steps.size() == 1) {7397if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {7398if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {7399FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();7400FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();74017402// The result is noreturn if both operands are.7403bool Noreturn =7404EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();7405EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);7406EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);74077408// The result is nothrow if both operands are.7409SmallVector<QualType, 8> ExceptionTypeStorage;7410EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(7411EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,7412getLangOpts().CPlusPlus17);74137414Composite1 = Context.getFunctionType(FPT1->getReturnType(),7415FPT1->getParamTypes(), EPI1);7416Composite2 = Context.getFunctionType(FPT2->getReturnType(),7417FPT2->getParamTypes(), EPI2);7418}7419}7420}74217422// There are some more conversions we can perform under exactly one pointer.7423if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&7424!Context.hasSameType(Composite1, Composite2)) {7425// - if T1 or T2 is "pointer to cv1 void" and the other type is7426// "pointer to cv2 T", where T is an object type or void,7427// "pointer to cv12 void", where cv12 is the union of cv1 and cv2;7428if (Composite1->isVoidType() && Composite2->isObjectType())7429Composite2 = Composite1;7430else if (Composite2->isVoidType() && Composite1->isObjectType())7431Composite1 = Composite2;7432// - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C17433// is reference-related to C2 or C2 is reference-related to C1 (8.6.3),7434// the cv-combined type of T1 and T2 or the cv-combined type of T2 and7435// T1, respectively;7436//7437// The "similar type" handling covers all of this except for the "T1 is a7438// base class of T2" case in the definition of reference-related.7439else if (IsDerivedFrom(Loc, Composite1, Composite2))7440Composite1 = Composite2;7441else if (IsDerivedFrom(Loc, Composite2, Composite1))7442Composite2 = Composite1;7443}74447445// At this point, either the inner types are the same or we have failed to7446// find a composite pointer type.7447if (!Context.hasSameType(Composite1, Composite2))7448return QualType();74497450// Per C++ [conv.qual]p3, add 'const' to every level before the last7451// differing qualifier.7452for (unsigned I = 0; I != NeedConstBefore; ++I)7453Steps[I].Quals.addConst();74547455// Rebuild the composite type.7456QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);7457for (auto &S : llvm::reverse(Steps))7458Composite = S.rebuild(Context, Composite);74597460if (ConvertArgs) {7461// Convert the expressions to the composite pointer type.7462InitializedEntity Entity =7463InitializedEntity::InitializeTemporary(Composite);7464InitializationKind Kind =7465InitializationKind::CreateCopy(Loc, SourceLocation());74667467InitializationSequence E1ToC(*this, Entity, Kind, E1);7468if (!E1ToC)7469return QualType();74707471InitializationSequence E2ToC(*this, Entity, Kind, E2);7472if (!E2ToC)7473return QualType();74747475// FIXME: Let the caller know if these fail to avoid duplicate diagnostics.7476ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);7477if (E1Result.isInvalid())7478return QualType();7479E1 = E1Result.get();74807481ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);7482if (E2Result.isInvalid())7483return QualType();7484E2 = E2Result.get();7485}74867487return Composite;7488}74897490ExprResult Sema::MaybeBindToTemporary(Expr *E) {7491if (!E)7492return ExprError();74937494assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");74957496// If the result is a glvalue, we shouldn't bind it.7497if (E->isGLValue())7498return E;74997500// In ARC, calls that return a retainable type can return retained,7501// in which case we have to insert a consuming cast.7502if (getLangOpts().ObjCAutoRefCount &&7503E->getType()->isObjCRetainableType()) {75047505bool ReturnsRetained;75067507// For actual calls, we compute this by examining the type of the7508// called value.7509if (CallExpr *Call = dyn_cast<CallExpr>(E)) {7510Expr *Callee = Call->getCallee()->IgnoreParens();7511QualType T = Callee->getType();75127513if (T == Context.BoundMemberTy) {7514// Handle pointer-to-members.7515if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))7516T = BinOp->getRHS()->getType();7517else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))7518T = Mem->getMemberDecl()->getType();7519}75207521if (const PointerType *Ptr = T->getAs<PointerType>())7522T = Ptr->getPointeeType();7523else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())7524T = Ptr->getPointeeType();7525else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())7526T = MemPtr->getPointeeType();75277528auto *FTy = T->castAs<FunctionType>();7529ReturnsRetained = FTy->getExtInfo().getProducesResult();75307531// ActOnStmtExpr arranges things so that StmtExprs of retainable7532// type always produce a +1 object.7533} else if (isa<StmtExpr>(E)) {7534ReturnsRetained = true;75357536// We hit this case with the lambda conversion-to-block optimization;7537// we don't want any extra casts here.7538} else if (isa<CastExpr>(E) &&7539isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {7540return E;75417542// For message sends and property references, we try to find an7543// actual method. FIXME: we should infer retention by selector in7544// cases where we don't have an actual method.7545} else {7546ObjCMethodDecl *D = nullptr;7547if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {7548D = Send->getMethodDecl();7549} else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {7550D = BoxedExpr->getBoxingMethod();7551} else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {7552// Don't do reclaims if we're using the zero-element array7553// constant.7554if (ArrayLit->getNumElements() == 0 &&7555Context.getLangOpts().ObjCRuntime.hasEmptyCollections())7556return E;75577558D = ArrayLit->getArrayWithObjectsMethod();7559} else if (ObjCDictionaryLiteral *DictLit7560= dyn_cast<ObjCDictionaryLiteral>(E)) {7561// Don't do reclaims if we're using the zero-element dictionary7562// constant.7563if (DictLit->getNumElements() == 0 &&7564Context.getLangOpts().ObjCRuntime.hasEmptyCollections())7565return E;75667567D = DictLit->getDictWithObjectsMethod();7568}75697570ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());75717572// Don't do reclaims on performSelector calls; despite their7573// return type, the invoked method doesn't necessarily actually7574// return an object.7575if (!ReturnsRetained &&7576D && D->getMethodFamily() == OMF_performSelector)7577return E;7578}75797580// Don't reclaim an object of Class type.7581if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())7582return E;75837584Cleanup.setExprNeedsCleanups(true);75857586CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject7587: CK_ARCReclaimReturnedObject);7588return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,7589VK_PRValue, FPOptionsOverride());7590}75917592if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)7593Cleanup.setExprNeedsCleanups(true);75947595if (!getLangOpts().CPlusPlus)7596return E;75977598// Search for the base element type (cf. ASTContext::getBaseElementType) with7599// a fast path for the common case that the type is directly a RecordType.7600const Type *T = Context.getCanonicalType(E->getType().getTypePtr());7601const RecordType *RT = nullptr;7602while (!RT) {7603switch (T->getTypeClass()) {7604case Type::Record:7605RT = cast<RecordType>(T);7606break;7607case Type::ConstantArray:7608case Type::IncompleteArray:7609case Type::VariableArray:7610case Type::DependentSizedArray:7611T = cast<ArrayType>(T)->getElementType().getTypePtr();7612break;7613default:7614return E;7615}7616}76177618// That should be enough to guarantee that this type is complete, if we're7619// not processing a decltype expression.7620CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());7621if (RD->isInvalidDecl() || RD->isDependentContext())7622return E;76237624bool IsDecltype = ExprEvalContexts.back().ExprContext ==7625ExpressionEvaluationContextRecord::EK_Decltype;7626CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);76277628if (Destructor) {7629MarkFunctionReferenced(E->getExprLoc(), Destructor);7630CheckDestructorAccess(E->getExprLoc(), Destructor,7631PDiag(diag::err_access_dtor_temp)7632<< E->getType());7633if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))7634return ExprError();76357636// If destructor is trivial, we can avoid the extra copy.7637if (Destructor->isTrivial())7638return E;76397640// We need a cleanup, but we don't need to remember the temporary.7641Cleanup.setExprNeedsCleanups(true);7642}76437644CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);7645CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);76467647if (IsDecltype)7648ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);76497650return Bind;7651}76527653ExprResult7654Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {7655if (SubExpr.isInvalid())7656return ExprError();76577658return MaybeCreateExprWithCleanups(SubExpr.get());7659}76607661Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {7662assert(SubExpr && "subexpression can't be null!");76637664CleanupVarDeclMarking();76657666unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;7667assert(ExprCleanupObjects.size() >= FirstCleanup);7668assert(Cleanup.exprNeedsCleanups() ||7669ExprCleanupObjects.size() == FirstCleanup);7670if (!Cleanup.exprNeedsCleanups())7671return SubExpr;76727673auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,7674ExprCleanupObjects.size() - FirstCleanup);76757676auto *E = ExprWithCleanups::Create(7677Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);7678DiscardCleanupsInEvaluationContext();76797680return E;7681}76827683Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {7684assert(SubStmt && "sub-statement can't be null!");76857686CleanupVarDeclMarking();76877688if (!Cleanup.exprNeedsCleanups())7689return SubStmt;76907691// FIXME: In order to attach the temporaries, wrap the statement into7692// a StmtExpr; currently this is only used for asm statements.7693// This is hacky, either create a new CXXStmtWithTemporaries statement or7694// a new AsmStmtWithTemporaries.7695CompoundStmt *CompStmt =7696CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(),7697SourceLocation(), SourceLocation());7698Expr *E = new (Context)7699StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),7700/*FIXME TemplateDepth=*/0);7701return MaybeCreateExprWithCleanups(E);7702}77037704ExprResult Sema::ActOnDecltypeExpression(Expr *E) {7705assert(ExprEvalContexts.back().ExprContext ==7706ExpressionEvaluationContextRecord::EK_Decltype &&7707"not in a decltype expression");77087709ExprResult Result = CheckPlaceholderExpr(E);7710if (Result.isInvalid())7711return ExprError();7712E = Result.get();77137714// C++11 [expr.call]p11:7715// If a function call is a prvalue of object type,7716// -- if the function call is either7717// -- the operand of a decltype-specifier, or7718// -- the right operand of a comma operator that is the operand of a7719// decltype-specifier,7720// a temporary object is not introduced for the prvalue.77217722// Recursively rebuild ParenExprs and comma expressions to strip out the7723// outermost CXXBindTemporaryExpr, if any.7724if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {7725ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());7726if (SubExpr.isInvalid())7727return ExprError();7728if (SubExpr.get() == PE->getSubExpr())7729return E;7730return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());7731}7732if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {7733if (BO->getOpcode() == BO_Comma) {7734ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());7735if (RHS.isInvalid())7736return ExprError();7737if (RHS.get() == BO->getRHS())7738return E;7739return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,7740BO->getType(), BO->getValueKind(),7741BO->getObjectKind(), BO->getOperatorLoc(),7742BO->getFPFeatures());7743}7744}77457746CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);7747CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())7748: nullptr;7749if (TopCall)7750E = TopCall;7751else7752TopBind = nullptr;77537754// Disable the special decltype handling now.7755ExprEvalContexts.back().ExprContext =7756ExpressionEvaluationContextRecord::EK_Other;77577758Result = CheckUnevaluatedOperand(E);7759if (Result.isInvalid())7760return ExprError();7761E = Result.get();77627763// In MS mode, don't perform any extra checking of call return types within a7764// decltype expression.7765if (getLangOpts().MSVCCompat)7766return E;77677768// Perform the semantic checks we delayed until this point.7769for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();7770I != N; ++I) {7771CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];7772if (Call == TopCall)7773continue;77747775if (CheckCallReturnType(Call->getCallReturnType(Context),7776Call->getBeginLoc(), Call, Call->getDirectCallee()))7777return ExprError();7778}77797780// Now all relevant types are complete, check the destructors are accessible7781// and non-deleted, and annotate them on the temporaries.7782for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();7783I != N; ++I) {7784CXXBindTemporaryExpr *Bind =7785ExprEvalContexts.back().DelayedDecltypeBinds[I];7786if (Bind == TopBind)7787continue;77887789CXXTemporary *Temp = Bind->getTemporary();77907791CXXRecordDecl *RD =7792Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();7793CXXDestructorDecl *Destructor = LookupDestructor(RD);7794Temp->setDestructor(Destructor);77957796MarkFunctionReferenced(Bind->getExprLoc(), Destructor);7797CheckDestructorAccess(Bind->getExprLoc(), Destructor,7798PDiag(diag::err_access_dtor_temp)7799<< Bind->getType());7800if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))7801return ExprError();78027803// We need a cleanup, but we don't need to remember the temporary.7804Cleanup.setExprNeedsCleanups(true);7805}78067807// Possibly strip off the top CXXBindTemporaryExpr.7808return E;7809}78107811/// Note a set of 'operator->' functions that were used for a member access.7812static void noteOperatorArrows(Sema &S,7813ArrayRef<FunctionDecl *> OperatorArrows) {7814unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;7815// FIXME: Make this configurable?7816unsigned Limit = 9;7817if (OperatorArrows.size() > Limit) {7818// Produce Limit-1 normal notes and one 'skipping' note.7819SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;7820SkipCount = OperatorArrows.size() - (Limit - 1);7821}78227823for (unsigned I = 0; I < OperatorArrows.size(); /**/) {7824if (I == SkipStart) {7825S.Diag(OperatorArrows[I]->getLocation(),7826diag::note_operator_arrows_suppressed)7827<< SkipCount;7828I += SkipCount;7829} else {7830S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)7831<< OperatorArrows[I]->getCallResultType();7832++I;7833}7834}7835}78367837ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,7838SourceLocation OpLoc,7839tok::TokenKind OpKind,7840ParsedType &ObjectType,7841bool &MayBePseudoDestructor) {7842// Since this might be a postfix expression, get rid of ParenListExprs.7843ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);7844if (Result.isInvalid()) return ExprError();7845Base = Result.get();78467847Result = CheckPlaceholderExpr(Base);7848if (Result.isInvalid()) return ExprError();7849Base = Result.get();78507851QualType BaseType = Base->getType();7852MayBePseudoDestructor = false;7853if (BaseType->isDependentType()) {7854// If we have a pointer to a dependent type and are using the -> operator,7855// the object type is the type that the pointer points to. We might still7856// have enough information about that type to do something useful.7857if (OpKind == tok::arrow)7858if (const PointerType *Ptr = BaseType->getAs<PointerType>())7859BaseType = Ptr->getPointeeType();78607861ObjectType = ParsedType::make(BaseType);7862MayBePseudoDestructor = true;7863return Base;7864}78657866// C++ [over.match.oper]p8:7867// [...] When operator->returns, the operator-> is applied to the value7868// returned, with the original second operand.7869if (OpKind == tok::arrow) {7870QualType StartingType = BaseType;7871bool NoArrowOperatorFound = false;7872bool FirstIteration = true;7873FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);7874// The set of types we've considered so far.7875llvm::SmallPtrSet<CanQualType,8> CTypes;7876SmallVector<FunctionDecl*, 8> OperatorArrows;7877CTypes.insert(Context.getCanonicalType(BaseType));78787879while (BaseType->isRecordType()) {7880if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {7881Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)7882<< StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();7883noteOperatorArrows(*this, OperatorArrows);7884Diag(OpLoc, diag::note_operator_arrow_depth)7885<< getLangOpts().ArrowDepth;7886return ExprError();7887}78887889Result = BuildOverloadedArrowExpr(7890S, Base, OpLoc,7891// When in a template specialization and on the first loop iteration,7892// potentially give the default diagnostic (with the fixit in a7893// separate note) instead of having the error reported back to here7894// and giving a diagnostic with a fixit attached to the error itself.7895(FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())7896? nullptr7897: &NoArrowOperatorFound);7898if (Result.isInvalid()) {7899if (NoArrowOperatorFound) {7900if (FirstIteration) {7901Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)7902<< BaseType << 1 << Base->getSourceRange()7903<< FixItHint::CreateReplacement(OpLoc, ".");7904OpKind = tok::period;7905break;7906}7907Diag(OpLoc, diag::err_typecheck_member_reference_arrow)7908<< BaseType << Base->getSourceRange();7909CallExpr *CE = dyn_cast<CallExpr>(Base);7910if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {7911Diag(CD->getBeginLoc(),7912diag::note_member_reference_arrow_from_operator_arrow);7913}7914}7915return ExprError();7916}7917Base = Result.get();7918if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))7919OperatorArrows.push_back(OpCall->getDirectCallee());7920BaseType = Base->getType();7921CanQualType CBaseType = Context.getCanonicalType(BaseType);7922if (!CTypes.insert(CBaseType).second) {7923Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;7924noteOperatorArrows(*this, OperatorArrows);7925return ExprError();7926}7927FirstIteration = false;7928}79297930if (OpKind == tok::arrow) {7931if (BaseType->isPointerType())7932BaseType = BaseType->getPointeeType();7933else if (auto *AT = Context.getAsArrayType(BaseType))7934BaseType = AT->getElementType();7935}7936}79377938// Objective-C properties allow "." access on Objective-C pointer types,7939// so adjust the base type to the object type itself.7940if (BaseType->isObjCObjectPointerType())7941BaseType = BaseType->getPointeeType();79427943// C++ [basic.lookup.classref]p2:7944// [...] If the type of the object expression is of pointer to scalar7945// type, the unqualified-id is looked up in the context of the complete7946// postfix-expression.7947//7948// This also indicates that we could be parsing a pseudo-destructor-name.7949// Note that Objective-C class and object types can be pseudo-destructor7950// expressions or normal member (ivar or property) access expressions, and7951// it's legal for the type to be incomplete if this is a pseudo-destructor7952// call. We'll do more incomplete-type checks later in the lookup process,7953// so just skip this check for ObjC types.7954if (!BaseType->isRecordType()) {7955ObjectType = ParsedType::make(BaseType);7956MayBePseudoDestructor = true;7957return Base;7958}79597960// The object type must be complete (or dependent), or7961// C++11 [expr.prim.general]p3:7962// Unlike the object expression in other contexts, *this is not required to7963// be of complete type for purposes of class member access (5.2.5) outside7964// the member function body.7965if (!BaseType->isDependentType() &&7966!isThisOutsideMemberFunctionBody(BaseType) &&7967RequireCompleteType(OpLoc, BaseType,7968diag::err_incomplete_member_access)) {7969return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});7970}79717972// C++ [basic.lookup.classref]p2:7973// If the id-expression in a class member access (5.2.5) is an7974// unqualified-id, and the type of the object expression is of a class7975// type C (or of pointer to a class type C), the unqualified-id is looked7976// up in the scope of class C. [...]7977ObjectType = ParsedType::make(BaseType);7978return Base;7979}79807981static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,7982tok::TokenKind &OpKind, SourceLocation OpLoc) {7983if (Base->hasPlaceholderType()) {7984ExprResult result = S.CheckPlaceholderExpr(Base);7985if (result.isInvalid()) return true;7986Base = result.get();7987}7988ObjectType = Base->getType();79897990// C++ [expr.pseudo]p2:7991// The left-hand side of the dot operator shall be of scalar type. The7992// left-hand side of the arrow operator shall be of pointer to scalar type.7993// This scalar type is the object type.7994// Note that this is rather different from the normal handling for the7995// arrow operator.7996if (OpKind == tok::arrow) {7997// The operator requires a prvalue, so perform lvalue conversions.7998// Only do this if we might plausibly end with a pointer, as otherwise7999// this was likely to be intended to be a '.'.8000if (ObjectType->isPointerType() || ObjectType->isArrayType() ||8001ObjectType->isFunctionType()) {8002ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);8003if (BaseResult.isInvalid())8004return true;8005Base = BaseResult.get();8006ObjectType = Base->getType();8007}80088009if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {8010ObjectType = Ptr->getPointeeType();8011} else if (!Base->isTypeDependent()) {8012// The user wrote "p->" when they probably meant "p."; fix it.8013S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)8014<< ObjectType << true8015<< FixItHint::CreateReplacement(OpLoc, ".");8016if (S.isSFINAEContext())8017return true;80188019OpKind = tok::period;8020}8021}80228023return false;8024}80258026/// Check if it's ok to try and recover dot pseudo destructor calls on8027/// pointer objects.8028static bool8029canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,8030QualType DestructedType) {8031// If this is a record type, check if its destructor is callable.8032if (auto *RD = DestructedType->getAsCXXRecordDecl()) {8033if (RD->hasDefinition())8034if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))8035return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);8036return false;8037}80388039// Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.8040return DestructedType->isDependentType() || DestructedType->isScalarType() ||8041DestructedType->isVectorType();8042}80438044ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,8045SourceLocation OpLoc,8046tok::TokenKind OpKind,8047const CXXScopeSpec &SS,8048TypeSourceInfo *ScopeTypeInfo,8049SourceLocation CCLoc,8050SourceLocation TildeLoc,8051PseudoDestructorTypeStorage Destructed) {8052TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();80538054QualType ObjectType;8055if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))8056return ExprError();80578058if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&8059!ObjectType->isVectorType()) {8060if (getLangOpts().MSVCCompat && ObjectType->isVoidType())8061Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();8062else {8063Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)8064<< ObjectType << Base->getSourceRange();8065return ExprError();8066}8067}80688069// C++ [expr.pseudo]p2:8070// [...] The cv-unqualified versions of the object type and of the type8071// designated by the pseudo-destructor-name shall be the same type.8072if (DestructedTypeInfo) {8073QualType DestructedType = DestructedTypeInfo->getType();8074SourceLocation DestructedTypeStart =8075DestructedTypeInfo->getTypeLoc().getBeginLoc();8076if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {8077if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {8078// Detect dot pseudo destructor calls on pointer objects, e.g.:8079// Foo *foo;8080// foo.~Foo();8081if (OpKind == tok::period && ObjectType->isPointerType() &&8082Context.hasSameUnqualifiedType(DestructedType,8083ObjectType->getPointeeType())) {8084auto Diagnostic =8085Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)8086<< ObjectType << /*IsArrow=*/0 << Base->getSourceRange();80878088// Issue a fixit only when the destructor is valid.8089if (canRecoverDotPseudoDestructorCallsOnPointerObjects(8090*this, DestructedType))8091Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");80928093// Recover by setting the object type to the destructed type and the8094// operator to '->'.8095ObjectType = DestructedType;8096OpKind = tok::arrow;8097} else {8098Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)8099<< ObjectType << DestructedType << Base->getSourceRange()8100<< DestructedTypeInfo->getTypeLoc().getSourceRange();81018102// Recover by setting the destructed type to the object type.8103DestructedType = ObjectType;8104DestructedTypeInfo =8105Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);8106Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);8107}8108} else if (DestructedType.getObjCLifetime() !=8109ObjectType.getObjCLifetime()) {81108111if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {8112// Okay: just pretend that the user provided the correctly-qualified8113// type.8114} else {8115Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)8116<< ObjectType << DestructedType << Base->getSourceRange()8117<< DestructedTypeInfo->getTypeLoc().getSourceRange();8118}81198120// Recover by setting the destructed type to the object type.8121DestructedType = ObjectType;8122DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,8123DestructedTypeStart);8124Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);8125}8126}8127}81288129// C++ [expr.pseudo]p2:8130// [...] Furthermore, the two type-names in a pseudo-destructor-name of the8131// form8132//8133// ::[opt] nested-name-specifier[opt] type-name :: ~ type-name8134//8135// shall designate the same scalar type.8136if (ScopeTypeInfo) {8137QualType ScopeType = ScopeTypeInfo->getType();8138if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&8139!Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {81408141Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),8142diag::err_pseudo_dtor_type_mismatch)8143<< ObjectType << ScopeType << Base->getSourceRange()8144<< ScopeTypeInfo->getTypeLoc().getSourceRange();81458146ScopeType = QualType();8147ScopeTypeInfo = nullptr;8148}8149}81508151Expr *Result8152= new (Context) CXXPseudoDestructorExpr(Context, Base,8153OpKind == tok::arrow, OpLoc,8154SS.getWithLocInContext(Context),8155ScopeTypeInfo,8156CCLoc,8157TildeLoc,8158Destructed);81598160return Result;8161}81628163ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,8164SourceLocation OpLoc,8165tok::TokenKind OpKind,8166CXXScopeSpec &SS,8167UnqualifiedId &FirstTypeName,8168SourceLocation CCLoc,8169SourceLocation TildeLoc,8170UnqualifiedId &SecondTypeName) {8171assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||8172FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&8173"Invalid first type name in pseudo-destructor");8174assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||8175SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&8176"Invalid second type name in pseudo-destructor");81778178QualType ObjectType;8179if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))8180return ExprError();81818182// Compute the object type that we should use for name lookup purposes. Only8183// record types and dependent types matter.8184ParsedType ObjectTypePtrForLookup;8185if (!SS.isSet()) {8186if (ObjectType->isRecordType())8187ObjectTypePtrForLookup = ParsedType::make(ObjectType);8188else if (ObjectType->isDependentType())8189ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);8190}81918192// Convert the name of the type being destructed (following the ~) into a8193// type (with source-location information).8194QualType DestructedType;8195TypeSourceInfo *DestructedTypeInfo = nullptr;8196PseudoDestructorTypeStorage Destructed;8197if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {8198ParsedType T = getTypeName(*SecondTypeName.Identifier,8199SecondTypeName.StartLocation,8200S, &SS, true, false, ObjectTypePtrForLookup,8201/*IsCtorOrDtorName*/true);8202if (!T &&8203((SS.isSet() && !computeDeclContext(SS, false)) ||8204(!SS.isSet() && ObjectType->isDependentType()))) {8205// The name of the type being destroyed is a dependent name, and we8206// couldn't find anything useful in scope. Just store the identifier and8207// it's location, and we'll perform (qualified) name lookup again at8208// template instantiation time.8209Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,8210SecondTypeName.StartLocation);8211} else if (!T) {8212Diag(SecondTypeName.StartLocation,8213diag::err_pseudo_dtor_destructor_non_type)8214<< SecondTypeName.Identifier << ObjectType;8215if (isSFINAEContext())8216return ExprError();82178218// Recover by assuming we had the right type all along.8219DestructedType = ObjectType;8220} else8221DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);8222} else {8223// Resolve the template-id to a type.8224TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;8225ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),8226TemplateId->NumArgs);8227TypeResult T = ActOnTemplateIdType(S,8228SS,8229TemplateId->TemplateKWLoc,8230TemplateId->Template,8231TemplateId->Name,8232TemplateId->TemplateNameLoc,8233TemplateId->LAngleLoc,8234TemplateArgsPtr,8235TemplateId->RAngleLoc,8236/*IsCtorOrDtorName*/true);8237if (T.isInvalid() || !T.get()) {8238// Recover by assuming we had the right type all along.8239DestructedType = ObjectType;8240} else8241DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);8242}82438244// If we've performed some kind of recovery, (re-)build the type source8245// information.8246if (!DestructedType.isNull()) {8247if (!DestructedTypeInfo)8248DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,8249SecondTypeName.StartLocation);8250Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);8251}82528253// Convert the name of the scope type (the type prior to '::') into a type.8254TypeSourceInfo *ScopeTypeInfo = nullptr;8255QualType ScopeType;8256if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||8257FirstTypeName.Identifier) {8258if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {8259ParsedType T = getTypeName(*FirstTypeName.Identifier,8260FirstTypeName.StartLocation,8261S, &SS, true, false, ObjectTypePtrForLookup,8262/*IsCtorOrDtorName*/true);8263if (!T) {8264Diag(FirstTypeName.StartLocation,8265diag::err_pseudo_dtor_destructor_non_type)8266<< FirstTypeName.Identifier << ObjectType;82678268if (isSFINAEContext())8269return ExprError();82708271// Just drop this type. It's unnecessary anyway.8272ScopeType = QualType();8273} else8274ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);8275} else {8276// Resolve the template-id to a type.8277TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;8278ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),8279TemplateId->NumArgs);8280TypeResult T = ActOnTemplateIdType(S,8281SS,8282TemplateId->TemplateKWLoc,8283TemplateId->Template,8284TemplateId->Name,8285TemplateId->TemplateNameLoc,8286TemplateId->LAngleLoc,8287TemplateArgsPtr,8288TemplateId->RAngleLoc,8289/*IsCtorOrDtorName*/true);8290if (T.isInvalid() || !T.get()) {8291// Recover by dropping this type.8292ScopeType = QualType();8293} else8294ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);8295}8296}82978298if (!ScopeType.isNull() && !ScopeTypeInfo)8299ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,8300FirstTypeName.StartLocation);830183028303return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,8304ScopeTypeInfo, CCLoc, TildeLoc,8305Destructed);8306}83078308ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,8309SourceLocation OpLoc,8310tok::TokenKind OpKind,8311SourceLocation TildeLoc,8312const DeclSpec& DS) {8313QualType ObjectType;8314QualType T;8315TypeLocBuilder TLB;8316if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))8317return ExprError();83188319switch (DS.getTypeSpecType()) {8320case DeclSpec::TST_decltype_auto: {8321Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);8322return true;8323}8324case DeclSpec::TST_decltype: {8325T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);8326DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);8327DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());8328DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());8329break;8330}8331case DeclSpec::TST_typename_pack_indexing: {8332T = ActOnPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(),8333DS.getBeginLoc(), DS.getEllipsisLoc());8334TLB.pushTrivial(getASTContext(),8335cast<PackIndexingType>(T.getTypePtr())->getPattern(),8336DS.getBeginLoc());8337PackIndexingTypeLoc PITL = TLB.push<PackIndexingTypeLoc>(T);8338PITL.setEllipsisLoc(DS.getEllipsisLoc());8339break;8340}8341default:8342llvm_unreachable("Unsupported type in pseudo destructor");8343}8344TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);8345PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);83468347return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),8348nullptr, SourceLocation(), TildeLoc,8349Destructed);8350}83518352ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,8353SourceLocation RParen) {8354// If the operand is an unresolved lookup expression, the expression is ill-8355// formed per [over.over]p1, because overloaded function names cannot be used8356// without arguments except in explicit contexts.8357ExprResult R = CheckPlaceholderExpr(Operand);8358if (R.isInvalid())8359return R;83608361R = CheckUnevaluatedOperand(R.get());8362if (R.isInvalid())8363return ExprError();83648365Operand = R.get();83668367if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&8368Operand->HasSideEffects(Context, false)) {8369// The expression operand for noexcept is in an unevaluated expression8370// context, so side effects could result in unintended consequences.8371Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);8372}83738374CanThrowResult CanThrow = canThrow(Operand);8375return new (Context)8376CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);8377}83788379ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,8380Expr *Operand, SourceLocation RParen) {8381return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);8382}83838384static void MaybeDecrementCount(8385Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {8386DeclRefExpr *LHS = nullptr;8387bool IsCompoundAssign = false;8388bool isIncrementDecrementUnaryOp = false;8389if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {8390if (BO->getLHS()->getType()->isDependentType() ||8391BO->getRHS()->getType()->isDependentType()) {8392if (BO->getOpcode() != BO_Assign)8393return;8394} else if (!BO->isAssignmentOp())8395return;8396else8397IsCompoundAssign = BO->isCompoundAssignmentOp();8398LHS = dyn_cast<DeclRefExpr>(BO->getLHS());8399} else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {8400if (COCE->getOperator() != OO_Equal)8401return;8402LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));8403} else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {8404if (!UO->isIncrementDecrementOp())8405return;8406isIncrementDecrementUnaryOp = true;8407LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());8408}8409if (!LHS)8410return;8411VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());8412if (!VD)8413return;8414// Don't decrement RefsMinusAssignments if volatile variable with compound8415// assignment (+=, ...) or increment/decrement unary operator to avoid8416// potential unused-but-set-variable warning.8417if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&8418VD->getType().isVolatileQualified())8419return;8420auto iter = RefsMinusAssignments.find(VD);8421if (iter == RefsMinusAssignments.end())8422return;8423iter->getSecond()--;8424}84258426/// Perform the conversions required for an expression used in a8427/// context that ignores the result.8428ExprResult Sema::IgnoredValueConversions(Expr *E) {8429MaybeDecrementCount(E, RefsMinusAssignments);84308431if (E->hasPlaceholderType()) {8432ExprResult result = CheckPlaceholderExpr(E);8433if (result.isInvalid()) return E;8434E = result.get();8435}84368437if (getLangOpts().CPlusPlus) {8438// The C++11 standard defines the notion of a discarded-value expression;8439// normally, we don't need to do anything to handle it, but if it is a8440// volatile lvalue with a special form, we perform an lvalue-to-rvalue8441// conversion.8442if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {8443ExprResult Res = DefaultLvalueConversion(E);8444if (Res.isInvalid())8445return E;8446E = Res.get();8447} else {8448// Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if8449// it occurs as a discarded-value expression.8450CheckUnusedVolatileAssignment(E);8451}84528453// C++1z:8454// If the expression is a prvalue after this optional conversion, the8455// temporary materialization conversion is applied.8456//8457// We do not materialize temporaries by default in order to avoid creating8458// unnecessary temporary objects. If we skip this step, IR generation is8459// able to synthesize the storage for itself in the aggregate case, and8460// adding the extra node to the AST is just clutter.8461if (isInLifetimeExtendingContext() && getLangOpts().CPlusPlus17 &&8462E->isPRValue() && !E->getType()->isVoidType()) {8463ExprResult Res = TemporaryMaterializationConversion(E);8464if (Res.isInvalid())8465return E;8466E = Res.get();8467}8468return E;8469}84708471// C99 6.3.2.1:8472// [Except in specific positions,] an lvalue that does not have8473// array type is converted to the value stored in the8474// designated object (and is no longer an lvalue).8475if (E->isPRValue()) {8476// In C, function designators (i.e. expressions of function type)8477// are r-values, but we still want to do function-to-pointer decay8478// on them. This is both technically correct and convenient for8479// some clients.8480if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())8481return DefaultFunctionArrayConversion(E);84828483return E;8484}84858486// GCC seems to also exclude expressions of incomplete enum type.8487if (const EnumType *T = E->getType()->getAs<EnumType>()) {8488if (!T->getDecl()->isComplete()) {8489// FIXME: stupid workaround for a codegen bug!8490E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();8491return E;8492}8493}84948495ExprResult Res = DefaultFunctionArrayLvalueConversion(E);8496if (Res.isInvalid())8497return E;8498E = Res.get();84998500if (!E->getType()->isVoidType())8501RequireCompleteType(E->getExprLoc(), E->getType(),8502diag::err_incomplete_type);8503return E;8504}85058506ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {8507// Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if8508// it occurs as an unevaluated operand.8509CheckUnusedVolatileAssignment(E);85108511return E;8512}85138514// If we can unambiguously determine whether Var can never be used8515// in a constant expression, return true.8516// - if the variable and its initializer are non-dependent, then8517// we can unambiguously check if the variable is a constant expression.8518// - if the initializer is not value dependent - we can determine whether8519// it can be used to initialize a constant expression. If Init can not8520// be used to initialize a constant expression we conclude that Var can8521// never be a constant expression.8522// - FXIME: if the initializer is dependent, we can still do some analysis and8523// identify certain cases unambiguously as non-const by using a Visitor:8524// - such as those that involve odr-use of a ParmVarDecl, involve a new8525// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...8526static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,8527ASTContext &Context) {8528if (isa<ParmVarDecl>(Var)) return true;8529const VarDecl *DefVD = nullptr;85308531// If there is no initializer - this can not be a constant expression.8532const Expr *Init = Var->getAnyInitializer(DefVD);8533if (!Init)8534return true;8535assert(DefVD);8536if (DefVD->isWeak())8537return false;85388539if (Var->getType()->isDependentType() || Init->isValueDependent()) {8540// FIXME: Teach the constant evaluator to deal with the non-dependent parts8541// of value-dependent expressions, and use it here to determine whether the8542// initializer is a potential constant expression.8543return false;8544}85458546return !Var->isUsableInConstantExpressions(Context);8547}85488549/// Check if the current lambda has any potential captures8550/// that must be captured by any of its enclosing lambdas that are ready to8551/// capture. If there is a lambda that can capture a nested8552/// potential-capture, go ahead and do so. Also, check to see if any8553/// variables are uncaptureable or do not involve an odr-use so do not8554/// need to be captured.85558556static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(8557Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {85588559assert(!S.isUnevaluatedContext());8560assert(S.CurContext->isDependentContext());8561#ifndef NDEBUG8562DeclContext *DC = S.CurContext;8563while (isa_and_nonnull<CapturedDecl>(DC))8564DC = DC->getParent();8565assert(8566CurrentLSI->CallOperator == DC &&8567"The current call operator must be synchronized with Sema's CurContext");8568#endif // NDEBUG85698570const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();85718572// All the potentially captureable variables in the current nested8573// lambda (within a generic outer lambda), must be captured by an8574// outer lambda that is enclosed within a non-dependent context.8575CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {8576// If the variable is clearly identified as non-odr-used and the full8577// expression is not instantiation dependent, only then do we not8578// need to check enclosing lambda's for speculative captures.8579// For e.g.:8580// Even though 'x' is not odr-used, it should be captured.8581// int test() {8582// const int x = 10;8583// auto L = [=](auto a) {8584// (void) +x + a;8585// };8586// }8587if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&8588!IsFullExprInstantiationDependent)8589return;85908591VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();8592if (!UnderlyingVar)8593return;85948595// If we have a capture-capable lambda for the variable, go ahead and8596// capture the variable in that lambda (and all its enclosing lambdas).8597if (const std::optional<unsigned> Index =8598getStackIndexOfNearestEnclosingCaptureCapableLambda(8599S.FunctionScopes, Var, S))8600S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);8601const bool IsVarNeverAConstantExpression =8602VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context);8603if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {8604// This full expression is not instantiation dependent or the variable8605// can not be used in a constant expression - which means8606// this variable must be odr-used here, so diagnose a8607// capture violation early, if the variable is un-captureable.8608// This is purely for diagnosing errors early. Otherwise, this8609// error would get diagnosed when the lambda becomes capture ready.8610QualType CaptureType, DeclRefType;8611SourceLocation ExprLoc = VarExpr->getExprLoc();8612if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,8613/*EllipsisLoc*/ SourceLocation(),8614/*BuildAndDiagnose*/false, CaptureType,8615DeclRefType, nullptr)) {8616// We will never be able to capture this variable, and we need8617// to be able to in any and all instantiations, so diagnose it.8618S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,8619/*EllipsisLoc*/ SourceLocation(),8620/*BuildAndDiagnose*/true, CaptureType,8621DeclRefType, nullptr);8622}8623}8624});86258626// Check if 'this' needs to be captured.8627if (CurrentLSI->hasPotentialThisCapture()) {8628// If we have a capture-capable lambda for 'this', go ahead and capture8629// 'this' in that lambda (and all its enclosing lambdas).8630if (const std::optional<unsigned> Index =8631getStackIndexOfNearestEnclosingCaptureCapableLambda(8632S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {8633const unsigned FunctionScopeIndexOfCapturableLambda = *Index;8634S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,8635/*Explicit*/ false, /*BuildAndDiagnose*/ true,8636&FunctionScopeIndexOfCapturableLambda);8637}8638}86398640// Reset all the potential captures at the end of each full-expression.8641CurrentLSI->clearPotentialCaptures();8642}86438644static ExprResult attemptRecovery(Sema &SemaRef,8645const TypoCorrectionConsumer &Consumer,8646const TypoCorrection &TC) {8647LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),8648Consumer.getLookupResult().getLookupKind());8649const CXXScopeSpec *SS = Consumer.getSS();8650CXXScopeSpec NewSS;86518652// Use an approprate CXXScopeSpec for building the expr.8653if (auto *NNS = TC.getCorrectionSpecifier())8654NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());8655else if (SS && !TC.WillReplaceSpecifier())8656NewSS = *SS;86578658if (auto *ND = TC.getFoundDecl()) {8659R.setLookupName(ND->getDeclName());8660R.addDecl(ND);8661if (ND->isCXXClassMember()) {8662// Figure out the correct naming class to add to the LookupResult.8663CXXRecordDecl *Record = nullptr;8664if (auto *NNS = TC.getCorrectionSpecifier())8665Record = NNS->getAsType()->getAsCXXRecordDecl();8666if (!Record)8667Record =8668dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());8669if (Record)8670R.setNamingClass(Record);86718672// Detect and handle the case where the decl might be an implicit8673// member.8674if (SemaRef.isPotentialImplicitMemberAccess(8675NewSS, R, Consumer.isAddressOfOperand()))8676return SemaRef.BuildPossibleImplicitMemberExpr(8677NewSS, /*TemplateKWLoc*/ SourceLocation(), R,8678/*TemplateArgs*/ nullptr, /*S*/ nullptr);8679} else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {8680return SemaRef.ObjC().LookupInObjCMethod(R, Consumer.getScope(),8681Ivar->getIdentifier());8682}8683}86848685return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,8686/*AcceptInvalidDecl*/ true);8687}86888689namespace {8690class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {8691llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;86928693public:8694explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)8695: TypoExprs(TypoExprs) {}8696bool VisitTypoExpr(TypoExpr *TE) {8697TypoExprs.insert(TE);8698return true;8699}8700};87018702class TransformTypos : public TreeTransform<TransformTypos> {8703typedef TreeTransform<TransformTypos> BaseTransform;87048705VarDecl *InitDecl; // A decl to avoid as a correction because it is in the8706// process of being initialized.8707llvm::function_ref<ExprResult(Expr *)> ExprFilter;8708llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;8709llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;8710llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;87118712/// Emit diagnostics for all of the TypoExprs encountered.8713///8714/// If the TypoExprs were successfully corrected, then the diagnostics should8715/// suggest the corrections. Otherwise the diagnostics will not suggest8716/// anything (having been passed an empty TypoCorrection).8717///8718/// If we've failed to correct due to ambiguous corrections, we need to8719/// be sure to pass empty corrections and replacements. Otherwise it's8720/// possible that the Consumer has a TypoCorrection that failed to ambiguity8721/// and we don't want to report those diagnostics.8722void EmitAllDiagnostics(bool IsAmbiguous) {8723for (TypoExpr *TE : TypoExprs) {8724auto &State = SemaRef.getTypoExprState(TE);8725if (State.DiagHandler) {8726TypoCorrection TC = IsAmbiguous8727? TypoCorrection() : State.Consumer->getCurrentCorrection();8728ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];87298730// Extract the NamedDecl from the transformed TypoExpr and add it to the8731// TypoCorrection, replacing the existing decls. This ensures the right8732// NamedDecl is used in diagnostics e.g. in the case where overload8733// resolution was used to select one from several possible decls that8734// had been stored in the TypoCorrection.8735if (auto *ND = getDeclFromExpr(8736Replacement.isInvalid() ? nullptr : Replacement.get()))8737TC.setCorrectionDecl(ND);87388739State.DiagHandler(TC);8740}8741SemaRef.clearDelayedTypo(TE);8742}8743}87448745/// Try to advance the typo correction state of the first unfinished TypoExpr.8746/// We allow advancement of the correction stream by removing it from the8747/// TransformCache which allows `TransformTypoExpr` to advance during the8748/// next transformation attempt.8749///8750/// Any substitution attempts for the previous TypoExprs (which must have been8751/// finished) will need to be retried since it's possible that they will now8752/// be invalid given the latest advancement.8753///8754/// We need to be sure that we're making progress - it's possible that the8755/// tree is so malformed that the transform never makes it to the8756/// `TransformTypoExpr`.8757///8758/// Returns true if there are any untried correction combinations.8759bool CheckAndAdvanceTypoExprCorrectionStreams() {8760for (auto *TE : TypoExprs) {8761auto &State = SemaRef.getTypoExprState(TE);8762TransformCache.erase(TE);8763if (!State.Consumer->hasMadeAnyCorrectionProgress())8764return false;8765if (!State.Consumer->finished())8766return true;8767State.Consumer->resetCorrectionStream();8768}8769return false;8770}87718772NamedDecl *getDeclFromExpr(Expr *E) {8773if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))8774E = OverloadResolution[OE];87758776if (!E)8777return nullptr;8778if (auto *DRE = dyn_cast<DeclRefExpr>(E))8779return DRE->getFoundDecl();8780if (auto *ME = dyn_cast<MemberExpr>(E))8781return ME->getFoundDecl();8782// FIXME: Add any other expr types that could be seen by the delayed typo8783// correction TreeTransform for which the corresponding TypoCorrection could8784// contain multiple decls.8785return nullptr;8786}87878788ExprResult TryTransform(Expr *E) {8789Sema::SFINAETrap Trap(SemaRef);8790ExprResult Res = TransformExpr(E);8791if (Trap.hasErrorOccurred() || Res.isInvalid())8792return ExprError();87938794return ExprFilter(Res.get());8795}87968797// Since correcting typos may intoduce new TypoExprs, this function8798// checks for new TypoExprs and recurses if it finds any. Note that it will8799// only succeed if it is able to correct all typos in the given expression.8800ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {8801if (Res.isInvalid()) {8802return Res;8803}8804// Check to see if any new TypoExprs were created. If so, we need to recurse8805// to check their validity.8806Expr *FixedExpr = Res.get();88078808auto SavedTypoExprs = std::move(TypoExprs);8809auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);8810TypoExprs.clear();8811AmbiguousTypoExprs.clear();88128813FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);8814if (!TypoExprs.empty()) {8815// Recurse to handle newly created TypoExprs. If we're not able to8816// handle them, discard these TypoExprs.8817ExprResult RecurResult =8818RecursiveTransformLoop(FixedExpr, IsAmbiguous);8819if (RecurResult.isInvalid()) {8820Res = ExprError();8821// Recursive corrections didn't work, wipe them away and don't add8822// them to the TypoExprs set. Remove them from Sema's TypoExpr list8823// since we don't want to clear them twice. Note: it's possible the8824// TypoExprs were created recursively and thus won't be in our8825// Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.8826auto &SemaTypoExprs = SemaRef.TypoExprs;8827for (auto *TE : TypoExprs) {8828TransformCache.erase(TE);8829SemaRef.clearDelayedTypo(TE);88308831auto SI = find(SemaTypoExprs, TE);8832if (SI != SemaTypoExprs.end()) {8833SemaTypoExprs.erase(SI);8834}8835}8836} else {8837// TypoExpr is valid: add newly created TypoExprs since we were8838// able to correct them.8839Res = RecurResult;8840SavedTypoExprs.set_union(TypoExprs);8841}8842}88438844TypoExprs = std::move(SavedTypoExprs);8845AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);88468847return Res;8848}88498850// Try to transform the given expression, looping through the correction8851// candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.8852//8853// If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to8854// true and this method immediately will return an `ExprError`.8855ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {8856ExprResult Res;8857auto SavedTypoExprs = std::move(SemaRef.TypoExprs);8858SemaRef.TypoExprs.clear();88598860while (true) {8861Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);88628863// Recursion encountered an ambiguous correction. This means that our8864// correction itself is ambiguous, so stop now.8865if (IsAmbiguous)8866break;88678868// If the transform is still valid after checking for any new typos,8869// it's good to go.8870if (!Res.isInvalid())8871break;88728873// The transform was invalid, see if we have any TypoExprs with untried8874// correction candidates.8875if (!CheckAndAdvanceTypoExprCorrectionStreams())8876break;8877}88788879// If we found a valid result, double check to make sure it's not ambiguous.8880if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {8881auto SavedTransformCache =8882llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);88838884// Ensure none of the TypoExprs have multiple typo correction candidates8885// with the same edit length that pass all the checks and filters.8886while (!AmbiguousTypoExprs.empty()) {8887auto TE = AmbiguousTypoExprs.back();88888889// TryTransform itself can create new Typos, adding them to the TypoExpr map8890// and invalidating our TypoExprState, so always fetch it instead of storing.8891SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();88928893TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();8894TypoCorrection Next;8895do {8896// Fetch the next correction by erasing the typo from the cache and calling8897// `TryTransform` which will iterate through corrections in8898// `TransformTypoExpr`.8899TransformCache.erase(TE);8900ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);89018902if (!AmbigRes.isInvalid() || IsAmbiguous) {8903SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();8904SavedTransformCache.erase(TE);8905Res = ExprError();8906IsAmbiguous = true;8907break;8908}8909} while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&8910Next.getEditDistance(false) == TC.getEditDistance(false));89118912if (IsAmbiguous)8913break;89148915AmbiguousTypoExprs.remove(TE);8916SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();8917TransformCache[TE] = SavedTransformCache[TE];8918}8919TransformCache = std::move(SavedTransformCache);8920}89218922// Wipe away any newly created TypoExprs that we don't know about. Since we8923// clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only8924// possible if a `TypoExpr` is created during a transformation but then8925// fails before we can discover it.8926auto &SemaTypoExprs = SemaRef.TypoExprs;8927for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {8928auto TE = *Iterator;8929auto FI = find(TypoExprs, TE);8930if (FI != TypoExprs.end()) {8931Iterator++;8932continue;8933}8934SemaRef.clearDelayedTypo(TE);8935Iterator = SemaTypoExprs.erase(Iterator);8936}8937SemaRef.TypoExprs = std::move(SavedTypoExprs);89388939return Res;8940}89418942public:8943TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)8944: BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}89458946ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,8947MultiExprArg Args,8948SourceLocation RParenLoc,8949Expr *ExecConfig = nullptr) {8950auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,8951RParenLoc, ExecConfig);8952if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {8953if (Result.isUsable()) {8954Expr *ResultCall = Result.get();8955if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))8956ResultCall = BE->getSubExpr();8957if (auto *CE = dyn_cast<CallExpr>(ResultCall))8958OverloadResolution[OE] = CE->getCallee();8959}8960}8961return Result;8962}89638964ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }89658966ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }89678968ExprResult Transform(Expr *E) {8969bool IsAmbiguous = false;8970ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);89718972if (!Res.isUsable())8973FindTypoExprs(TypoExprs).TraverseStmt(E);89748975EmitAllDiagnostics(IsAmbiguous);89768977return Res;8978}89798980ExprResult TransformTypoExpr(TypoExpr *E) {8981// If the TypoExpr hasn't been seen before, record it. Otherwise, return the8982// cached transformation result if there is one and the TypoExpr isn't the8983// first one that was encountered.8984auto &CacheEntry = TransformCache[E];8985if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {8986return CacheEntry;8987}89888989auto &State = SemaRef.getTypoExprState(E);8990assert(State.Consumer && "Cannot transform a cleared TypoExpr");89918992// For the first TypoExpr and an uncached TypoExpr, find the next likely8993// typo correction and return it.8994while (TypoCorrection TC = State.Consumer->getNextCorrection()) {8995if (InitDecl && TC.getFoundDecl() == InitDecl)8996continue;8997// FIXME: If we would typo-correct to an invalid declaration, it's8998// probably best to just suppress all errors from this typo correction.8999ExprResult NE = State.RecoveryHandler ?9000State.RecoveryHandler(SemaRef, E, TC) :9001attemptRecovery(SemaRef, *State.Consumer, TC);9002if (!NE.isInvalid()) {9003// Check whether there may be a second viable correction with the same9004// edit distance; if so, remember this TypoExpr may have an ambiguous9005// correction so it can be more thoroughly vetted later.9006TypoCorrection Next;9007if ((Next = State.Consumer->peekNextCorrection()) &&9008Next.getEditDistance(false) == TC.getEditDistance(false)) {9009AmbiguousTypoExprs.insert(E);9010} else {9011AmbiguousTypoExprs.remove(E);9012}9013assert(!NE.isUnset() &&9014"Typo was transformed into a valid-but-null ExprResult");9015return CacheEntry = NE;9016}9017}9018return CacheEntry = ExprError();9019}9020};9021}90229023ExprResult9024Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,9025bool RecoverUncorrectedTypos,9026llvm::function_ref<ExprResult(Expr *)> Filter) {9027// If the current evaluation context indicates there are uncorrected typos9028// and the current expression isn't guaranteed to not have typos, try to9029// resolve any TypoExpr nodes that might be in the expression.9030if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&9031(E->isTypeDependent() || E->isValueDependent() ||9032E->isInstantiationDependent())) {9033auto TyposResolved = DelayedTypos.size();9034auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);9035TyposResolved -= DelayedTypos.size();9036if (Result.isInvalid() || Result.get() != E) {9037ExprEvalContexts.back().NumTypos -= TyposResolved;9038if (Result.isInvalid() && RecoverUncorrectedTypos) {9039struct TyposReplace : TreeTransform<TyposReplace> {9040TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}9041ExprResult TransformTypoExpr(clang::TypoExpr *E) {9042return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),9043E->getEndLoc(), {});9044}9045} TT(*this);9046return TT.TransformExpr(E);9047}9048return Result;9049}9050assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");9051}9052return E;9053}90549055ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,9056bool DiscardedValue, bool IsConstexpr,9057bool IsTemplateArgument) {9058ExprResult FullExpr = FE;90599060if (!FullExpr.get())9061return ExprError();90629063if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))9064return ExprError();90659066if (DiscardedValue) {9067// Top-level expressions default to 'id' when we're in a debugger.9068if (getLangOpts().DebuggerCastResultToId &&9069FullExpr.get()->getType() == Context.UnknownAnyTy) {9070FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());9071if (FullExpr.isInvalid())9072return ExprError();9073}90749075FullExpr = CheckPlaceholderExpr(FullExpr.get());9076if (FullExpr.isInvalid())9077return ExprError();90789079FullExpr = IgnoredValueConversions(FullExpr.get());9080if (FullExpr.isInvalid())9081return ExprError();90829083DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);9084}90859086FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,9087/*RecoverUncorrectedTypos=*/true);9088if (FullExpr.isInvalid())9089return ExprError();90909091CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);90929093// At the end of this full expression (which could be a deeply nested9094// lambda), if there is a potential capture within the nested lambda,9095// have the outer capture-able lambda try and capture it.9096// Consider the following code:9097// void f(int, int);9098// void f(const int&, double);9099// void foo() {9100// const int x = 10, y = 20;9101// auto L = [=](auto a) {9102// auto M = [=](auto b) {9103// f(x, b); <-- requires x to be captured by L and M9104// f(y, a); <-- requires y to be captured by L, but not all Ms9105// };9106// };9107// }91089109// FIXME: Also consider what happens for something like this that involves9110// the gnu-extension statement-expressions or even lambda-init-captures:9111// void f() {9112// const int n = 0;9113// auto L = [&](auto a) {9114// +n + ({ 0; a; });9115// };9116// }9117//9118// Here, we see +n, and then the full-expression 0; ends, so we don't9119// capture n (and instead remove it from our list of potential captures),9120// and then the full-expression +n + ({ 0; }); ends, but it's too late9121// for us to see that we need to capture n after all.91229123LambdaScopeInfo *const CurrentLSI =9124getCurLambda(/*IgnoreCapturedRegions=*/true);9125// FIXME: PR 17877 showed that getCurLambda() can return a valid pointer9126// even if CurContext is not a lambda call operator. Refer to that Bug Report9127// for an example of the code that might cause this asynchrony.9128// By ensuring we are in the context of a lambda's call operator9129// we can fix the bug (we only need to check whether we need to capture9130// if we are within a lambda's body); but per the comments in that9131// PR, a proper fix would entail :9132// "Alternative suggestion:9133// - Add to Sema an integer holding the smallest (outermost) scope9134// index that we are *lexically* within, and save/restore/set to9135// FunctionScopes.size() in InstantiatingTemplate's9136// constructor/destructor.9137// - Teach the handful of places that iterate over FunctionScopes to9138// stop at the outermost enclosing lexical scope."9139DeclContext *DC = CurContext;9140while (isa_and_nonnull<CapturedDecl>(DC))9141DC = DC->getParent();9142const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);9143if (IsInLambdaDeclContext && CurrentLSI &&9144CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())9145CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,9146*this);9147return MaybeCreateExprWithCleanups(FullExpr);9148}91499150StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {9151if (!FullStmt) return StmtError();91529153return MaybeCreateStmtWithCleanups(FullStmt);9154}91559156Sema::IfExistsResult9157Sema::CheckMicrosoftIfExistsSymbol(Scope *S,9158CXXScopeSpec &SS,9159const DeclarationNameInfo &TargetNameInfo) {9160DeclarationName TargetName = TargetNameInfo.getName();9161if (!TargetName)9162return IER_DoesNotExist;91639164// If the name itself is dependent, then the result is dependent.9165if (TargetName.isDependentName())9166return IER_Dependent;91679168// Do the redeclaration lookup in the current scope.9169LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,9170RedeclarationKind::NotForRedeclaration);9171LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());9172R.suppressDiagnostics();91739174switch (R.getResultKind()) {9175case LookupResult::Found:9176case LookupResult::FoundOverloaded:9177case LookupResult::FoundUnresolvedValue:9178case LookupResult::Ambiguous:9179return IER_Exists;91809181case LookupResult::NotFound:9182return IER_DoesNotExist;91839184case LookupResult::NotFoundInCurrentInstantiation:9185return IER_Dependent;9186}91879188llvm_unreachable("Invalid LookupResult Kind!");9189}91909191Sema::IfExistsResult9192Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,9193bool IsIfExists, CXXScopeSpec &SS,9194UnqualifiedId &Name) {9195DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);91969197// Check for an unexpanded parameter pack.9198auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;9199if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||9200DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))9201return IER_Error;92029203return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);9204}92059206concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {9207return BuildExprRequirement(E, /*IsSimple=*/true,9208/*NoexceptLoc=*/SourceLocation(),9209/*ReturnTypeRequirement=*/{});9210}92119212concepts::Requirement *Sema::ActOnTypeRequirement(9213SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,9214const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {9215assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&9216"Exactly one of TypeName and TemplateId must be specified.");9217TypeSourceInfo *TSI = nullptr;9218if (TypeName) {9219QualType T =9220CheckTypenameType(ElaboratedTypeKeyword::Typename, TypenameKWLoc,9221SS.getWithLocInContext(Context), *TypeName, NameLoc,9222&TSI, /*DeducedTSTContext=*/false);9223if (T.isNull())9224return nullptr;9225} else {9226ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),9227TemplateId->NumArgs);9228TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,9229TemplateId->TemplateKWLoc,9230TemplateId->Template, TemplateId->Name,9231TemplateId->TemplateNameLoc,9232TemplateId->LAngleLoc, ArgsPtr,9233TemplateId->RAngleLoc);9234if (T.isInvalid())9235return nullptr;9236if (GetTypeFromParser(T.get(), &TSI).isNull())9237return nullptr;9238}9239return BuildTypeRequirement(TSI);9240}92419242concepts::Requirement *9243Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {9244return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,9245/*ReturnTypeRequirement=*/{});9246}92479248concepts::Requirement *9249Sema::ActOnCompoundRequirement(9250Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,9251TemplateIdAnnotation *TypeConstraint, unsigned Depth) {9252// C++2a [expr.prim.req.compound] p1.3.39253// [..] the expression is deduced against an invented function template9254// F [...] F is a void function template with a single type template9255// parameter T declared with the constrained-parameter. Form a new9256// cv-qualifier-seq cv by taking the union of const and volatile specifiers9257// around the constrained-parameter. F has a single parameter whose9258// type-specifier is cv T followed by the abstract-declarator. [...]9259//9260// The cv part is done in the calling function - we get the concept with9261// arguments and the abstract declarator with the correct CV qualification and9262// have to synthesize T and the single parameter of F.9263auto &II = Context.Idents.get("expr-type");9264auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,9265SourceLocation(),9266SourceLocation(), Depth,9267/*Index=*/0, &II,9268/*Typename=*/true,9269/*ParameterPack=*/false,9270/*HasTypeConstraint=*/true);92719272if (BuildTypeConstraint(SS, TypeConstraint, TParam,9273/*EllipsisLoc=*/SourceLocation(),9274/*AllowUnexpandedPack=*/true))9275// Just produce a requirement with no type requirements.9276return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});92779278auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),9279SourceLocation(),9280ArrayRef<NamedDecl *>(TParam),9281SourceLocation(),9282/*RequiresClause=*/nullptr);9283return BuildExprRequirement(9284E, /*IsSimple=*/false, NoexceptLoc,9285concepts::ExprRequirement::ReturnTypeRequirement(TPL));9286}92879288concepts::ExprRequirement *9289Sema::BuildExprRequirement(9290Expr *E, bool IsSimple, SourceLocation NoexceptLoc,9291concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {9292auto Status = concepts::ExprRequirement::SS_Satisfied;9293ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;9294if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() ||9295ReturnTypeRequirement.isDependent())9296Status = concepts::ExprRequirement::SS_Dependent;9297else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)9298Status = concepts::ExprRequirement::SS_NoexceptNotMet;9299else if (ReturnTypeRequirement.isSubstitutionFailure())9300Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;9301else if (ReturnTypeRequirement.isTypeConstraint()) {9302// C++2a [expr.prim.req]p1.3.39303// The immediately-declared constraint ([temp]) of decltype((E)) shall9304// be satisfied.9305TemplateParameterList *TPL =9306ReturnTypeRequirement.getTypeConstraintTemplateParameterList();9307QualType MatchedType =9308Context.getReferenceQualifiedType(E).getCanonicalType();9309llvm::SmallVector<TemplateArgument, 1> Args;9310Args.push_back(TemplateArgument(MatchedType));93119312auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));93139314MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);9315MLTAL.addOuterRetainedLevels(TPL->getDepth());9316const TypeConstraint *TC = Param->getTypeConstraint();9317assert(TC && "Type Constraint cannot be null here");9318auto *IDC = TC->getImmediatelyDeclaredConstraint();9319assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");9320ExprResult Constraint = SubstExpr(IDC, MLTAL);9321if (Constraint.isInvalid()) {9322return new (Context) concepts::ExprRequirement(9323concepts::createSubstDiagAt(*this, IDC->getExprLoc(),9324[&](llvm::raw_ostream &OS) {9325IDC->printPretty(OS, /*Helper=*/nullptr,9326getPrintingPolicy());9327}),9328IsSimple, NoexceptLoc, ReturnTypeRequirement);9329}9330SubstitutedConstraintExpr =9331cast<ConceptSpecializationExpr>(Constraint.get());9332if (!SubstitutedConstraintExpr->isSatisfied())9333Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;9334}9335return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,9336ReturnTypeRequirement, Status,9337SubstitutedConstraintExpr);9338}93399340concepts::ExprRequirement *9341Sema::BuildExprRequirement(9342concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,9343bool IsSimple, SourceLocation NoexceptLoc,9344concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {9345return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,9346IsSimple, NoexceptLoc,9347ReturnTypeRequirement);9348}93499350concepts::TypeRequirement *9351Sema::BuildTypeRequirement(TypeSourceInfo *Type) {9352return new (Context) concepts::TypeRequirement(Type);9353}93549355concepts::TypeRequirement *9356Sema::BuildTypeRequirement(9357concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {9358return new (Context) concepts::TypeRequirement(SubstDiag);9359}93609361concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {9362return BuildNestedRequirement(Constraint);9363}93649365concepts::NestedRequirement *9366Sema::BuildNestedRequirement(Expr *Constraint) {9367ConstraintSatisfaction Satisfaction;9368if (!Constraint->isInstantiationDependent() &&9369CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},9370Constraint->getSourceRange(), Satisfaction))9371return nullptr;9372return new (Context) concepts::NestedRequirement(Context, Constraint,9373Satisfaction);9374}93759376concepts::NestedRequirement *9377Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,9378const ASTConstraintSatisfaction &Satisfaction) {9379return new (Context) concepts::NestedRequirement(9380InvalidConstraintEntity,9381ASTConstraintSatisfaction::Rebuild(Context, Satisfaction));9382}93839384RequiresExprBodyDecl *9385Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,9386ArrayRef<ParmVarDecl *> LocalParameters,9387Scope *BodyScope) {9388assert(BodyScope);93899390RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,9391RequiresKWLoc);93929393PushDeclContext(BodyScope, Body);93949395for (ParmVarDecl *Param : LocalParameters) {9396if (Param->hasDefaultArg())9397// C++2a [expr.prim.req] p49398// [...] A local parameter of a requires-expression shall not have a9399// default argument. [...]9400Diag(Param->getDefaultArgRange().getBegin(),9401diag::err_requires_expr_local_parameter_default_argument);9402// Ignore default argument and move on94039404Param->setDeclContext(Body);9405// If this has an identifier, add it to the scope stack.9406if (Param->getIdentifier()) {9407CheckShadow(BodyScope, Param);9408PushOnScopeChains(Param, BodyScope);9409}9410}9411return Body;9412}94139414void Sema::ActOnFinishRequiresExpr() {9415assert(CurContext && "DeclContext imbalance!");9416CurContext = CurContext->getLexicalParent();9417assert(CurContext && "Popped translation unit!");9418}94199420ExprResult Sema::ActOnRequiresExpr(9421SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,9422SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,9423SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,9424SourceLocation ClosingBraceLoc) {9425auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,9426LocalParameters, RParenLoc, Requirements,9427ClosingBraceLoc);9428if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))9429return ExprError();9430return RE;9431}943294339434