brintos

brintos / llvm-project-archived public Read only

0
0
Text · 260.4 KiB · 5572e0a Raw
7577 lines · cpp
1//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// Implements C++ name mangling according to the Itanium C++ ABI,10// which is used in GCC 3.2 and newer (and many compilers that are11// ABI-compatible with GCC):12//13//   http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling14//15//===----------------------------------------------------------------------===//16 17#include "clang/AST/ASTContext.h"18#include "clang/AST/Attr.h"19#include "clang/AST/Decl.h"20#include "clang/AST/DeclCXX.h"21#include "clang/AST/DeclObjC.h"22#include "clang/AST/DeclOpenMP.h"23#include "clang/AST/DeclTemplate.h"24#include "clang/AST/Expr.h"25#include "clang/AST/ExprCXX.h"26#include "clang/AST/ExprConcepts.h"27#include "clang/AST/ExprObjC.h"28#include "clang/AST/Mangle.h"29#include "clang/AST/TypeLoc.h"30#include "clang/Basic/ABI.h"31#include "clang/Basic/Module.h"32#include "clang/Basic/TargetInfo.h"33#include "clang/Basic/Thunk.h"34#include "llvm/ADT/StringExtras.h"35#include "llvm/Support/ErrorHandling.h"36#include "llvm/Support/raw_ostream.h"37#include "llvm/TargetParser/RISCVTargetParser.h"38#include <optional>39 40using namespace clang;41 42namespace {43 44static bool isLocalContainerContext(const DeclContext *DC) {45  return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);46}47 48static const FunctionDecl *getStructor(const FunctionDecl *fn) {49  if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())50    return ftd->getTemplatedDecl();51 52  return fn;53}54 55static const NamedDecl *getStructor(const NamedDecl *decl) {56  const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);57  return (fn ? getStructor(fn) : decl);58}59 60static bool isLambda(const NamedDecl *ND) {61  const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);62  if (!Record)63    return false;64 65  return Record->isLambda();66}67 68static const unsigned UnknownArity = ~0U;69 70class ItaniumMangleContextImpl : public ItaniumMangleContext {71  typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;72  llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;73  llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;74  const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;75  NamespaceDecl *StdNamespace = nullptr;76 77  bool NeedsUniqueInternalLinkageNames = false;78 79public:80  explicit ItaniumMangleContextImpl(81      ASTContext &Context, DiagnosticsEngine &Diags,82      DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)83      : ItaniumMangleContext(Context, Diags, IsAux),84        DiscriminatorOverride(DiscriminatorOverride) {}85 86  /// @name Mangler Entry Points87  /// @{88 89  bool shouldMangleCXXName(const NamedDecl *D) override;90  bool shouldMangleStringLiteral(const StringLiteral *) override {91    return false;92  }93 94  bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;95  void needsUniqueInternalLinkageNames() override {96    NeedsUniqueInternalLinkageNames = true;97  }98 99  void mangleCXXName(GlobalDecl GD, raw_ostream &) override;100  void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, bool,101                   raw_ostream &) override;102  void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,103                          const ThunkInfo &Thunk, bool, raw_ostream &) override;104  void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,105                                raw_ostream &) override;106  void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;107  void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;108  void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,109                           const CXXRecordDecl *Type, raw_ostream &) override;110  void mangleCXXRTTI(QualType T, raw_ostream &) override;111  void mangleCXXRTTIName(QualType T, raw_ostream &,112                         bool NormalizeIntegers) override;113  void mangleCanonicalTypeName(QualType T, raw_ostream &,114                               bool NormalizeIntegers) override;115 116  void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;117  void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;118  void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;119  void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;120  void mangleDynamicAtExitDestructor(const VarDecl *D,121                                     raw_ostream &Out) override;122  void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;123  void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,124                                 raw_ostream &Out) override;125  void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,126                             raw_ostream &Out) override;127  void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;128  void mangleItaniumThreadLocalWrapper(const VarDecl *D,129                                       raw_ostream &) override;130 131  void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;132 133  void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;134 135  void mangleModuleInitializer(const Module *Module, raw_ostream &) override;136 137  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {138    // Lambda closure types are already numbered.139    if (isLambda(ND))140      return false;141 142    // Anonymous tags are already numbered.143    if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {144      if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())145        return false;146    }147 148    // Use the canonical number for externally visible decls.149    if (ND->isExternallyVisible()) {150      unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());151      if (discriminator == 1)152        return false;153      disc = discriminator - 2;154      return true;155    }156 157    // Make up a reasonable number for internal decls.158    unsigned &discriminator = Uniquifier[ND];159    if (!discriminator) {160      const DeclContext *DC = getEffectiveDeclContext(ND);161      discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];162    }163    if (discriminator == 1)164      return false;165    disc = discriminator-2;166    return true;167  }168 169  std::string getLambdaString(const CXXRecordDecl *Lambda) override {170    // This function matches the one in MicrosoftMangle, which returns171    // the string that is used in lambda mangled names.172    assert(Lambda->isLambda() && "RD must be a lambda!");173    std::string Name("<lambda");174    Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();175    unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();176    unsigned LambdaId;177    const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);178    const FunctionDecl *Func =179        Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;180 181    if (Func) {182      unsigned DefaultArgNo =183          Func->getNumParams() - Parm->getFunctionScopeIndex();184      Name += llvm::utostr(DefaultArgNo);185      Name += "_";186    }187 188    if (LambdaManglingNumber)189      LambdaId = LambdaManglingNumber;190    else191      LambdaId = getAnonymousStructIdForDebugInfo(Lambda);192 193    Name += llvm::utostr(LambdaId);194    Name += '>';195    return Name;196  }197 198  DiscriminatorOverrideTy getDiscriminatorOverride() const override {199    return DiscriminatorOverride;200  }201 202  NamespaceDecl *getStdNamespace();203 204  const DeclContext *getEffectiveDeclContext(const Decl *D);205  const DeclContext *getEffectiveParentContext(const DeclContext *DC) {206    return getEffectiveDeclContext(cast<Decl>(DC));207  }208 209  bool isInternalLinkageDecl(const NamedDecl *ND);210 211  /// @}212};213 214/// Manage the mangling of a single name.215class CXXNameMangler {216  ItaniumMangleContextImpl &Context;217  raw_ostream &Out;218  /// Normalize integer types for cross-language CFI support with other219  /// languages that can't represent and encode C/C++ integer types.220  bool NormalizeIntegers = false;221 222  bool NullOut = false;223  /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.224  /// This mode is used when mangler creates another mangler recursively to225  /// calculate ABI tags for the function return value or the variable type.226  /// Also it is required to avoid infinite recursion in some cases.227  bool DisableDerivedAbiTags = false;228 229  /// The "structor" is the top-level declaration being mangled, if230  /// that's not a template specialization; otherwise it's the pattern231  /// for that specialization.232  const NamedDecl *Structor;233  unsigned StructorType = 0;234 235  // An offset to add to all template parameter depths while mangling. Used236  // when mangling a template parameter list to see if it matches a template237  // template parameter exactly.238  unsigned TemplateDepthOffset = 0;239 240  /// The next substitution sequence number.241  unsigned SeqID = 0;242 243  class FunctionTypeDepthState {244    unsigned Bits = 0;245 246    enum { InResultTypeMask = 1 };247 248  public:249    FunctionTypeDepthState() = default;250 251    /// The number of function types we're inside.252    unsigned getDepth() const {253      return Bits >> 1;254    }255 256    /// True if we're in the return type of the innermost function type.257    bool isInResultType() const {258      return Bits & InResultTypeMask;259    }260 261    FunctionTypeDepthState push() {262      FunctionTypeDepthState tmp = *this;263      Bits = (Bits & ~InResultTypeMask) + 2;264      return tmp;265    }266 267    void enterResultType() {268      Bits |= InResultTypeMask;269    }270 271    void leaveResultType() {272      Bits &= ~InResultTypeMask;273    }274 275    void pop(FunctionTypeDepthState saved) {276      assert(getDepth() == saved.getDepth() + 1);277      Bits = saved.Bits;278    }279 280  } FunctionTypeDepth;281 282  // abi_tag is a gcc attribute, taking one or more strings called "tags".283  // The goal is to annotate against which version of a library an object was284  // built and to be able to provide backwards compatibility ("dual abi").285  // For more information see docs/ItaniumMangleAbiTags.rst.286  typedef SmallVector<StringRef, 4> AbiTagList;287 288  // State to gather all implicit and explicit tags used in a mangled name.289  // Must always have an instance of this while emitting any name to keep290  // track.291  class AbiTagState final {292  public:293    explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {294      Parent = LinkHead;295      LinkHead = this;296    }297 298    // No copy, no move.299    AbiTagState(const AbiTagState &) = delete;300    AbiTagState &operator=(const AbiTagState &) = delete;301 302    ~AbiTagState() { pop(); }303 304    void write(raw_ostream &Out, const NamedDecl *ND,305               const AbiTagList *AdditionalAbiTags) {306      ND = cast<NamedDecl>(ND->getCanonicalDecl());307      if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {308        assert(309            !AdditionalAbiTags &&310            "only function and variables need a list of additional abi tags");311        if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {312          if (const auto *AbiTag = NS->getAttr<AbiTagAttr>())313            llvm::append_range(UsedAbiTags, AbiTag->tags());314          // Don't emit abi tags for namespaces.315          return;316        }317      }318 319      AbiTagList TagList;320      if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {321        llvm::append_range(UsedAbiTags, AbiTag->tags());322        llvm::append_range(TagList, AbiTag->tags());323      }324 325      if (AdditionalAbiTags) {326        llvm::append_range(UsedAbiTags, *AdditionalAbiTags);327        llvm::append_range(TagList, *AdditionalAbiTags);328      }329 330      llvm::sort(TagList);331      TagList.erase(llvm::unique(TagList), TagList.end());332 333      writeSortedUniqueAbiTags(Out, TagList);334    }335 336    const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }337    void setUsedAbiTags(const AbiTagList &AbiTags) {338      UsedAbiTags = AbiTags;339    }340 341    const AbiTagList &getEmittedAbiTags() const {342      return EmittedAbiTags;343    }344 345    const AbiTagList &getSortedUniqueUsedAbiTags() {346      llvm::sort(UsedAbiTags);347      UsedAbiTags.erase(llvm::unique(UsedAbiTags), UsedAbiTags.end());348      return UsedAbiTags;349    }350 351  private:352    //! All abi tags used implicitly or explicitly.353    AbiTagList UsedAbiTags;354    //! All explicit abi tags (i.e. not from namespace).355    AbiTagList EmittedAbiTags;356 357    AbiTagState *&LinkHead;358    AbiTagState *Parent = nullptr;359 360    void pop() {361      assert(LinkHead == this &&362             "abi tag link head must point to us on destruction");363      if (Parent) {364        Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),365                                   UsedAbiTags.begin(), UsedAbiTags.end());366        Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),367                                      EmittedAbiTags.begin(),368                                      EmittedAbiTags.end());369      }370      LinkHead = Parent;371    }372 373    void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {374      for (const auto &Tag : AbiTags) {375        EmittedAbiTags.push_back(Tag);376        Out << "B";377        Out << Tag.size();378        Out << Tag;379      }380    }381  };382 383  AbiTagState *AbiTags = nullptr;384  AbiTagState AbiTagsRoot;385 386  llvm::DenseMap<uintptr_t, unsigned> Substitutions;387  llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;388 389  ASTContext &getASTContext() const { return Context.getASTContext(); }390 391  bool isCompatibleWith(LangOptions::ClangABI Ver) {392    return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;393  }394 395  bool isStd(const NamespaceDecl *NS);396  bool isStdNamespace(const DeclContext *DC);397 398  const RecordDecl *GetLocalClassDecl(const Decl *D);399  bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);400  bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,401                               llvm::StringRef Name, bool HasAllocator);402 403public:404  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,405                 const NamedDecl *D = nullptr, bool NullOut_ = false)406      : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),407        AbiTagsRoot(AbiTags) {408    // These can't be mangled without a ctor type or dtor type.409    assert(!D || (!isa<CXXDestructorDecl>(D) &&410                  !isa<CXXConstructorDecl>(D)));411  }412  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,413                 const CXXConstructorDecl *D, CXXCtorType Type)414      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),415        AbiTagsRoot(AbiTags) {}416  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,417                 const CXXDestructorDecl *D, CXXDtorType Type)418      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),419        AbiTagsRoot(AbiTags) {}420 421  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,422                 bool NormalizeIntegers_)423      : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),424        NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}425  CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)426      : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),427        StructorType(Outer.StructorType), SeqID(Outer.SeqID),428        FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),429        Substitutions(Outer.Substitutions),430        ModuleSubstitutions(Outer.ModuleSubstitutions) {}431 432  CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)433      : CXXNameMangler(Outer, (raw_ostream &)Out_) {434    NullOut = true;435  }436 437  struct WithTemplateDepthOffset { unsigned Offset; };438  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,439                 WithTemplateDepthOffset Offset)440      : CXXNameMangler(C, Out) {441    TemplateDepthOffset = Offset.Offset;442  }443 444  raw_ostream &getStream() { return Out; }445 446  void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }447  static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);448 449  void mangle(GlobalDecl GD);450  void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);451  void mangleNumber(const llvm::APSInt &I);452  void mangleNumber(int64_t Number);453  void mangleFloat(const llvm::APFloat &F);454  void mangleFunctionEncoding(GlobalDecl GD);455  void mangleSeqID(unsigned SeqID);456  void mangleName(GlobalDecl GD);457  void mangleType(QualType T);458  void mangleCXXRecordDecl(const CXXRecordDecl *Record,459                           bool SuppressSubstitution = false);460  void mangleLambdaSig(const CXXRecordDecl *Lambda);461  void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);462  void mangleVendorQualifier(StringRef Name);463  void mangleVendorType(StringRef Name);464 465private:466  bool mangleSubstitution(const NamedDecl *ND);467  bool mangleSubstitution(QualType T);468  bool mangleSubstitution(TemplateName Template);469  bool mangleSubstitution(uintptr_t Ptr);470 471  void mangleExistingSubstitution(TemplateName name);472 473  bool mangleStandardSubstitution(const NamedDecl *ND);474 475  void addSubstitution(const NamedDecl *ND) {476    ND = cast<NamedDecl>(ND->getCanonicalDecl());477 478    addSubstitution(reinterpret_cast<uintptr_t>(ND));479  }480  void addSubstitution(QualType T);481  void addSubstitution(TemplateName Template);482  void addSubstitution(uintptr_t Ptr);483  // Destructive copy substitutions from other mangler.484  void extendSubstitutions(CXXNameMangler* Other);485 486  void mangleUnresolvedPrefix(NestedNameSpecifier Qualifier,487                              bool recursive = false);488  void mangleUnresolvedName(NestedNameSpecifier Qualifier, DeclarationName name,489                            const TemplateArgumentLoc *TemplateArgs,490                            unsigned NumTemplateArgs,491                            unsigned KnownArity = UnknownArity);492 493  void mangleFunctionEncodingBareType(const FunctionDecl *FD);494 495  void mangleNameWithAbiTags(GlobalDecl GD,496                             const AbiTagList *AdditionalAbiTags);497  void mangleModuleName(const NamedDecl *ND);498  void mangleTemplateName(const TemplateDecl *TD,499                          ArrayRef<TemplateArgument> Args);500  void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,501                             const AbiTagList *AdditionalAbiTags) {502    mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,503                          UnknownArity, AdditionalAbiTags);504  }505  void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,506                             const DeclContext *DC, unsigned KnownArity,507                             const AbiTagList *AdditionalAbiTags);508  void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,509                          const AbiTagList *AdditionalAbiTags);510  void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,511                                  const AbiTagList *AdditionalAbiTags);512  void mangleSourceName(const IdentifierInfo *II);513  void mangleRegCallName(const IdentifierInfo *II);514  void mangleDeviceStubName(const IdentifierInfo *II);515  void mangleOCLDeviceStubName(const IdentifierInfo *II);516  void mangleSourceNameWithAbiTags(517      const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);518  void mangleLocalName(GlobalDecl GD,519                       const AbiTagList *AdditionalAbiTags);520  void mangleBlockForPrefix(const BlockDecl *Block);521  void mangleUnqualifiedBlock(const BlockDecl *Block);522  void mangleTemplateParamDecl(const NamedDecl *Decl);523  void mangleTemplateParameterList(const TemplateParameterList *Params);524  void mangleTypeConstraint(const TemplateDecl *Concept,525                            ArrayRef<TemplateArgument> Arguments);526  void mangleTypeConstraint(const TypeConstraint *Constraint);527  void mangleRequiresClause(const Expr *RequiresClause);528  void mangleLambda(const CXXRecordDecl *Lambda);529  void mangleNestedName(GlobalDecl GD, const DeclContext *DC,530                        const AbiTagList *AdditionalAbiTags,531                        bool NoFunction=false);532  void mangleNestedName(const TemplateDecl *TD,533                        ArrayRef<TemplateArgument> Args);534  void mangleNestedNameWithClosurePrefix(GlobalDecl GD,535                                         const NamedDecl *PrefixND,536                                         const AbiTagList *AdditionalAbiTags);537  void manglePrefix(NestedNameSpecifier Qualifier);538  void manglePrefix(const DeclContext *DC, bool NoFunction=false);539  void manglePrefix(QualType type);540  void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);541  void mangleTemplatePrefix(TemplateName Template);542  const NamedDecl *getClosurePrefix(const Decl *ND);543  void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);544  bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,545                                      StringRef Prefix = "");546  void mangleOperatorName(DeclarationName Name, unsigned Arity);547  void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);548  void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);549  void mangleRefQualifier(RefQualifierKind RefQualifier);550 551  void mangleObjCMethodName(const ObjCMethodDecl *MD);552 553  // Declare manglers for every type class.554#define ABSTRACT_TYPE(CLASS, PARENT)555#define NON_CANONICAL_TYPE(CLASS, PARENT)556#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);557#include "clang/AST/TypeNodes.inc"558 559  void mangleType(const TagType*);560  void mangleType(TemplateName);561  static StringRef getCallingConvQualifierName(CallingConv CC);562  void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);563  void mangleExtFunctionInfo(const FunctionType *T);564  void mangleSMEAttrs(unsigned SMEAttrs);565  void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,566                              const FunctionDecl *FD = nullptr);567  void mangleNeonVectorType(const VectorType *T);568  void mangleNeonVectorType(const DependentVectorType *T);569  void mangleAArch64NeonVectorType(const VectorType *T);570  void mangleAArch64NeonVectorType(const DependentVectorType *T);571  void mangleAArch64FixedSveVectorType(const VectorType *T);572  void mangleAArch64FixedSveVectorType(const DependentVectorType *T);573  void mangleRISCVFixedRVVVectorType(const VectorType *T);574  void mangleRISCVFixedRVVVectorType(const DependentVectorType *T);575 576  void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);577  void mangleFloatLiteral(QualType T, const llvm::APFloat &V);578  void mangleFixedPointLiteral();579  void mangleNullPointer(QualType T);580 581  void mangleMemberExprBase(const Expr *base, bool isArrow);582  void mangleMemberExpr(const Expr *base, bool isArrow,583                        NestedNameSpecifier Qualifier,584                        NamedDecl *firstQualifierLookup, DeclarationName name,585                        const TemplateArgumentLoc *TemplateArgs,586                        unsigned NumTemplateArgs, unsigned knownArity);587  void mangleCastExpression(const Expr *E, StringRef CastEncoding);588  void mangleInitListElements(const InitListExpr *InitList);589  void mangleRequirement(SourceLocation RequiresExprLoc,590                         const concepts::Requirement *Req);591  void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,592                        bool AsTemplateArg = false);593  void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);594  void mangleCXXDtorType(CXXDtorType T);595 596  struct TemplateArgManglingInfo;597  void mangleTemplateArgs(TemplateName TN,598                          const TemplateArgumentLoc *TemplateArgs,599                          unsigned NumTemplateArgs);600  void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);601  void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);602  void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index,603                         TemplateArgument A);604  void mangleTemplateArg(TemplateArgument A, bool NeedExactType);605  void mangleTemplateArgExpr(const Expr *E);606  void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,607                                bool NeedExactType = false);608 609  void mangleTemplateParameter(unsigned Depth, unsigned Index);610 611  void mangleFunctionParam(const ParmVarDecl *parm);612 613  void writeAbiTags(const NamedDecl *ND,614                    const AbiTagList *AdditionalAbiTags);615 616  // Returns sorted unique list of ABI tags.617  AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);618  // Returns sorted unique list of ABI tags.619  AbiTagList makeVariableTypeTags(const VarDecl *VD);620};621 622}623 624NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {625  if (!StdNamespace) {626    StdNamespace = NamespaceDecl::Create(627        getASTContext(), getASTContext().getTranslationUnitDecl(),628        /*Inline=*/false, SourceLocation(), SourceLocation(),629        &getASTContext().Idents.get("std"),630        /*PrevDecl=*/nullptr, /*Nested=*/false);631    StdNamespace->setImplicit();632  }633  return StdNamespace;634}635 636/// Retrieve the declaration context that should be used when mangling the given637/// declaration.638const DeclContext *639ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {640  // The ABI assumes that lambda closure types that occur within641  // default arguments live in the context of the function. However, due to642  // the way in which Clang parses and creates function declarations, this is643  // not the case: the lambda closure type ends up living in the context644  // where the function itself resides, because the function declaration itself645  // had not yet been created. Fix the context here.646  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {647    if (RD->isLambda())648      if (ParmVarDecl *ContextParam =649              dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))650        return ContextParam->getDeclContext();651  }652 653  // Perform the same check for block literals.654  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {655    if (ParmVarDecl *ContextParam =656            dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))657      return ContextParam->getDeclContext();658  }659 660  // On ARM and AArch64, the va_list tag is always mangled as if in the std661  // namespace. We do not represent va_list as actually being in the std662  // namespace in C because this would result in incorrect debug info in C,663  // among other things. It is important for both languages to have the same664  // mangling in order for -fsanitize=cfi-icall to work.665  if (D == getASTContext().getVaListTagDecl()) {666    const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();667    if (T.isARM() || T.isThumb() || T.isAArch64())668      return getStdNamespace();669  }670 671  const DeclContext *DC = D->getDeclContext();672  if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||673      isa<OMPDeclareMapperDecl>(DC)) {674    return getEffectiveDeclContext(cast<Decl>(DC));675  }676 677  if (const auto *VD = dyn_cast<VarDecl>(D))678    if (VD->isExternC())679      return getASTContext().getTranslationUnitDecl();680 681  if (const auto *FD = getASTContext().getLangOpts().getClangABICompat() >682                               LangOptions::ClangABI::Ver19683                           ? D->getAsFunction()684                           : dyn_cast<FunctionDecl>(D)) {685    if (FD->isExternC())686      return getASTContext().getTranslationUnitDecl();687    // Member-like constrained friends are mangled as if they were members of688    // the enclosing class.689    if (FD->isMemberLikeConstrainedFriend() &&690        getASTContext().getLangOpts().getClangABICompat() >691            LangOptions::ClangABI::Ver17)692      return D->getLexicalDeclContext()->getRedeclContext();693  }694 695  return DC->getRedeclContext();696}697 698bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {699  if (ND && ND->getFormalLinkage() == Linkage::Internal &&700      !ND->isExternallyVisible() &&701      getEffectiveDeclContext(ND)->isFileContext() &&702      !ND->isInAnonymousNamespace())703    return true;704  return false;705}706 707// Check if this Function Decl needs a unique internal linkage name.708bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(709    const NamedDecl *ND) {710  if (!NeedsUniqueInternalLinkageNames || !ND)711    return false;712 713  const auto *FD = dyn_cast<FunctionDecl>(ND);714  if (!FD)715    return false;716 717  // For C functions without prototypes, return false as their718  // names should not be mangled.719  if (!FD->getType()->getAs<FunctionProtoType>())720    return false;721 722  if (isInternalLinkageDecl(ND))723    return true;724 725  return false;726}727 728bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {729  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {730    LanguageLinkage L = FD->getLanguageLinkage();731    // Overloadable functions need mangling.732    if (FD->hasAttr<OverloadableAttr>())733      return true;734 735    // "main" is not mangled.736    if (FD->isMain())737      return false;738 739    // The Windows ABI expects that we would never mangle "typical"740    // user-defined entry points regardless of visibility or freestanding-ness.741    //742    // N.B. This is distinct from asking about "main".  "main" has a lot of743    // special rules associated with it in the standard while these744    // user-defined entry points are outside of the purview of the standard.745    // For example, there can be only one definition for "main" in a standards746    // compliant program; however nothing forbids the existence of wmain and747    // WinMain in the same translation unit.748    if (FD->isMSVCRTEntryPoint())749      return false;750 751    // C++ functions and those whose names are not a simple identifier need752    // mangling.753    if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)754      return true;755 756    // C functions are not mangled.757    if (L == CLanguageLinkage)758      return false;759  }760 761  // Otherwise, no mangling is done outside C++ mode.762  if (!getASTContext().getLangOpts().CPlusPlus)763    return false;764 765  if (const auto *VD = dyn_cast<VarDecl>(D)) {766    // Decompositions are mangled.767    if (isa<DecompositionDecl>(VD))768      return true;769 770    // C variables are not mangled.771    if (VD->isExternC())772      return false;773 774    // Variables at global scope are not mangled unless they have internal775    // linkage or are specializations or are attached to a named module.776    const DeclContext *DC = getEffectiveDeclContext(D);777    // Check for extern variable declared locally.778    if (DC->isFunctionOrMethod() && D->hasLinkage())779      while (!DC->isFileContext())780        DC = getEffectiveParentContext(DC);781    if (DC->isTranslationUnit() && D->getFormalLinkage() != Linkage::Internal &&782        !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&783        !isa<VarTemplateSpecializationDecl>(VD) &&784        !VD->getOwningModuleForLinkage())785      return false;786  }787 788  return true;789}790 791void CXXNameMangler::writeAbiTags(const NamedDecl *ND,792                                  const AbiTagList *AdditionalAbiTags) {793  assert(AbiTags && "require AbiTagState");794  AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);795}796 797void CXXNameMangler::mangleSourceNameWithAbiTags(798    const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {799  mangleSourceName(ND->getIdentifier());800  writeAbiTags(ND, AdditionalAbiTags);801}802 803void CXXNameMangler::mangle(GlobalDecl GD) {804  // <mangled-name> ::= _Z <encoding>805  //            ::= <data name>806  //            ::= <special-name>807  Out << "_Z";808  if (isa<FunctionDecl>(GD.getDecl()))809    mangleFunctionEncoding(GD);810  else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,811               BindingDecl>(GD.getDecl()))812    mangleName(GD);813  else if (const IndirectFieldDecl *IFD =814               dyn_cast<IndirectFieldDecl>(GD.getDecl()))815    mangleName(IFD->getAnonField());816  else817    llvm_unreachable("unexpected kind of global decl");818}819 820void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {821  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());822  // <encoding> ::= <function name> <bare-function-type>823 824  // Don't mangle in the type if this isn't a decl we should typically mangle.825  if (!Context.shouldMangleDeclName(FD)) {826    mangleName(GD);827    return;828  }829 830  AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);831  if (ReturnTypeAbiTags.empty()) {832    // There are no tags for return type, the simplest case. Enter the function833    // parameter scope before mangling the name, because a template using834    // constrained `auto` can have references to its parameters within its835    // template argument list:836    //837    //   template<typename T> void f(T x, C<decltype(x)> auto)838    // ... is mangled as ...839    //   template<typename T, C<decltype(param 1)> U> void f(T, U)840    FunctionTypeDepthState Saved = FunctionTypeDepth.push();841    mangleName(GD);842    FunctionTypeDepth.pop(Saved);843    mangleFunctionEncodingBareType(FD);844    return;845  }846 847  // Mangle function name and encoding to temporary buffer.848  // We have to output name and encoding to the same mangler to get the same849  // substitution as it will be in final mangling.850  SmallString<256> FunctionEncodingBuf;851  llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);852  CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);853  // Output name of the function.854  FunctionEncodingMangler.disableDerivedAbiTags();855 856  FunctionTypeDepthState Saved = FunctionTypeDepth.push();857  FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);858  FunctionTypeDepth.pop(Saved);859 860  // Remember length of the function name in the buffer.861  size_t EncodingPositionStart = FunctionEncodingStream.str().size();862  FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);863 864  // Get tags from return type that are not present in function name or865  // encoding.866  const AbiTagList &UsedAbiTags =867      FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();868  AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());869  AdditionalAbiTags.erase(870      std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),871                          UsedAbiTags.begin(), UsedAbiTags.end(),872                          AdditionalAbiTags.begin()),873      AdditionalAbiTags.end());874 875  // Output name with implicit tags and function encoding from temporary buffer.876  Saved = FunctionTypeDepth.push();877  mangleNameWithAbiTags(FD, &AdditionalAbiTags);878  FunctionTypeDepth.pop(Saved);879  Out << FunctionEncodingStream.str().substr(EncodingPositionStart);880 881  // Function encoding could create new substitutions so we have to add882  // temp mangled substitutions to main mangler.883  extendSubstitutions(&FunctionEncodingMangler);884}885 886void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {887  if (FD->hasAttr<EnableIfAttr>()) {888    FunctionTypeDepthState Saved = FunctionTypeDepth.push();889    Out << "Ua9enable_ifI";890    for (AttrVec::const_iterator I = FD->getAttrs().begin(),891                                 E = FD->getAttrs().end();892         I != E; ++I) {893      EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);894      if (!EIA)895        continue;896      if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {897        // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,898        // even though <template-arg> should not include an X/E around899        // <expr-primary>.900        Out << 'X';901        mangleExpression(EIA->getCond());902        Out << 'E';903      } else {904        mangleTemplateArgExpr(EIA->getCond());905      }906    }907    Out << 'E';908    FunctionTypeDepth.pop(Saved);909  }910 911  // When mangling an inheriting constructor, the bare function type used is912  // that of the inherited constructor.913  if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))914    if (auto Inherited = CD->getInheritedConstructor())915      FD = Inherited.getConstructor();916 917  // Whether the mangling of a function type includes the return type depends on918  // the context and the nature of the function. The rules for deciding whether919  // the return type is included are:920  //921  //   1. Template functions (names or types) have return types encoded, with922  //   the exceptions listed below.923  //   2. Function types not appearing as part of a function name mangling,924  //   e.g. parameters, pointer types, etc., have return type encoded, with the925  //   exceptions listed below.926  //   3. Non-template function names do not have return types encoded.927  //928  // The exceptions mentioned in (1) and (2) above, for which the return type is929  // never included, are930  //   1. Constructors.931  //   2. Destructors.932  //   3. Conversion operator functions, e.g. operator int.933  bool MangleReturnType = false;934  if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {935    if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||936          isa<CXXConversionDecl>(FD)))937      MangleReturnType = true;938 939    // Mangle the type of the primary template.940    FD = PrimaryTemplate->getTemplatedDecl();941  }942 943  mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),944                         MangleReturnType, FD);945}946 947/// Return whether a given namespace is the 'std' namespace.948bool CXXNameMangler::isStd(const NamespaceDecl *NS) {949  if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())950    return false;951 952  const IdentifierInfo *II = NS->getFirstDecl()->getIdentifier();953  return II && II->isStr("std");954}955 956// isStdNamespace - Return whether a given decl context is a toplevel 'std'957// namespace.958bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {959  if (!DC->isNamespace())960    return false;961 962  return isStd(cast<NamespaceDecl>(DC));963}964 965static const GlobalDecl966isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {967  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());968  // Check if we have a function template.969  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {970    if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {971      TemplateArgs = FD->getTemplateSpecializationArgs();972      return GD.getWithDecl(TD);973    }974  }975 976  // Check if we have a class template.977  if (const ClassTemplateSpecializationDecl *Spec =978        dyn_cast<ClassTemplateSpecializationDecl>(ND)) {979    TemplateArgs = &Spec->getTemplateArgs();980    return GD.getWithDecl(Spec->getSpecializedTemplate());981  }982 983  // Check if we have a variable template.984  if (const VarTemplateSpecializationDecl *Spec =985          dyn_cast<VarTemplateSpecializationDecl>(ND)) {986    TemplateArgs = &Spec->getTemplateArgs();987    return GD.getWithDecl(Spec->getSpecializedTemplate());988  }989 990  return GlobalDecl();991}992 993static TemplateName asTemplateName(GlobalDecl GD) {994  const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());995  return TemplateName(const_cast<TemplateDecl*>(TD));996}997 998void CXXNameMangler::mangleName(GlobalDecl GD) {999  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());1000  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {1001    // Variables should have implicit tags from its type.1002    AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);1003    if (VariableTypeAbiTags.empty()) {1004      // Simple case no variable type tags.1005      mangleNameWithAbiTags(VD, nullptr);1006      return;1007    }1008 1009    // Mangle variable name to null stream to collect tags.1010    llvm::raw_null_ostream NullOutStream;1011    CXXNameMangler VariableNameMangler(*this, NullOutStream);1012    VariableNameMangler.disableDerivedAbiTags();1013    VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);1014 1015    // Get tags from variable type that are not present in its name.1016    const AbiTagList &UsedAbiTags =1017        VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();1018    AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());1019    AdditionalAbiTags.erase(1020        std::set_difference(VariableTypeAbiTags.begin(),1021                            VariableTypeAbiTags.end(), UsedAbiTags.begin(),1022                            UsedAbiTags.end(), AdditionalAbiTags.begin()),1023        AdditionalAbiTags.end());1024 1025    // Output name with implicit tags.1026    mangleNameWithAbiTags(VD, &AdditionalAbiTags);1027  } else {1028    mangleNameWithAbiTags(GD, nullptr);1029  }1030}1031 1032const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {1033  const DeclContext *DC = Context.getEffectiveDeclContext(D);1034  while (!DC->isNamespace() && !DC->isTranslationUnit()) {1035    if (isLocalContainerContext(DC))1036      return dyn_cast<RecordDecl>(D);1037    D = cast<Decl>(DC);1038    DC = Context.getEffectiveDeclContext(D);1039  }1040  return nullptr;1041}1042 1043void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,1044                                           const AbiTagList *AdditionalAbiTags) {1045  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());1046  //  <name> ::= [<module-name>] <nested-name>1047  //         ::= [<module-name>] <unscoped-name>1048  //         ::= [<module-name>] <unscoped-template-name> <template-args>1049  //         ::= <local-name>1050  //1051  const DeclContext *DC = Context.getEffectiveDeclContext(ND);1052  bool IsLambda = isLambda(ND);1053 1054  // If this is an extern variable declared locally, the relevant DeclContext1055  // is that of the containing namespace, or the translation unit.1056  // FIXME: This is a hack; extern variables declared locally should have1057  // a proper semantic declaration context!1058  if (isLocalContainerContext(DC) && ND->hasLinkage() && !IsLambda)1059    while (!DC->isNamespace() && !DC->isTranslationUnit())1060      DC = Context.getEffectiveParentContext(DC);1061  else if (GetLocalClassDecl(ND) &&1062           (!IsLambda || isCompatibleWith(LangOptions::ClangABI::Ver18))) {1063    mangleLocalName(GD, AdditionalAbiTags);1064    return;1065  }1066 1067  assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");1068 1069  // Closures can require a nested-name mangling even if they're semantically1070  // in the global namespace.1071  if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {1072    mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);1073    return;1074  }1075 1076  if (isLocalContainerContext(DC)) {1077    mangleLocalName(GD, AdditionalAbiTags);1078    return;1079  }1080 1081  while (DC->isRequiresExprBody())1082    DC = DC->getParent();1083 1084  if (DC->isTranslationUnit() || isStdNamespace(DC)) {1085    // Check if we have a template.1086    const TemplateArgumentList *TemplateArgs = nullptr;1087    if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {1088      mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);1089      mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);1090      return;1091    }1092 1093    mangleUnscopedName(GD, DC, AdditionalAbiTags);1094    return;1095  }1096 1097  mangleNestedName(GD, DC, AdditionalAbiTags);1098}1099 1100void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {1101  if (ND->isExternallyVisible())1102    if (Module *M = ND->getOwningModuleForLinkage())1103      mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());1104}1105 1106// <module-name> ::= <module-subname>1107//		 ::= <module-name> <module-subname>1108//	 	 ::= <substitution>1109// <module-subname> ::= W <source-name>1110//		    ::= W P <source-name>1111void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {1112  //  <substitution> ::= S <seq-id> _1113  auto It = ModuleSubstitutions.find(Name);1114  if (It != ModuleSubstitutions.end()) {1115    Out << 'S';1116    mangleSeqID(It->second);1117    return;1118  }1119 1120  // FIXME: Preserve hierarchy in module names rather than flattening1121  // them to strings; use Module*s as substitution keys.1122  auto Parts = Name.rsplit('.');1123  if (Parts.second.empty())1124    Parts.second = Parts.first;1125  else {1126    mangleModuleNamePrefix(Parts.first, IsPartition);1127    IsPartition = false;1128  }1129 1130  Out << 'W';1131  if (IsPartition)1132    Out << 'P';1133  Out << Parts.second.size() << Parts.second;1134  ModuleSubstitutions.insert({Name, SeqID++});1135}1136 1137void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,1138                                        ArrayRef<TemplateArgument> Args) {1139  const DeclContext *DC = Context.getEffectiveDeclContext(TD);1140 1141  if (DC->isTranslationUnit() || isStdNamespace(DC)) {1142    mangleUnscopedTemplateName(TD, DC, nullptr);1143    mangleTemplateArgs(asTemplateName(TD), Args);1144  } else {1145    mangleNestedName(TD, Args);1146  }1147}1148 1149void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,1150                                        const AbiTagList *AdditionalAbiTags) {1151  //  <unscoped-name> ::= <unqualified-name>1152  //                  ::= St <unqualified-name>   # ::std::1153 1154  assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");1155  if (isStdNamespace(DC)) {1156    if (getASTContext().getTargetInfo().getTriple().isOSSolaris()) {1157      const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());1158      if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND)) {1159        // Issue #33114: Need non-standard mangling of std::tm etc. for1160        // Solaris ABI compatibility.1161        //1162        // <substitution> ::= tm # ::std::tm, same for the others1163        if (const IdentifierInfo *II = RD->getIdentifier()) {1164          StringRef type = II->getName();1165          if (llvm::is_contained({"div_t", "ldiv_t", "lconv", "tm"}, type)) {1166            Out << type.size() << type;1167            return;1168          }1169        }1170      }1171    }1172    Out << "St";1173  }1174 1175  mangleUnqualifiedName(GD, DC, AdditionalAbiTags);1176}1177 1178void CXXNameMangler::mangleUnscopedTemplateName(1179    GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {1180  const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());1181  //     <unscoped-template-name> ::= <unscoped-name>1182  //                              ::= <substitution>1183  if (mangleSubstitution(ND))1184    return;1185 1186  // <template-template-param> ::= <template-param>1187  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {1188    assert(!AdditionalAbiTags &&1189           "template template param cannot have abi tags");1190    mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());1191  } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {1192    mangleUnscopedName(GD, DC, AdditionalAbiTags);1193  } else {1194    mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,1195                       AdditionalAbiTags);1196  }1197 1198  addSubstitution(ND);1199}1200 1201void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {1202  // ABI:1203  //   Floating-point literals are encoded using a fixed-length1204  //   lowercase hexadecimal string corresponding to the internal1205  //   representation (IEEE on Itanium), high-order bytes first,1206  //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f1207  //   on Itanium.1208  // The 'without leading zeroes' thing seems to be an editorial1209  // mistake; see the discussion on cxx-abi-dev beginning on1210  // 2012-01-16.1211 1212  // Our requirements here are just barely weird enough to justify1213  // using a custom algorithm instead of post-processing APInt::toString().1214 1215  llvm::APInt valueBits = f.bitcastToAPInt();1216  unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;1217  assert(numCharacters != 0);1218 1219  // Allocate a buffer of the right number of characters.1220  SmallVector<char, 20> buffer(numCharacters);1221 1222  // Fill the buffer left-to-right.1223  for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {1224    // The bit-index of the next hex digit.1225    unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);1226 1227    // Project out 4 bits starting at 'digitIndex'.1228    uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];1229    hexDigit >>= (digitBitIndex % 64);1230    hexDigit &= 0xF;1231 1232    // Map that over to a lowercase hex digit.1233    static const char charForHex[16] = {1234      '0', '1', '2', '3', '4', '5', '6', '7',1235      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'1236    };1237    buffer[stringIndex] = charForHex[hexDigit];1238  }1239 1240  Out.write(buffer.data(), numCharacters);1241}1242 1243void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {1244  Out << 'L';1245  mangleType(T);1246  mangleFloat(V);1247  Out << 'E';1248}1249 1250void CXXNameMangler::mangleFixedPointLiteral() {1251  DiagnosticsEngine &Diags = Context.getDiags();1252  unsigned DiagID = Diags.getCustomDiagID(1253      DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");1254  Diags.Report(DiagID);1255}1256 1257void CXXNameMangler::mangleNullPointer(QualType T) {1258  //  <expr-primary> ::= L <type> 0 E1259  Out << 'L';1260  mangleType(T);1261  Out << "0E";1262}1263 1264void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {1265  if (Value.isSigned() && Value.isNegative()) {1266    Out << 'n';1267    Value.abs().print(Out, /*signed*/ false);1268  } else {1269    Value.print(Out, /*signed*/ false);1270  }1271}1272 1273void CXXNameMangler::mangleNumber(int64_t Number) {1274  //  <number> ::= [n] <non-negative decimal integer>1275  if (Number < 0) {1276    Out << 'n';1277    Number = -Number;1278  }1279 1280  Out << Number;1281}1282 1283void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {1284  //  <call-offset>  ::= h <nv-offset> _1285  //                 ::= v <v-offset> _1286  //  <nv-offset>    ::= <offset number>        # non-virtual base override1287  //  <v-offset>     ::= <offset number> _ <virtual offset number>1288  //                      # virtual base override, with vcall offset1289  if (!Virtual) {1290    Out << 'h';1291    mangleNumber(NonVirtual);1292    Out << '_';1293    return;1294  }1295 1296  Out << 'v';1297  mangleNumber(NonVirtual);1298  Out << '_';1299  mangleNumber(Virtual);1300  Out << '_';1301}1302 1303void CXXNameMangler::manglePrefix(QualType type) {1304  if (const auto *TST = type->getAs<TemplateSpecializationType>()) {1305    if (!mangleSubstitution(QualType(TST, 0))) {1306      mangleTemplatePrefix(TST->getTemplateName());1307 1308      // FIXME: GCC does not appear to mangle the template arguments when1309      // the template in question is a dependent template name. Should we1310      // emulate that badness?1311      mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());1312      addSubstitution(QualType(TST, 0));1313    }1314  } else if (const auto *DNT = type->getAs<DependentNameType>()) {1315    // Clang 14 and before did not consider this substitutable.1316    bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14);1317    if (!Clang14Compat && mangleSubstitution(QualType(DNT, 0)))1318      return;1319 1320    // Member expressions can have these without prefixes, but that1321    // should end up in mangleUnresolvedPrefix instead.1322    assert(DNT->getQualifier());1323    manglePrefix(DNT->getQualifier());1324 1325    mangleSourceName(DNT->getIdentifier());1326 1327    if (!Clang14Compat)1328      addSubstitution(QualType(DNT, 0));1329  } else {1330    // We use the QualType mangle type variant here because it handles1331    // substitutions.1332    mangleType(type);1333  }1334}1335 1336/// Mangle everything prior to the base-unresolved-name in an unresolved-name.1337///1338/// \param recursive - true if this is being called recursively,1339///   i.e. if there is more prefix "to the right".1340void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier Qualifier,1341                                            bool recursive) {1342 1343  // x, ::x1344  // <unresolved-name> ::= [gs] <base-unresolved-name>1345 1346  // T::x / decltype(p)::x1347  // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>1348 1349  // T::N::x /decltype(p)::N::x1350  // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E1351  //                       <base-unresolved-name>1352 1353  // A::x, N::y, A<T>::z; "gs" means leading "::"1354  // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E1355  //                       <base-unresolved-name>1356 1357  switch (Qualifier.getKind()) {1358  case NestedNameSpecifier::Kind::Null:1359    llvm_unreachable("unexpected null nested name specifier");1360 1361  case NestedNameSpecifier::Kind::Global:1362    Out << "gs";1363 1364    // We want an 'sr' unless this is the entire NNS.1365    if (recursive)1366      Out << "sr";1367 1368    // We never want an 'E' here.1369    return;1370 1371  case NestedNameSpecifier::Kind::MicrosoftSuper:1372    llvm_unreachable("Can't mangle __super specifier");1373 1374  case NestedNameSpecifier::Kind::Namespace: {1375    auto [Namespace, Prefix] = Qualifier.getAsNamespaceAndPrefix();1376    if (Prefix)1377      mangleUnresolvedPrefix(Prefix,1378                             /*recursive*/ true);1379    else1380      Out << "sr";1381    mangleSourceNameWithAbiTags(Namespace);1382    break;1383  }1384 1385  case NestedNameSpecifier::Kind::Type: {1386    const Type *type = Qualifier.getAsType();1387 1388    // We only want to use an unresolved-type encoding if this is one of:1389    //   - a decltype1390    //   - a template type parameter1391    //   - a template template parameter with arguments1392    // In all of these cases, we should have no prefix.1393    if (NestedNameSpecifier Prefix = type->getPrefix()) {1394      mangleUnresolvedPrefix(Prefix,1395                             /*recursive=*/true);1396    } else {1397      // Otherwise, all the cases want this.1398      Out << "sr";1399    }1400 1401    if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))1402      return;1403 1404    break;1405  }1406  }1407 1408  // If this was the innermost part of the NNS, and we fell out to1409  // here, append an 'E'.1410  if (!recursive)1411    Out << 'E';1412}1413 1414/// Mangle an unresolved-name, which is generally used for names which1415/// weren't resolved to specific entities.1416void CXXNameMangler::mangleUnresolvedName(1417    NestedNameSpecifier Qualifier, DeclarationName name,1418    const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,1419    unsigned knownArity) {1420  if (Qualifier)1421    mangleUnresolvedPrefix(Qualifier);1422  switch (name.getNameKind()) {1423    // <base-unresolved-name> ::= <simple-id>1424    case DeclarationName::Identifier:1425      mangleSourceName(name.getAsIdentifierInfo());1426      break;1427    // <base-unresolved-name> ::= dn <destructor-name>1428    case DeclarationName::CXXDestructorName:1429      Out << "dn";1430      mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());1431      break;1432    // <base-unresolved-name> ::= on <operator-name>1433    case DeclarationName::CXXConversionFunctionName:1434    case DeclarationName::CXXLiteralOperatorName:1435    case DeclarationName::CXXOperatorName:1436      Out << "on";1437      mangleOperatorName(name, knownArity);1438      break;1439    case DeclarationName::CXXConstructorName:1440      llvm_unreachable("Can't mangle a constructor name!");1441    case DeclarationName::CXXUsingDirective:1442      llvm_unreachable("Can't mangle a using directive name!");1443    case DeclarationName::CXXDeductionGuideName:1444      llvm_unreachable("Can't mangle a deduction guide name!");1445    case DeclarationName::ObjCMultiArgSelector:1446    case DeclarationName::ObjCOneArgSelector:1447    case DeclarationName::ObjCZeroArgSelector:1448      llvm_unreachable("Can't mangle Objective-C selector names here!");1449  }1450 1451  // The <simple-id> and on <operator-name> productions end in an optional1452  // <template-args>.1453  if (TemplateArgs)1454    mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);1455}1456 1457void CXXNameMangler::mangleUnqualifiedName(1458    GlobalDecl GD, DeclarationName Name, const DeclContext *DC,1459    unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {1460  const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());1461  //  <unqualified-name> ::= [<module-name>] [F] <operator-name>1462  //                     ::= <ctor-dtor-name>1463  //                     ::= [<module-name>] [F] <source-name>1464  //                     ::= [<module-name>] DC <source-name>* E1465 1466  if (ND && DC && DC->isFileContext())1467    mangleModuleName(ND);1468 1469  // A member-like constrained friend is mangled with a leading 'F'.1470  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.1471  auto *FD = dyn_cast<FunctionDecl>(ND);1472  auto *FTD = dyn_cast<FunctionTemplateDecl>(ND);1473  if ((FD && FD->isMemberLikeConstrainedFriend()) ||1474      (FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {1475    if (!isCompatibleWith(LangOptions::ClangABI::Ver17))1476      Out << 'F';1477  }1478 1479  unsigned Arity = KnownArity;1480  switch (Name.getNameKind()) {1481  case DeclarationName::Identifier: {1482    const IdentifierInfo *II = Name.getAsIdentifierInfo();1483 1484    // We mangle decomposition declarations as the names of their bindings.1485    if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {1486      // FIXME: Non-standard mangling for decomposition declarations:1487      //1488      //  <unqualified-name> ::= DC <source-name>* E1489      //1490      // Proposed on cxx-abi-dev on 2016-08-121491      Out << "DC";1492      for (auto *BD : DD->bindings())1493        mangleSourceName(BD->getDeclName().getAsIdentifierInfo());1494      Out << 'E';1495      writeAbiTags(ND, AdditionalAbiTags);1496      break;1497    }1498 1499    if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {1500      // We follow MSVC in mangling GUID declarations as if they were variables1501      // with a particular reserved name. Continue the pretense here.1502      SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;1503      llvm::raw_svector_ostream GUIDOS(GUID);1504      Context.mangleMSGuidDecl(GD, GUIDOS);1505      Out << GUID.size() << GUID;1506      break;1507    }1508 1509    if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {1510      // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.1511      Out << "TA";1512      mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),1513                               TPO->getValue(), /*TopLevel=*/true);1514      break;1515    }1516 1517    if (II) {1518      // Match GCC's naming convention for internal linkage symbols, for1519      // symbols that are not actually visible outside of this TU. GCC1520      // distinguishes between internal and external linkage symbols in1521      // its mangling, to support cases like this that were valid C++ prior1522      // to DR426:1523      //1524      //   void test() { extern void foo(); }1525      //   static void foo();1526      //1527      // Don't bother with the L marker for names in anonymous namespaces; the1528      // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better1529      // matches GCC anyway, because GCC does not treat anonymous namespaces as1530      // implying internal linkage.1531      if (Context.isInternalLinkageDecl(ND))1532        Out << 'L';1533 1534      bool IsRegCall = FD &&1535                       FD->getType()->castAs<FunctionType>()->getCallConv() ==1536                           clang::CC_X86RegCall;1537      bool IsDeviceStub =1538          FD && FD->hasAttr<CUDAGlobalAttr>() &&1539          GD.getKernelReferenceKind() == KernelReferenceKind::Stub;1540      bool IsOCLDeviceStub =1541          FD &&1542          DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()) &&1543          GD.getKernelReferenceKind() == KernelReferenceKind::Stub;1544      if (IsDeviceStub)1545        mangleDeviceStubName(II);1546      else if (IsOCLDeviceStub)1547        mangleOCLDeviceStubName(II);1548      else if (IsRegCall)1549        mangleRegCallName(II);1550      else1551        mangleSourceName(II);1552 1553      writeAbiTags(ND, AdditionalAbiTags);1554      break;1555    }1556 1557    // Otherwise, an anonymous entity.  We must have a declaration.1558    assert(ND && "mangling empty name without declaration");1559 1560    if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {1561      if (NS->isAnonymousNamespace()) {1562        // This is how gcc mangles these names.1563        Out << "12_GLOBAL__N_1";1564        break;1565      }1566    }1567 1568    if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {1569      // We must have an anonymous union or struct declaration.1570      const auto *RD = VD->getType()->castAsRecordDecl();1571 1572      // Itanium C++ ABI 5.1.2:1573      //1574      //   For the purposes of mangling, the name of an anonymous union is1575      //   considered to be the name of the first named data member found by a1576      //   pre-order, depth-first, declaration-order walk of the data members of1577      //   the anonymous union. If there is no such data member (i.e., if all of1578      //   the data members in the union are unnamed), then there is no way for1579      //   a program to refer to the anonymous union, and there is therefore no1580      //   need to mangle its name.1581      assert(RD->isAnonymousStructOrUnion()1582             && "Expected anonymous struct or union!");1583      const FieldDecl *FD = RD->findFirstNamedDataMember();1584 1585      // It's actually possible for various reasons for us to get here1586      // with an empty anonymous struct / union.  Fortunately, it1587      // doesn't really matter what name we generate.1588      if (!FD) break;1589      assert(FD->getIdentifier() && "Data member name isn't an identifier!");1590 1591      mangleSourceName(FD->getIdentifier());1592      // Not emitting abi tags: internal name anyway.1593      break;1594    }1595 1596    // Class extensions have no name as a category, and it's possible1597    // for them to be the semantic parent of certain declarations1598    // (primarily, tag decls defined within declarations).  Such1599    // declarations will always have internal linkage, so the name1600    // doesn't really matter, but we shouldn't crash on them.  For1601    // safety, just handle all ObjC containers here.1602    if (isa<ObjCContainerDecl>(ND))1603      break;1604 1605    // We must have an anonymous struct.1606    const TagDecl *TD = cast<TagDecl>(ND);1607    if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {1608      assert(TD->getDeclContext() == D->getDeclContext() &&1609             "Typedef should not be in another decl context!");1610      assert(D->getDeclName().getAsIdentifierInfo() &&1611             "Typedef was not named!");1612      mangleSourceName(D->getDeclName().getAsIdentifierInfo());1613      assert(!AdditionalAbiTags && "Type cannot have additional abi tags");1614      // Explicit abi tags are still possible; take from underlying type, not1615      // from typedef.1616      writeAbiTags(TD, nullptr);1617      break;1618    }1619 1620    // <unnamed-type-name> ::= <closure-type-name>1621    //1622    // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _1623    // <lambda-sig> ::= <template-param-decl>* <parameter-type>+1624    //     # Parameter types or 'v' for 'void'.1625    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {1626      UnsignedOrNone DeviceNumber =1627          Context.getDiscriminatorOverride()(Context.getASTContext(), Record);1628 1629      // If we have a device-number via the discriminator, use that to mangle1630      // the lambda, otherwise use the typical lambda-mangling-number. In either1631      // case, a '0' should be mangled as a normal unnamed class instead of as a1632      // lambda.1633      if (Record->isLambda() &&1634          ((DeviceNumber && *DeviceNumber > 0) ||1635           (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {1636        assert(!AdditionalAbiTags &&1637               "Lambda type cannot have additional abi tags");1638        mangleLambda(Record);1639        break;1640      }1641    }1642 1643    if (TD->isExternallyVisible()) {1644      unsigned UnnamedMangle =1645          getASTContext().getManglingNumber(TD, Context.isAux());1646      Out << "Ut";1647      if (UnnamedMangle > 1)1648        Out << UnnamedMangle - 2;1649      Out << '_';1650      writeAbiTags(TD, AdditionalAbiTags);1651      break;1652    }1653 1654    // Get a unique id for the anonymous struct. If it is not a real output1655    // ID doesn't matter so use fake one.1656    unsigned AnonStructId =1657        NullOut ? 01658                : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));1659 1660    // Mangle it as a source name in the form1661    // [n] $_<id>1662    // where n is the length of the string.1663    SmallString<8> Str;1664    Str += "$_";1665    Str += llvm::utostr(AnonStructId);1666 1667    Out << Str.size();1668    Out << Str;1669    break;1670  }1671 1672  case DeclarationName::ObjCZeroArgSelector:1673  case DeclarationName::ObjCOneArgSelector:1674  case DeclarationName::ObjCMultiArgSelector:1675    llvm_unreachable("Can't mangle Objective-C selector names here!");1676 1677  case DeclarationName::CXXConstructorName: {1678    const CXXRecordDecl *InheritedFrom = nullptr;1679    TemplateName InheritedTemplateName;1680    const TemplateArgumentList *InheritedTemplateArgs = nullptr;1681    if (auto Inherited =1682            cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {1683      InheritedFrom = Inherited.getConstructor()->getParent();1684      InheritedTemplateName =1685          TemplateName(Inherited.getConstructor()->getPrimaryTemplate());1686      InheritedTemplateArgs =1687          Inherited.getConstructor()->getTemplateSpecializationArgs();1688    }1689 1690    if (ND == Structor)1691      // If the named decl is the C++ constructor we're mangling, use the type1692      // we were given.1693      mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);1694    else1695      // Otherwise, use the complete constructor name. This is relevant if a1696      // class with a constructor is declared within a constructor.1697      mangleCXXCtorType(Ctor_Complete, InheritedFrom);1698 1699    // FIXME: The template arguments are part of the enclosing prefix or1700    // nested-name, but it's more convenient to mangle them here.1701    if (InheritedTemplateArgs)1702      mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);1703 1704    writeAbiTags(ND, AdditionalAbiTags);1705    break;1706  }1707 1708  case DeclarationName::CXXDestructorName:1709    if (ND == Structor)1710      // If the named decl is the C++ destructor we're mangling, use the type we1711      // were given.1712      mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));1713    else1714      // Otherwise, use the complete destructor name. This is relevant if a1715      // class with a destructor is declared within a destructor.1716      mangleCXXDtorType(Dtor_Complete);1717    assert(ND);1718    writeAbiTags(ND, AdditionalAbiTags);1719    break;1720 1721  case DeclarationName::CXXOperatorName:1722    if (ND && Arity == UnknownArity) {1723      Arity = cast<FunctionDecl>(ND)->getNumParams();1724 1725      // If we have a member function, we need to include the 'this' pointer.1726      if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))1727        if (MD->isImplicitObjectMemberFunction())1728          Arity++;1729    }1730    [[fallthrough]];1731  case DeclarationName::CXXConversionFunctionName:1732  case DeclarationName::CXXLiteralOperatorName:1733    mangleOperatorName(Name, Arity);1734    writeAbiTags(ND, AdditionalAbiTags);1735    break;1736 1737  case DeclarationName::CXXDeductionGuideName:1738    llvm_unreachable("Can't mangle a deduction guide name!");1739 1740  case DeclarationName::CXXUsingDirective:1741    llvm_unreachable("Can't mangle a using directive name!");1742  }1743}1744 1745void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {1746  // <source-name> ::= <positive length number> __regcall3__ <identifier>1747  // <number> ::= [n] <non-negative decimal integer>1748  // <identifier> ::= <unqualified source code identifier>1749  if (getASTContext().getLangOpts().RegCall4)1750    Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"1751        << II->getName();1752  else1753    Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"1754        << II->getName();1755}1756 1757void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {1758  // <source-name> ::= <positive length number> __device_stub__ <identifier>1759  // <number> ::= [n] <non-negative decimal integer>1760  // <identifier> ::= <unqualified source code identifier>1761  Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"1762      << II->getName();1763}1764 1765void CXXNameMangler::mangleOCLDeviceStubName(const IdentifierInfo *II) {1766  // <source-name> ::= <positive length number> __clang_ocl_kern_imp_1767  // <identifier> <number> ::= [n] <non-negative decimal integer> <identifier>1768  // ::= <unqualified source code identifier>1769  StringRef OCLDeviceStubNamePrefix = "__clang_ocl_kern_imp_";1770  Out << II->getLength() + OCLDeviceStubNamePrefix.size()1771      << OCLDeviceStubNamePrefix << II->getName();1772}1773 1774void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {1775  // <source-name> ::= <positive length number> <identifier>1776  // <number> ::= [n] <non-negative decimal integer>1777  // <identifier> ::= <unqualified source code identifier>1778  Out << II->getLength() << II->getName();1779}1780 1781void CXXNameMangler::mangleNestedName(GlobalDecl GD,1782                                      const DeclContext *DC,1783                                      const AbiTagList *AdditionalAbiTags,1784                                      bool NoFunction) {1785  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());1786  // <nested-name>1787  //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E1788  //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>1789  //       <template-args> E1790 1791  Out << 'N';1792  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {1793    Qualifiers MethodQuals = Method->getMethodQualifiers();1794    // We do not consider restrict a distinguishing attribute for overloading1795    // purposes so we must not mangle it.1796    if (Method->isExplicitObjectMemberFunction())1797      Out << 'H';1798    MethodQuals.removeRestrict();1799    mangleQualifiers(MethodQuals);1800    mangleRefQualifier(Method->getRefQualifier());1801  }1802 1803  // Check if we have a template.1804  const TemplateArgumentList *TemplateArgs = nullptr;1805  if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {1806    mangleTemplatePrefix(TD, NoFunction);1807    mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);1808  } else {1809    manglePrefix(DC, NoFunction);1810    mangleUnqualifiedName(GD, DC, AdditionalAbiTags);1811  }1812 1813  Out << 'E';1814}1815void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,1816                                      ArrayRef<TemplateArgument> Args) {1817  // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E1818 1819  Out << 'N';1820 1821  mangleTemplatePrefix(TD);1822  mangleTemplateArgs(asTemplateName(TD), Args);1823 1824  Out << 'E';1825}1826 1827void CXXNameMangler::mangleNestedNameWithClosurePrefix(1828    GlobalDecl GD, const NamedDecl *PrefixND,1829    const AbiTagList *AdditionalAbiTags) {1830  // A <closure-prefix> represents a variable or field, not a regular1831  // DeclContext, so needs special handling. In this case we're mangling a1832  // limited form of <nested-name>:1833  //1834  // <nested-name> ::= N <closure-prefix> <closure-type-name> E1835 1836  Out << 'N';1837 1838  mangleClosurePrefix(PrefixND);1839  mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);1840 1841  Out << 'E';1842}1843 1844static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {1845  GlobalDecl GD;1846  // The Itanium spec says:1847  // For entities in constructors and destructors, the mangling of the1848  // complete object constructor or destructor is used as the base function1849  // name, i.e. the C1 or D1 version.1850  if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))1851    GD = GlobalDecl(CD, Ctor_Complete);1852  else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))1853    GD = GlobalDecl(DD, Dtor_Complete);1854  else1855    GD = GlobalDecl(cast<FunctionDecl>(DC));1856  return GD;1857}1858 1859void CXXNameMangler::mangleLocalName(GlobalDecl GD,1860                                     const AbiTagList *AdditionalAbiTags) {1861  const Decl *D = GD.getDecl();1862  // <local-name> := Z <function encoding> E <entity name> [<discriminator>]1863  //              := Z <function encoding> E s [<discriminator>]1864  // <local-name> := Z <function encoding> E d [ <parameter number> ]1865  //                 _ <entity name>1866  // <discriminator> := _ <non-negative number>1867  assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));1868  const RecordDecl *RD = GetLocalClassDecl(D);1869  const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);1870 1871  Out << 'Z';1872 1873  {1874    AbiTagState LocalAbiTags(AbiTags);1875 1876    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))1877      mangleObjCMethodName(MD);1878    else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))1879      mangleBlockForPrefix(BD);1880    else1881      mangleFunctionEncoding(getParentOfLocalEntity(DC));1882 1883    // Implicit ABI tags (from namespace) are not available in the following1884    // entity; reset to actually emitted tags, which are available.1885    LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());1886  }1887 1888  Out << 'E';1889 1890  // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to1891  // be a bug that is fixed in trunk.1892 1893  if (RD) {1894    // The parameter number is omitted for the last parameter, 0 for the1895    // second-to-last parameter, 1 for the third-to-last parameter, etc. The1896    // <entity name> will of course contain a <closure-type-name>: Its1897    // numbering will be local to the particular argument in which it appears1898    // -- other default arguments do not affect its encoding.1899    const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);1900    if (CXXRD && CXXRD->isLambda()) {1901      if (const ParmVarDecl *Parm1902              = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {1903        if (const FunctionDecl *Func1904              = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {1905          Out << 'd';1906          unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();1907          if (Num > 1)1908            mangleNumber(Num - 2);1909          Out << '_';1910        }1911      }1912    }1913 1914    // Mangle the name relative to the closest enclosing function.1915    // equality ok because RD derived from ND above1916    if (D == RD)  {1917      mangleUnqualifiedName(RD, DC, AdditionalAbiTags);1918    } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {1919      if (const NamedDecl *PrefixND = getClosurePrefix(BD))1920        mangleClosurePrefix(PrefixND, true /*NoFunction*/);1921      else1922        manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);1923      assert(!AdditionalAbiTags && "Block cannot have additional abi tags");1924      mangleUnqualifiedBlock(BD);1925    } else {1926      const NamedDecl *ND = cast<NamedDecl>(D);1927      mangleNestedName(GD, Context.getEffectiveDeclContext(ND),1928                       AdditionalAbiTags, true /*NoFunction*/);1929    }1930  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {1931    // Mangle a block in a default parameter; see above explanation for1932    // lambdas.1933    if (const ParmVarDecl *Parm1934            = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {1935      if (const FunctionDecl *Func1936            = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {1937        Out << 'd';1938        unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();1939        if (Num > 1)1940          mangleNumber(Num - 2);1941        Out << '_';1942      }1943    }1944 1945    assert(!AdditionalAbiTags && "Block cannot have additional abi tags");1946    mangleUnqualifiedBlock(BD);1947  } else {1948    mangleUnqualifiedName(GD, DC, AdditionalAbiTags);1949  }1950 1951  if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {1952    unsigned disc;1953    if (Context.getNextDiscriminator(ND, disc)) {1954      if (disc < 10)1955        Out << '_' << disc;1956      else1957        Out << "__" << disc << '_';1958    }1959  }1960}1961 1962void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {1963  if (GetLocalClassDecl(Block)) {1964    mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);1965    return;1966  }1967  const DeclContext *DC = Context.getEffectiveDeclContext(Block);1968  if (isLocalContainerContext(DC)) {1969    mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);1970    return;1971  }1972  if (const NamedDecl *PrefixND = getClosurePrefix(Block))1973    mangleClosurePrefix(PrefixND);1974  else1975    manglePrefix(DC);1976  mangleUnqualifiedBlock(Block);1977}1978 1979void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {1980  // When trying to be ABI-compatibility with clang 12 and before, mangle a1981  // <data-member-prefix> now, with no substitutions and no <template-args>.1982  if (Decl *Context = Block->getBlockManglingContextDecl()) {1983    if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&1984        (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&1985        Context->getDeclContext()->isRecord()) {1986      const auto *ND = cast<NamedDecl>(Context);1987      if (ND->getIdentifier()) {1988        mangleSourceNameWithAbiTags(ND);1989        Out << 'M';1990      }1991    }1992  }1993 1994  // If we have a block mangling number, use it.1995  unsigned Number = Block->getBlockManglingNumber();1996  // Otherwise, just make up a number. It doesn't matter what it is because1997  // the symbol in question isn't externally visible.1998  if (!Number)1999    Number = Context.getBlockId(Block, false);2000  else {2001    // Stored mangling numbers are 1-based.2002    --Number;2003  }2004  Out << "Ub";2005  if (Number > 0)2006    Out << Number - 1;2007  Out << '_';2008}2009 2010// <template-param-decl>2011//   ::= Ty                                  # template type parameter2012//   ::= Tk <concept name> [<template-args>] # constrained type parameter2013//   ::= Tn <type>                           # template non-type parameter2014//   ::= Tt <template-param-decl>* E [Q <requires-clause expr>]2015//                                           # template template parameter2016//   ::= Tp <template-param-decl>            # template parameter pack2017void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {2018  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.2019  if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {2020    if (Ty->isParameterPack())2021      Out << "Tp";2022    const TypeConstraint *Constraint = Ty->getTypeConstraint();2023    if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {2024      // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.2025      Out << "Tk";2026      mangleTypeConstraint(Constraint);2027    } else {2028      Out << "Ty";2029    }2030  } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {2031    if (Tn->isExpandedParameterPack()) {2032      for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {2033        Out << "Tn";2034        mangleType(Tn->getExpansionType(I));2035      }2036    } else {2037      QualType T = Tn->getType();2038      if (Tn->isParameterPack()) {2039        Out << "Tp";2040        if (auto *PackExpansion = T->getAs<PackExpansionType>())2041          T = PackExpansion->getPattern();2042      }2043      Out << "Tn";2044      mangleType(T);2045    }2046  } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {2047    if (Tt->isExpandedParameterPack()) {2048      for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;2049           ++I)2050        mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));2051    } else {2052      if (Tt->isParameterPack())2053        Out << "Tp";2054      mangleTemplateParameterList(Tt->getTemplateParameters());2055    }2056  }2057}2058 2059void CXXNameMangler::mangleTemplateParameterList(2060    const TemplateParameterList *Params) {2061  Out << "Tt";2062  for (auto *Param : *Params)2063    mangleTemplateParamDecl(Param);2064  mangleRequiresClause(Params->getRequiresClause());2065  Out << "E";2066}2067 2068void CXXNameMangler::mangleTypeConstraint(2069    const TemplateDecl *Concept, ArrayRef<TemplateArgument> Arguments) {2070  const DeclContext *DC = Context.getEffectiveDeclContext(Concept);2071  if (!Arguments.empty())2072    mangleTemplateName(Concept, Arguments);2073  else if (DC->isTranslationUnit() || isStdNamespace(DC))2074    mangleUnscopedName(Concept, DC, nullptr);2075  else2076    mangleNestedName(Concept, DC, nullptr);2077}2078 2079void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {2080  llvm::SmallVector<TemplateArgument, 8> Args;2081  if (Constraint->getTemplateArgsAsWritten()) {2082    for (const TemplateArgumentLoc &ArgLoc :2083         Constraint->getTemplateArgsAsWritten()->arguments())2084      Args.push_back(ArgLoc.getArgument());2085  }2086  return mangleTypeConstraint(Constraint->getNamedConcept(), Args);2087}2088 2089void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {2090  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.2091  if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {2092    Out << 'Q';2093    mangleExpression(RequiresClause);2094  }2095}2096 2097void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {2098  // When trying to be ABI-compatibility with clang 12 and before, mangle a2099  // <data-member-prefix> now, with no substitutions.2100  if (Decl *Context = Lambda->getLambdaContextDecl()) {2101    if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&2102        (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&2103        !isa<ParmVarDecl>(Context)) {2104      if (const IdentifierInfo *Name2105            = cast<NamedDecl>(Context)->getIdentifier()) {2106        mangleSourceName(Name);2107        const TemplateArgumentList *TemplateArgs = nullptr;2108        if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))2109          mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);2110        Out << 'M';2111      }2112    }2113  }2114 2115  Out << "Ul";2116  mangleLambdaSig(Lambda);2117  Out << "E";2118 2119  // The number is omitted for the first closure type with a given2120  // <lambda-sig> in a given context; it is n-2 for the nth closure type2121  // (in lexical order) with that same <lambda-sig> and context.2122  //2123  // The AST keeps track of the number for us.2124  //2125  // In CUDA/HIP, to ensure the consistent lamba numbering between the device-2126  // and host-side compilations, an extra device mangle context may be created2127  // if the host-side CXX ABI has different numbering for lambda. In such case,2128  // if the mangle context is that device-side one, use the device-side lambda2129  // mangling number for this lambda.2130  UnsignedOrNone DeviceNumber =2131      Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);2132  unsigned Number =2133      DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();2134 2135  assert(Number > 0 && "Lambda should be mangled as an unnamed class");2136  if (Number > 1)2137    mangleNumber(Number - 2);2138  Out << '_';2139}2140 2141void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {2142  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.2143  for (auto *D : Lambda->getLambdaExplicitTemplateParameters())2144    mangleTemplateParamDecl(D);2145 2146  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.2147  if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())2148    mangleRequiresClause(TPL->getRequiresClause());2149 2150  auto *Proto =2151      Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();2152  mangleBareFunctionType(Proto, /*MangleReturnType=*/false,2153                         Lambda->getLambdaStaticInvoker());2154}2155 2156void CXXNameMangler::manglePrefix(NestedNameSpecifier Qualifier) {2157  switch (Qualifier.getKind()) {2158  case NestedNameSpecifier::Kind::Null:2159  case NestedNameSpecifier::Kind::Global:2160    // nothing2161    return;2162 2163  case NestedNameSpecifier::Kind::MicrosoftSuper:2164    llvm_unreachable("Can't mangle __super specifier");2165 2166  case NestedNameSpecifier::Kind::Namespace:2167    mangleName(Qualifier.getAsNamespaceAndPrefix().Namespace->getNamespace());2168    return;2169 2170  case NestedNameSpecifier::Kind::Type:2171    manglePrefix(QualType(Qualifier.getAsType(), 0));2172    return;2173  }2174 2175  llvm_unreachable("unexpected nested name specifier");2176}2177 2178void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {2179  //  <prefix> ::= <prefix> <unqualified-name>2180  //           ::= <template-prefix> <template-args>2181  //           ::= <closure-prefix>2182  //           ::= <template-param>2183  //           ::= # empty2184  //           ::= <substitution>2185 2186  assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");2187 2188  if (DC->isTranslationUnit())2189    return;2190 2191  if (NoFunction && isLocalContainerContext(DC))2192    return;2193 2194  const NamedDecl *ND = cast<NamedDecl>(DC);2195  if (mangleSubstitution(ND))2196    return;2197 2198  // Check if we have a template-prefix or a closure-prefix.2199  const TemplateArgumentList *TemplateArgs = nullptr;2200  if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {2201    mangleTemplatePrefix(TD);2202    mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);2203  } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {2204    mangleClosurePrefix(PrefixND, NoFunction);2205    mangleUnqualifiedName(ND, nullptr, nullptr);2206  } else {2207    const DeclContext *DC = Context.getEffectiveDeclContext(ND);2208    manglePrefix(DC, NoFunction);2209    mangleUnqualifiedName(ND, DC, nullptr);2210  }2211 2212  addSubstitution(ND);2213}2214 2215void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {2216  // <template-prefix> ::= <prefix> <template unqualified-name>2217  //                   ::= <template-param>2218  //                   ::= <substitution>2219  if (TemplateDecl *TD = Template.getAsTemplateDecl())2220    return mangleTemplatePrefix(TD);2221 2222  DependentTemplateName *Dependent = Template.getAsDependentTemplateName();2223  assert(Dependent && "unexpected template name kind");2224 2225  // Clang 11 and before mangled the substitution for a dependent template name2226  // after already having emitted (a substitution for) the prefix.2227  bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11);2228  if (!Clang11Compat && mangleSubstitution(Template))2229    return;2230 2231  manglePrefix(Dependent->getQualifier());2232 2233  if (Clang11Compat && mangleSubstitution(Template))2234    return;2235 2236  if (IdentifierOrOverloadedOperator Name = Dependent->getName();2237      const IdentifierInfo *Id = Name.getIdentifier())2238    mangleSourceName(Id);2239  else2240    mangleOperatorName(Name.getOperator(), UnknownArity);2241 2242  addSubstitution(Template);2243}2244 2245void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,2246                                          bool NoFunction) {2247  const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());2248  // <template-prefix> ::= <prefix> <template unqualified-name>2249  //                   ::= <template-param>2250  //                   ::= <substitution>2251  // <template-template-param> ::= <template-param>2252  //                               <substitution>2253 2254  if (mangleSubstitution(ND))2255    return;2256 2257  // <template-template-param> ::= <template-param>2258  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {2259    mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());2260  } else {2261    const DeclContext *DC = Context.getEffectiveDeclContext(ND);2262    manglePrefix(DC, NoFunction);2263    if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))2264      mangleUnqualifiedName(GD, DC, nullptr);2265    else2266      mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,2267                            nullptr);2268  }2269 2270  addSubstitution(ND);2271}2272 2273const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {2274  if (isCompatibleWith(LangOptions::ClangABI::Ver12))2275    return nullptr;2276 2277  const NamedDecl *Context = nullptr;2278  if (auto *Block = dyn_cast<BlockDecl>(ND)) {2279    Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());2280  } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {2281    if (RD->isLambda())2282      Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());2283  }2284  if (!Context)2285    return nullptr;2286 2287  // Only lambdas within the initializer of a non-local variable or non-static2288  // data member get a <closure-prefix>.2289  if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||2290      isa<FieldDecl>(Context))2291    return Context;2292 2293  return nullptr;2294}2295 2296void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {2297  //  <closure-prefix> ::= [ <prefix> ] <unqualified-name> M2298  //                   ::= <template-prefix> <template-args> M2299  if (mangleSubstitution(ND))2300    return;2301 2302  const TemplateArgumentList *TemplateArgs = nullptr;2303  if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {2304    mangleTemplatePrefix(TD, NoFunction);2305    mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);2306  } else {2307    const auto *DC = Context.getEffectiveDeclContext(ND);2308    manglePrefix(DC, NoFunction);2309    mangleUnqualifiedName(ND, DC, nullptr);2310  }2311 2312  Out << 'M';2313 2314  addSubstitution(ND);2315}2316 2317/// Mangles a template name under the production <type>.  Required for2318/// template template arguments.2319///   <type> ::= <class-enum-type>2320///          ::= <template-param>2321///          ::= <substitution>2322void CXXNameMangler::mangleType(TemplateName TN) {2323  if (mangleSubstitution(TN))2324    return;2325 2326  TemplateDecl *TD = nullptr;2327 2328  switch (TN.getKind()) {2329  case TemplateName::QualifiedTemplate:2330  case TemplateName::UsingTemplate:2331  case TemplateName::Template:2332    TD = TN.getAsTemplateDecl();2333    goto HaveDecl;2334 2335  HaveDecl:2336    if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))2337      mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());2338    else2339      mangleName(TD);2340    break;2341 2342  case TemplateName::OverloadedTemplate:2343  case TemplateName::AssumedTemplate:2344    llvm_unreachable("can't mangle an overloaded template name as a <type>");2345 2346  case TemplateName::DependentTemplate: {2347    const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();2348    const IdentifierInfo *II = Dependent->getName().getIdentifier();2349    assert(II);2350 2351    // <class-enum-type> ::= <name>2352    // <name> ::= <nested-name>2353    mangleUnresolvedPrefix(Dependent->getQualifier());2354    mangleSourceName(II);2355    break;2356  }2357 2358  case TemplateName::SubstTemplateTemplateParm: {2359    // Substituted template parameters are mangled as the substituted2360    // template.  This will check for the substitution twice, which is2361    // fine, but we have to return early so that we don't try to *add*2362    // the substitution twice.2363    SubstTemplateTemplateParmStorage *subst2364      = TN.getAsSubstTemplateTemplateParm();2365    mangleType(subst->getReplacement());2366    return;2367  }2368 2369  case TemplateName::SubstTemplateTemplateParmPack: {2370    // FIXME: not clear how to mangle this!2371    // template <template <class> class T...> class A {2372    //   template <template <class> class U...> void foo(B<T,U> x...);2373    // };2374    Out << "_SUBSTPACK_";2375    break;2376  }2377  case TemplateName::DeducedTemplate:2378    llvm_unreachable("Unexpected DeducedTemplate");2379  }2380 2381  addSubstitution(TN);2382}2383 2384bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,2385                                                    StringRef Prefix) {2386  // Only certain other types are valid as prefixes;  enumerate them.2387  switch (Ty->getTypeClass()) {2388  case Type::Builtin:2389  case Type::Complex:2390  case Type::Adjusted:2391  case Type::Decayed:2392  case Type::ArrayParameter:2393  case Type::Pointer:2394  case Type::BlockPointer:2395  case Type::LValueReference:2396  case Type::RValueReference:2397  case Type::MemberPointer:2398  case Type::ConstantArray:2399  case Type::IncompleteArray:2400  case Type::VariableArray:2401  case Type::DependentSizedArray:2402  case Type::DependentAddressSpace:2403  case Type::DependentVector:2404  case Type::DependentSizedExtVector:2405  case Type::Vector:2406  case Type::ExtVector:2407  case Type::ConstantMatrix:2408  case Type::DependentSizedMatrix:2409  case Type::FunctionProto:2410  case Type::FunctionNoProto:2411  case Type::Paren:2412  case Type::Attributed:2413  case Type::BTFTagAttributed:2414  case Type::HLSLAttributedResource:2415  case Type::HLSLInlineSpirv:2416  case Type::Auto:2417  case Type::DeducedTemplateSpecialization:2418  case Type::PackExpansion:2419  case Type::ObjCObject:2420  case Type::ObjCInterface:2421  case Type::ObjCObjectPointer:2422  case Type::ObjCTypeParam:2423  case Type::Atomic:2424  case Type::Pipe:2425  case Type::MacroQualified:2426  case Type::BitInt:2427  case Type::DependentBitInt:2428  case Type::CountAttributed:2429    llvm_unreachable("type is illegal as a nested name specifier");2430 2431  case Type::SubstBuiltinTemplatePack:2432    // FIXME: not clear how to mangle this!2433    // template <class T...> class A {2434    //   template <class U...> void foo(__builtin_dedup_pack<T...>(*)(U) x...);2435    // };2436    Out << "_SUBSTBUILTINPACK_";2437    break;2438  case Type::SubstTemplateTypeParmPack:2439    // FIXME: not clear how to mangle this!2440    // template <class T...> class A {2441    //   template <class U...> void foo(decltype(T::foo(U())) x...);2442    // };2443    Out << "_SUBSTPACK_";2444    break;2445 2446  // <unresolved-type> ::= <template-param>2447  //                   ::= <decltype>2448  //                   ::= <template-template-param> <template-args>2449  // (this last is not official yet)2450  case Type::TypeOfExpr:2451  case Type::TypeOf:2452  case Type::Decltype:2453  case Type::PackIndexing:2454  case Type::TemplateTypeParm:2455  case Type::UnaryTransform:2456  unresolvedType:2457    // Some callers want a prefix before the mangled type.2458    Out << Prefix;2459 2460    // This seems to do everything we want.  It's not really2461    // sanctioned for a substituted template parameter, though.2462    mangleType(Ty);2463 2464    // We never want to print 'E' directly after an unresolved-type,2465    // so we return directly.2466    return true;2467 2468  case Type::SubstTemplateTypeParm: {2469    auto *ST = cast<SubstTemplateTypeParmType>(Ty);2470    // If this was replaced from a type alias, this is not substituted2471    // from an outer template parameter, so it's not an unresolved-type.2472    if (auto *TD = dyn_cast<TemplateDecl>(ST->getAssociatedDecl());2473        TD && TD->isTypeAlias())2474      return mangleUnresolvedTypeOrSimpleId(ST->getReplacementType(), Prefix);2475    goto unresolvedType;2476  }2477 2478  case Type::Typedef:2479    mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());2480    break;2481 2482  case Type::PredefinedSugar:2483    mangleType(cast<PredefinedSugarType>(Ty)->desugar());2484    break;2485 2486  case Type::UnresolvedUsing:2487    mangleSourceNameWithAbiTags(2488        cast<UnresolvedUsingType>(Ty)->getDecl());2489    break;2490 2491  case Type::Enum:2492  case Type::Record:2493    mangleSourceNameWithAbiTags(2494        cast<TagType>(Ty)->getDecl()->getDefinitionOrSelf());2495    break;2496 2497  case Type::TemplateSpecialization: {2498    const TemplateSpecializationType *TST =2499        cast<TemplateSpecializationType>(Ty);2500    TemplateName TN = TST->getTemplateName();2501    switch (TN.getKind()) {2502    case TemplateName::Template:2503    case TemplateName::QualifiedTemplate: {2504      TemplateDecl *TD = TN.getAsTemplateDecl();2505 2506      // If the base is a template template parameter, this is an2507      // unresolved type.2508      assert(TD && "no template for template specialization type");2509      if (isa<TemplateTemplateParmDecl>(TD))2510        goto unresolvedType;2511 2512      mangleSourceNameWithAbiTags(TD);2513      break;2514    }2515    case TemplateName::DependentTemplate: {2516      const DependentTemplateStorage *S = TN.getAsDependentTemplateName();2517      mangleSourceName(S->getName().getIdentifier());2518      break;2519    }2520 2521    case TemplateName::OverloadedTemplate:2522    case TemplateName::AssumedTemplate:2523    case TemplateName::DeducedTemplate:2524      llvm_unreachable("invalid base for a template specialization type");2525 2526    case TemplateName::SubstTemplateTemplateParm: {2527      SubstTemplateTemplateParmStorage *subst =2528          TN.getAsSubstTemplateTemplateParm();2529      mangleExistingSubstitution(subst->getReplacement());2530      break;2531    }2532 2533    case TemplateName::SubstTemplateTemplateParmPack: {2534      // FIXME: not clear how to mangle this!2535      // template <template <class U> class T...> class A {2536      //   template <class U...> void foo(decltype(T<U>::foo) x...);2537      // };2538      Out << "_SUBSTPACK_";2539      break;2540    }2541    case TemplateName::UsingTemplate: {2542      TemplateDecl *TD = TN.getAsTemplateDecl();2543      assert(TD && !isa<TemplateTemplateParmDecl>(TD));2544      mangleSourceNameWithAbiTags(TD);2545      break;2546    }2547    }2548 2549    // Note: we don't pass in the template name here. We are mangling the2550    // original source-level template arguments, so we shouldn't consider2551    // conversions to the corresponding template parameter.2552    // FIXME: Other compilers mangle partially-resolved template arguments in2553    // unresolved-qualifier-levels.2554    mangleTemplateArgs(TemplateName(), TST->template_arguments());2555    break;2556  }2557 2558  case Type::InjectedClassName:2559    mangleSourceNameWithAbiTags(2560        cast<InjectedClassNameType>(Ty)->getDecl()->getDefinitionOrSelf());2561    break;2562 2563  case Type::DependentName:2564    mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());2565    break;2566 2567  case Type::Using:2568    return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),2569                                          Prefix);2570  }2571 2572  return false;2573}2574 2575void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {2576  switch (Name.getNameKind()) {2577  case DeclarationName::CXXConstructorName:2578  case DeclarationName::CXXDestructorName:2579  case DeclarationName::CXXDeductionGuideName:2580  case DeclarationName::CXXUsingDirective:2581  case DeclarationName::Identifier:2582  case DeclarationName::ObjCMultiArgSelector:2583  case DeclarationName::ObjCOneArgSelector:2584  case DeclarationName::ObjCZeroArgSelector:2585    llvm_unreachable("Not an operator name");2586 2587  case DeclarationName::CXXConversionFunctionName:2588    // <operator-name> ::= cv <type>    # (cast)2589    Out << "cv";2590    mangleType(Name.getCXXNameType());2591    break;2592 2593  case DeclarationName::CXXLiteralOperatorName:2594    Out << "li";2595    mangleSourceName(Name.getCXXLiteralIdentifier());2596    return;2597 2598  case DeclarationName::CXXOperatorName:2599    mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);2600    break;2601  }2602}2603 2604void2605CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {2606  switch (OO) {2607  // <operator-name> ::= nw     # new2608  case OO_New: Out << "nw"; break;2609  //              ::= na        # new[]2610  case OO_Array_New: Out << "na"; break;2611  //              ::= dl        # delete2612  case OO_Delete: Out << "dl"; break;2613  //              ::= da        # delete[]2614  case OO_Array_Delete: Out << "da"; break;2615  //              ::= ps        # + (unary)2616  //              ::= pl        # + (binary or unknown)2617  case OO_Plus:2618    Out << (Arity == 1? "ps" : "pl"); break;2619  //              ::= ng        # - (unary)2620  //              ::= mi        # - (binary or unknown)2621  case OO_Minus:2622    Out << (Arity == 1? "ng" : "mi"); break;2623  //              ::= ad        # & (unary)2624  //              ::= an        # & (binary or unknown)2625  case OO_Amp:2626    Out << (Arity == 1? "ad" : "an"); break;2627  //              ::= de        # * (unary)2628  //              ::= ml        # * (binary or unknown)2629  case OO_Star:2630    // Use binary when unknown.2631    Out << (Arity == 1? "de" : "ml"); break;2632  //              ::= co        # ~2633  case OO_Tilde: Out << "co"; break;2634  //              ::= dv        # /2635  case OO_Slash: Out << "dv"; break;2636  //              ::= rm        # %2637  case OO_Percent: Out << "rm"; break;2638  //              ::= or        # |2639  case OO_Pipe: Out << "or"; break;2640  //              ::= eo        # ^2641  case OO_Caret: Out << "eo"; break;2642  //              ::= aS        # =2643  case OO_Equal: Out << "aS"; break;2644  //              ::= pL        # +=2645  case OO_PlusEqual: Out << "pL"; break;2646  //              ::= mI        # -=2647  case OO_MinusEqual: Out << "mI"; break;2648  //              ::= mL        # *=2649  case OO_StarEqual: Out << "mL"; break;2650  //              ::= dV        # /=2651  case OO_SlashEqual: Out << "dV"; break;2652  //              ::= rM        # %=2653  case OO_PercentEqual: Out << "rM"; break;2654  //              ::= aN        # &=2655  case OO_AmpEqual: Out << "aN"; break;2656  //              ::= oR        # |=2657  case OO_PipeEqual: Out << "oR"; break;2658  //              ::= eO        # ^=2659  case OO_CaretEqual: Out << "eO"; break;2660  //              ::= ls        # <<2661  case OO_LessLess: Out << "ls"; break;2662  //              ::= rs        # >>2663  case OO_GreaterGreater: Out << "rs"; break;2664  //              ::= lS        # <<=2665  case OO_LessLessEqual: Out << "lS"; break;2666  //              ::= rS        # >>=2667  case OO_GreaterGreaterEqual: Out << "rS"; break;2668  //              ::= eq        # ==2669  case OO_EqualEqual: Out << "eq"; break;2670  //              ::= ne        # !=2671  case OO_ExclaimEqual: Out << "ne"; break;2672  //              ::= lt        # <2673  case OO_Less: Out << "lt"; break;2674  //              ::= gt        # >2675  case OO_Greater: Out << "gt"; break;2676  //              ::= le        # <=2677  case OO_LessEqual: Out << "le"; break;2678  //              ::= ge        # >=2679  case OO_GreaterEqual: Out << "ge"; break;2680  //              ::= nt        # !2681  case OO_Exclaim: Out << "nt"; break;2682  //              ::= aa        # &&2683  case OO_AmpAmp: Out << "aa"; break;2684  //              ::= oo        # ||2685  case OO_PipePipe: Out << "oo"; break;2686  //              ::= pp        # ++2687  case OO_PlusPlus: Out << "pp"; break;2688  //              ::= mm        # --2689  case OO_MinusMinus: Out << "mm"; break;2690  //              ::= cm        # ,2691  case OO_Comma: Out << "cm"; break;2692  //              ::= pm        # ->*2693  case OO_ArrowStar: Out << "pm"; break;2694  //              ::= pt        # ->2695  case OO_Arrow: Out << "pt"; break;2696  //              ::= cl        # ()2697  case OO_Call: Out << "cl"; break;2698  //              ::= ix        # []2699  case OO_Subscript: Out << "ix"; break;2700 2701  //              ::= qu        # ?2702  // The conditional operator can't be overloaded, but we still handle it when2703  // mangling expressions.2704  case OO_Conditional: Out << "qu"; break;2705  // Proposal on cxx-abi-dev, 2015-10-21.2706  //              ::= aw        # co_await2707  case OO_Coawait: Out << "aw"; break;2708  // Proposed in cxx-abi github issue 43.2709  //              ::= ss        # <=>2710  case OO_Spaceship: Out << "ss"; break;2711 2712  case OO_None:2713  case NUM_OVERLOADED_OPERATORS:2714    llvm_unreachable("Not an overloaded operator");2715  }2716}2717 2718void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {2719  // Vendor qualifiers come first and if they are order-insensitive they must2720  // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.2721 2722  // <type> ::= U <addrspace-expr>2723  if (DAST) {2724    Out << "U2ASI";2725    mangleExpression(DAST->getAddrSpaceExpr());2726    Out << "E";2727  }2728 2729  // Address space qualifiers start with an ordinary letter.2730  if (Quals.hasAddressSpace()) {2731    // Address space extension:2732    //2733    //   <type> ::= U <target-addrspace>2734    //   <type> ::= U <OpenCL-addrspace>2735    //   <type> ::= U <CUDA-addrspace>2736 2737    SmallString<64> ASString;2738    LangAS AS = Quals.getAddressSpace();2739 2740    if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {2741      //  <target-addrspace> ::= "AS" <address-space-number>2742      unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);2743      if (TargetAS != 0 ||2744          Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)2745        ASString = "AS" + llvm::utostr(TargetAS);2746    } else {2747      switch (AS) {2748      default: llvm_unreachable("Not a language specific address space");2749      //  <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |2750      //                                "private"| "generic" | "device" |2751      //                                "host" ]2752      case LangAS::opencl_global:2753        ASString = "CLglobal";2754        break;2755      case LangAS::opencl_global_device:2756        ASString = "CLdevice";2757        break;2758      case LangAS::opencl_global_host:2759        ASString = "CLhost";2760        break;2761      case LangAS::opencl_local:2762        ASString = "CLlocal";2763        break;2764      case LangAS::opencl_constant:2765        ASString = "CLconstant";2766        break;2767      case LangAS::opencl_private:2768        ASString = "CLprivate";2769        break;2770      case LangAS::opencl_generic:2771        ASString = "CLgeneric";2772        break;2773      //  <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |2774      //                              "device" | "host" ]2775      case LangAS::sycl_global:2776        ASString = "SYglobal";2777        break;2778      case LangAS::sycl_global_device:2779        ASString = "SYdevice";2780        break;2781      case LangAS::sycl_global_host:2782        ASString = "SYhost";2783        break;2784      case LangAS::sycl_local:2785        ASString = "SYlocal";2786        break;2787      case LangAS::sycl_private:2788        ASString = "SYprivate";2789        break;2790      //  <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]2791      case LangAS::cuda_device:2792        ASString = "CUdevice";2793        break;2794      case LangAS::cuda_constant:2795        ASString = "CUconstant";2796        break;2797      case LangAS::cuda_shared:2798        ASString = "CUshared";2799        break;2800      //  <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]2801      case LangAS::ptr32_sptr:2802        ASString = "ptr32_sptr";2803        break;2804      case LangAS::ptr32_uptr:2805        // For z/OS, there are no special mangling rules applied to the ptr322806        // qualifier. Ex: void foo(int * __ptr32 p) -> _Z3f2Pi. The mangling for2807        // "p" is treated the same as a regular integer pointer.2808        if (!getASTContext().getTargetInfo().getTriple().isOSzOS())2809          ASString = "ptr32_uptr";2810        break;2811      case LangAS::ptr64:2812        ASString = "ptr64";2813        break;2814      }2815    }2816    if (!ASString.empty())2817      mangleVendorQualifier(ASString);2818  }2819 2820  // The ARC ownership qualifiers start with underscores.2821  // Objective-C ARC Extension:2822  //2823  //   <type> ::= U "__strong"2824  //   <type> ::= U "__weak"2825  //   <type> ::= U "__autoreleasing"2826  //2827  // Note: we emit __weak first to preserve the order as2828  // required by the Itanium ABI.2829  if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)2830    mangleVendorQualifier("__weak");2831 2832  // __unaligned (from -fms-extensions)2833  if (Quals.hasUnaligned())2834    mangleVendorQualifier("__unaligned");2835 2836  // __ptrauth.  Note that this is parameterized.2837  if (PointerAuthQualifier PtrAuth = Quals.getPointerAuth()) {2838    mangleVendorQualifier("__ptrauth");2839    // For now, since we only allow non-dependent arguments, we can just2840    // inline the mangling of those arguments as literals.  We treat the2841    // key and extra-discriminator arguments as 'unsigned int' and the2842    // address-discriminated argument as 'bool'.2843    Out << "I"2844           "Lj"2845        << PtrAuth.getKey()2846        << "E"2847           "Lb"2848        << unsigned(PtrAuth.isAddressDiscriminated())2849        << "E"2850           "Lj"2851        << PtrAuth.getExtraDiscriminator()2852        << "E"2853           "E";2854  }2855 2856  // Remaining ARC ownership qualifiers.2857  switch (Quals.getObjCLifetime()) {2858  case Qualifiers::OCL_None:2859    break;2860 2861  case Qualifiers::OCL_Weak:2862    // Do nothing as we already handled this case above.2863    break;2864 2865  case Qualifiers::OCL_Strong:2866    mangleVendorQualifier("__strong");2867    break;2868 2869  case Qualifiers::OCL_Autoreleasing:2870    mangleVendorQualifier("__autoreleasing");2871    break;2872 2873  case Qualifiers::OCL_ExplicitNone:2874    // The __unsafe_unretained qualifier is *not* mangled, so that2875    // __unsafe_unretained types in ARC produce the same manglings as the2876    // equivalent (but, naturally, unqualified) types in non-ARC, providing2877    // better ABI compatibility.2878    //2879    // It's safe to do this because unqualified 'id' won't show up2880    // in any type signatures that need to be mangled.2881    break;2882  }2883 2884  // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const2885  if (Quals.hasRestrict())2886    Out << 'r';2887  if (Quals.hasVolatile())2888    Out << 'V';2889  if (Quals.hasConst())2890    Out << 'K';2891}2892 2893void CXXNameMangler::mangleVendorQualifier(StringRef name) {2894  Out << 'U' << name.size() << name;2895}2896 2897void CXXNameMangler::mangleVendorType(StringRef name) {2898  Out << 'u' << name.size() << name;2899}2900 2901void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {2902  // <ref-qualifier> ::= R                # lvalue reference2903  //                 ::= O                # rvalue-reference2904  switch (RefQualifier) {2905  case RQ_None:2906    break;2907 2908  case RQ_LValue:2909    Out << 'R';2910    break;2911 2912  case RQ_RValue:2913    Out << 'O';2914    break;2915  }2916}2917 2918void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {2919  Context.mangleObjCMethodNameAsSourceName(MD, Out);2920}2921 2922static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,2923                                ASTContext &Ctx) {2924  if (Quals)2925    return true;2926  if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))2927    return true;2928  if (Ty->isOpenCLSpecificType())2929    return true;2930  // From Clang 18.0 we correctly treat SVE types as substitution candidates.2931  if (Ty->isSVESizelessBuiltinType() &&2932      Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)2933    return true;2934  if (Ty->isBuiltinType())2935    return false;2936  // Through to Clang 6.0, we accidentally treated undeduced auto types as2937  // substitution candidates.2938  if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&2939      isa<AutoType>(Ty))2940    return false;2941  // A placeholder type for class template deduction is substitutable with2942  // its corresponding template name; this is handled specially when mangling2943  // the type.2944  if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())2945    if (DeducedTST->getDeducedType().isNull())2946      return false;2947  return true;2948}2949 2950void CXXNameMangler::mangleType(QualType T) {2951  // If our type is instantiation-dependent but not dependent, we mangle2952  // it as it was written in the source, removing any top-level sugar.2953  // Otherwise, use the canonical type.2954  //2955  // FIXME: This is an approximation of the instantiation-dependent name2956  // mangling rules, since we should really be using the type as written and2957  // augmented via semantic analysis (i.e., with implicit conversions and2958  // default template arguments) for any instantiation-dependent type.2959  // Unfortunately, that requires several changes to our AST:2960  //   - Instantiation-dependent TemplateSpecializationTypes will need to be2961  //     uniqued, so that we can handle substitutions properly2962  //   - Default template arguments will need to be represented in the2963  //     TemplateSpecializationType, since they need to be mangled even though2964  //     they aren't written.2965  //   - Conversions on non-type template arguments need to be expressed, since2966  //     they can affect the mangling of sizeof/alignof.2967  //2968  // FIXME: This is wrong when mapping to the canonical type for a dependent2969  // type discards instantiation-dependent portions of the type, such as for:2970  //2971  //   template<typename T, int N> void f(T (&)[sizeof(N)]);2972  //   template<typename T> void f(T() throw(typename T::type)); (pre-C++17)2973  //2974  // It's also wrong in the opposite direction when instantiation-dependent,2975  // canonically-equivalent types differ in some irrelevant portion of inner2976  // type sugar. In such cases, we fail to form correct substitutions, eg:2977  //2978  //   template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));2979  //2980  // We should instead canonicalize the non-instantiation-dependent parts,2981  // regardless of whether the type as a whole is dependent or instantiation2982  // dependent.2983  if (!T->isInstantiationDependentType() || T->isDependentType())2984    T = T.getCanonicalType();2985  else {2986    // Desugar any types that are purely sugar.2987    do {2988      // Don't desugar through template specialization types that aren't2989      // type aliases. We need to mangle the template arguments as written.2990      if (const TemplateSpecializationType *TST2991                                      = dyn_cast<TemplateSpecializationType>(T))2992        if (!TST->isTypeAlias())2993          break;2994 2995      // FIXME: We presumably shouldn't strip off ElaboratedTypes with2996      // instantation-dependent qualifiers. See2997      // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.2998 2999      QualType Desugared3000        = T.getSingleStepDesugaredType(Context.getASTContext());3001      if (Desugared == T)3002        break;3003 3004      T = Desugared;3005    } while (true);3006  }3007  SplitQualType split = T.split();3008  Qualifiers quals = split.Quals;3009  const Type *ty = split.Ty;3010 3011  bool isSubstitutable =3012    isTypeSubstitutable(quals, ty, Context.getASTContext());3013  if (isSubstitutable && mangleSubstitution(T))3014    return;3015 3016  // If we're mangling a qualified array type, push the qualifiers to3017  // the element type.3018  if (quals && isa<ArrayType>(T)) {3019    ty = Context.getASTContext().getAsArrayType(T);3020    quals = Qualifiers();3021 3022    // Note that we don't update T: we want to add the3023    // substitution at the original type.3024  }3025 3026  if (quals || ty->isDependentAddressSpaceType()) {3027    if (const DependentAddressSpaceType *DAST =3028        dyn_cast<DependentAddressSpaceType>(ty)) {3029      SplitQualType splitDAST = DAST->getPointeeType().split();3030      mangleQualifiers(splitDAST.Quals, DAST);3031      mangleType(QualType(splitDAST.Ty, 0));3032    } else {3033      mangleQualifiers(quals);3034 3035      // Recurse:  even if the qualified type isn't yet substitutable,3036      // the unqualified type might be.3037      mangleType(QualType(ty, 0));3038    }3039  } else {3040    switch (ty->getTypeClass()) {3041#define ABSTRACT_TYPE(CLASS, PARENT)3042#define NON_CANONICAL_TYPE(CLASS, PARENT) \3043    case Type::CLASS: \3044      llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \3045      return;3046#define TYPE(CLASS, PARENT) \3047    case Type::CLASS: \3048      mangleType(static_cast<const CLASS##Type*>(ty)); \3049      break;3050#include "clang/AST/TypeNodes.inc"3051    }3052  }3053 3054  // Add the substitution.3055  if (isSubstitutable)3056    addSubstitution(T);3057}3058 3059void CXXNameMangler::mangleCXXRecordDecl(const CXXRecordDecl *Record,3060                                         bool SuppressSubstitution) {3061  if (mangleSubstitution(Record))3062    return;3063  mangleName(Record);3064  if (SuppressSubstitution)3065    return;3066  addSubstitution(Record);3067}3068 3069void CXXNameMangler::mangleType(const BuiltinType *T) {3070  //  <type>         ::= <builtin-type>3071  //  <builtin-type> ::= v  # void3072  //                 ::= w  # wchar_t3073  //                 ::= b  # bool3074  //                 ::= c  # char3075  //                 ::= a  # signed char3076  //                 ::= h  # unsigned char3077  //                 ::= s  # short3078  //                 ::= t  # unsigned short3079  //                 ::= i  # int3080  //                 ::= j  # unsigned int3081  //                 ::= l  # long3082  //                 ::= m  # unsigned long3083  //                 ::= x  # long long, __int643084  //                 ::= y  # unsigned long long, __int643085  //                 ::= n  # __int1283086  //                 ::= o  # unsigned __int1283087  //                 ::= f  # float3088  //                 ::= d  # double3089  //                 ::= e  # long double, __float803090  //                 ::= g  # __float1283091  //                 ::= g  # __ibm1283092  // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)3093  // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)3094  // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)3095  //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)3096  //                 ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);3097  //                 ::= Di # char32_t3098  //                 ::= Ds # char16_t3099  //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))3100  //                 ::= [DS] DA  # N1169 fixed-point [_Sat] T _Accum3101  //                 ::= [DS] DR  # N1169 fixed-point [_Sat] T _Fract3102  //                 ::= u <source-name>    # vendor extended type3103  //3104  //  <fixed-point-size>3105  //                 ::= s # short3106  //                 ::= t # unsigned short3107  //                 ::= i # plain3108  //                 ::= j # unsigned3109  //                 ::= l # long3110  //                 ::= m # unsigned long3111  std::string type_name;3112  // Normalize integer types as vendor extended types:3113  // u<length>i<type size>3114  // u<length>u<type size>3115  if (NormalizeIntegers && T->isInteger()) {3116    if (T->isSignedInteger()) {3117      switch (getASTContext().getTypeSize(T)) {3118      case 8:3119        // Pick a representative for each integer size in the substitution3120        // dictionary. (Its actual defined size is not relevant.)3121        if (mangleSubstitution(BuiltinType::SChar))3122          break;3123        Out << "u2i8";3124        addSubstitution(BuiltinType::SChar);3125        break;3126      case 16:3127        if (mangleSubstitution(BuiltinType::Short))3128          break;3129        Out << "u3i16";3130        addSubstitution(BuiltinType::Short);3131        break;3132      case 32:3133        if (mangleSubstitution(BuiltinType::Int))3134          break;3135        Out << "u3i32";3136        addSubstitution(BuiltinType::Int);3137        break;3138      case 64:3139        if (mangleSubstitution(BuiltinType::Long))3140          break;3141        Out << "u3i64";3142        addSubstitution(BuiltinType::Long);3143        break;3144      case 128:3145        if (mangleSubstitution(BuiltinType::Int128))3146          break;3147        Out << "u4i128";3148        addSubstitution(BuiltinType::Int128);3149        break;3150      default:3151        llvm_unreachable("Unknown integer size for normalization");3152      }3153    } else {3154      switch (getASTContext().getTypeSize(T)) {3155      case 8:3156        if (mangleSubstitution(BuiltinType::UChar))3157          break;3158        Out << "u2u8";3159        addSubstitution(BuiltinType::UChar);3160        break;3161      case 16:3162        if (mangleSubstitution(BuiltinType::UShort))3163          break;3164        Out << "u3u16";3165        addSubstitution(BuiltinType::UShort);3166        break;3167      case 32:3168        if (mangleSubstitution(BuiltinType::UInt))3169          break;3170        Out << "u3u32";3171        addSubstitution(BuiltinType::UInt);3172        break;3173      case 64:3174        if (mangleSubstitution(BuiltinType::ULong))3175          break;3176        Out << "u3u64";3177        addSubstitution(BuiltinType::ULong);3178        break;3179      case 128:3180        if (mangleSubstitution(BuiltinType::UInt128))3181          break;3182        Out << "u4u128";3183        addSubstitution(BuiltinType::UInt128);3184        break;3185      default:3186        llvm_unreachable("Unknown integer size for normalization");3187      }3188    }3189    return;3190  }3191  switch (T->getKind()) {3192  case BuiltinType::Void:3193    Out << 'v';3194    break;3195  case BuiltinType::Bool:3196    Out << 'b';3197    break;3198  case BuiltinType::Char_U:3199  case BuiltinType::Char_S:3200    Out << 'c';3201    break;3202  case BuiltinType::UChar:3203    Out << 'h';3204    break;3205  case BuiltinType::UShort:3206    Out << 't';3207    break;3208  case BuiltinType::UInt:3209    Out << 'j';3210    break;3211  case BuiltinType::ULong:3212    Out << 'm';3213    break;3214  case BuiltinType::ULongLong:3215    Out << 'y';3216    break;3217  case BuiltinType::UInt128:3218    Out << 'o';3219    break;3220  case BuiltinType::SChar:3221    Out << 'a';3222    break;3223  case BuiltinType::WChar_S:3224  case BuiltinType::WChar_U:3225    Out << 'w';3226    break;3227  case BuiltinType::Char8:3228    Out << "Du";3229    break;3230  case BuiltinType::Char16:3231    Out << "Ds";3232    break;3233  case BuiltinType::Char32:3234    Out << "Di";3235    break;3236  case BuiltinType::Short:3237    Out << 's';3238    break;3239  case BuiltinType::Int:3240    Out << 'i';3241    break;3242  case BuiltinType::Long:3243    Out << 'l';3244    break;3245  case BuiltinType::LongLong:3246    Out << 'x';3247    break;3248  case BuiltinType::Int128:3249    Out << 'n';3250    break;3251  case BuiltinType::Float16:3252    Out << "DF16_";3253    break;3254  case BuiltinType::ShortAccum:3255    Out << "DAs";3256    break;3257  case BuiltinType::Accum:3258    Out << "DAi";3259    break;3260  case BuiltinType::LongAccum:3261    Out << "DAl";3262    break;3263  case BuiltinType::UShortAccum:3264    Out << "DAt";3265    break;3266  case BuiltinType::UAccum:3267    Out << "DAj";3268    break;3269  case BuiltinType::ULongAccum:3270    Out << "DAm";3271    break;3272  case BuiltinType::ShortFract:3273    Out << "DRs";3274    break;3275  case BuiltinType::Fract:3276    Out << "DRi";3277    break;3278  case BuiltinType::LongFract:3279    Out << "DRl";3280    break;3281  case BuiltinType::UShortFract:3282    Out << "DRt";3283    break;3284  case BuiltinType::UFract:3285    Out << "DRj";3286    break;3287  case BuiltinType::ULongFract:3288    Out << "DRm";3289    break;3290  case BuiltinType::SatShortAccum:3291    Out << "DSDAs";3292    break;3293  case BuiltinType::SatAccum:3294    Out << "DSDAi";3295    break;3296  case BuiltinType::SatLongAccum:3297    Out << "DSDAl";3298    break;3299  case BuiltinType::SatUShortAccum:3300    Out << "DSDAt";3301    break;3302  case BuiltinType::SatUAccum:3303    Out << "DSDAj";3304    break;3305  case BuiltinType::SatULongAccum:3306    Out << "DSDAm";3307    break;3308  case BuiltinType::SatShortFract:3309    Out << "DSDRs";3310    break;3311  case BuiltinType::SatFract:3312    Out << "DSDRi";3313    break;3314  case BuiltinType::SatLongFract:3315    Out << "DSDRl";3316    break;3317  case BuiltinType::SatUShortFract:3318    Out << "DSDRt";3319    break;3320  case BuiltinType::SatUFract:3321    Out << "DSDRj";3322    break;3323  case BuiltinType::SatULongFract:3324    Out << "DSDRm";3325    break;3326  case BuiltinType::Half:3327    Out << "Dh";3328    break;3329  case BuiltinType::Float:3330    Out << 'f';3331    break;3332  case BuiltinType::Double:3333    Out << 'd';3334    break;3335  case BuiltinType::LongDouble: {3336    const TargetInfo *TI =3337        getASTContext().getLangOpts().OpenMP &&3338                getASTContext().getLangOpts().OpenMPIsTargetDevice3339            ? getASTContext().getAuxTargetInfo()3340            : &getASTContext().getTargetInfo();3341    Out << TI->getLongDoubleMangling();3342    break;3343  }3344  case BuiltinType::Float128: {3345    const TargetInfo *TI =3346        getASTContext().getLangOpts().OpenMP &&3347                getASTContext().getLangOpts().OpenMPIsTargetDevice3348            ? getASTContext().getAuxTargetInfo()3349            : &getASTContext().getTargetInfo();3350    Out << TI->getFloat128Mangling();3351    break;3352  }3353  case BuiltinType::BFloat16: {3354    const TargetInfo *TI =3355        ((getASTContext().getLangOpts().OpenMP &&3356          getASTContext().getLangOpts().OpenMPIsTargetDevice) ||3357         getASTContext().getLangOpts().SYCLIsDevice)3358            ? getASTContext().getAuxTargetInfo()3359            : &getASTContext().getTargetInfo();3360    Out << TI->getBFloat16Mangling();3361    break;3362  }3363  case BuiltinType::Ibm128: {3364    const TargetInfo *TI = &getASTContext().getTargetInfo();3365    Out << TI->getIbm128Mangling();3366    break;3367  }3368  case BuiltinType::NullPtr:3369    Out << "Dn";3370    break;3371 3372#define BUILTIN_TYPE(Id, SingletonId)3373#define PLACEHOLDER_TYPE(Id, SingletonId) \3374  case BuiltinType::Id:3375#include "clang/AST/BuiltinTypes.def"3376  case BuiltinType::Dependent:3377    if (!NullOut)3378      llvm_unreachable("mangling a placeholder type");3379    break;3380  case BuiltinType::ObjCId:3381    Out << "11objc_object";3382    break;3383  case BuiltinType::ObjCClass:3384    Out << "10objc_class";3385    break;3386  case BuiltinType::ObjCSel:3387    Out << "13objc_selector";3388    break;3389#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \3390  case BuiltinType::Id: \3391    type_name = "ocl_" #ImgType "_" #Suffix; \3392    Out << type_name.size() << type_name; \3393    break;3394#include "clang/Basic/OpenCLImageTypes.def"3395  case BuiltinType::OCLSampler:3396    Out << "11ocl_sampler";3397    break;3398  case BuiltinType::OCLEvent:3399    Out << "9ocl_event";3400    break;3401  case BuiltinType::OCLClkEvent:3402    Out << "12ocl_clkevent";3403    break;3404  case BuiltinType::OCLQueue:3405    Out << "9ocl_queue";3406    break;3407  case BuiltinType::OCLReserveID:3408    Out << "13ocl_reserveid";3409    break;3410#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \3411  case BuiltinType::Id: \3412    type_name = "ocl_" #ExtType; \3413    Out << type_name.size() << type_name; \3414    break;3415#include "clang/Basic/OpenCLExtensionTypes.def"3416  // The SVE types are effectively target-specific.  The mangling scheme3417  // is defined in the appendices to the Procedure Call Standard for the3418  // Arm Architecture.3419#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId)                    \3420  case BuiltinType::Id:                                                        \3421    if (T->getKind() == BuiltinType::SveBFloat16 &&                            \3422        isCompatibleWith(LangOptions::ClangABI::Ver17)) {                      \3423      /* Prior to Clang 18.0 we used this incorrect mangled name */            \3424      mangleVendorType("__SVBFloat16_t");                                      \3425    } else {                                                                   \3426      type_name = #MangledName;                                                \3427      Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \3428    }                                                                          \3429    break;3430#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId)                 \3431  case BuiltinType::Id:                                                        \3432    type_name = #MangledName;                                                  \3433    Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name;   \3434    break;3435#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId)                    \3436  case BuiltinType::Id:                                                        \3437    type_name = #MangledName;                                                  \3438    Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name;   \3439    break;3440#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits)              \3441  case BuiltinType::Id:                                                        \3442    type_name = #MangledName;                                                  \3443    Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name;   \3444    break;3445#include "clang/Basic/AArch64ACLETypes.def"3446#define PPC_VECTOR_TYPE(Name, Id, Size)                                        \3447  case BuiltinType::Id:                                                        \3448    mangleVendorType(#Name);                                                   \3449    break;3450#include "clang/Basic/PPCTypes.def"3451    // TODO: Check the mangling scheme for RISC-V V.3452#define RVV_TYPE(Name, Id, SingletonId)                                        \3453  case BuiltinType::Id:                                                        \3454    mangleVendorType(Name);                                                    \3455    break;3456#include "clang/Basic/RISCVVTypes.def"3457#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS)          \3458  case BuiltinType::Id:                                                        \3459    mangleVendorType(MangledName);                                             \3460    break;3461#include "clang/Basic/WebAssemblyReferenceTypes.def"3462#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align)                       \3463  case BuiltinType::Id:                                                        \3464    mangleVendorType(Name);                                                    \3465    break;3466#include "clang/Basic/AMDGPUTypes.def"3467#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId)                            \3468  case BuiltinType::Id:                                                        \3469    mangleVendorType(#Name);                                                   \3470    break;3471#include "clang/Basic/HLSLIntangibleTypes.def"3472  }3473}3474 3475StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {3476  switch (CC) {3477  case CC_C:3478    return "";3479 3480  case CC_X86VectorCall:3481  case CC_X86Pascal:3482  case CC_X86RegCall:3483  case CC_AAPCS:3484  case CC_AAPCS_VFP:3485  case CC_AArch64VectorCall:3486  case CC_AArch64SVEPCS:3487  case CC_IntelOclBicc:3488  case CC_SpirFunction:3489  case CC_DeviceKernel:3490  case CC_PreserveMost:3491  case CC_PreserveAll:3492  case CC_M68kRTD:3493  case CC_PreserveNone:3494  case CC_RISCVVectorCall:3495#define CC_VLS_CASE(ABI_VLEN) case CC_RISCVVLSCall_##ABI_VLEN:3496    CC_VLS_CASE(32)3497    CC_VLS_CASE(64)3498    CC_VLS_CASE(128)3499    CC_VLS_CASE(256)3500    CC_VLS_CASE(512)3501    CC_VLS_CASE(1024)3502    CC_VLS_CASE(2048)3503    CC_VLS_CASE(4096)3504    CC_VLS_CASE(8192)3505    CC_VLS_CASE(16384)3506    CC_VLS_CASE(32768)3507    CC_VLS_CASE(65536)3508#undef CC_VLS_CASE3509    // FIXME: we should be mangling all of the above.3510    return "";3511 3512  case CC_X86ThisCall:3513    // FIXME: To match mingw GCC, thiscall should only be mangled in when it is3514    // used explicitly. At this point, we don't have that much information in3515    // the AST, since clang tends to bake the convention into the canonical3516    // function type. thiscall only rarely used explicitly, so don't mangle it3517    // for now.3518    return "";3519 3520  case CC_X86StdCall:3521    return "stdcall";3522  case CC_X86FastCall:3523    return "fastcall";3524  case CC_X86_64SysV:3525    return "sysv_abi";3526  case CC_Win64:3527    return "ms_abi";3528  case CC_Swift:3529    return "swiftcall";3530  case CC_SwiftAsync:3531    return "swiftasynccall";3532  }3533  llvm_unreachable("bad calling convention");3534}3535 3536void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {3537  // Fast path.3538  if (T->getExtInfo() == FunctionType::ExtInfo())3539    return;3540 3541  // Vendor-specific qualifiers are emitted in reverse alphabetical order.3542  // This will get more complicated in the future if we mangle other3543  // things here; but for now, since we mangle ns_returns_retained as3544  // a qualifier on the result type, we can get away with this:3545  StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());3546  if (!CCQualifier.empty())3547    mangleVendorQualifier(CCQualifier);3548 3549  // FIXME: regparm3550  // FIXME: noreturn3551}3552 3553enum class AAPCSBitmaskSME : unsigned {3554  ArmStreamingBit = 1 << 0,3555  ArmStreamingCompatibleBit = 1 << 1,3556  ArmAgnosticSMEZAStateBit = 1 << 2,3557  ZA_Shift = 3,3558  ZT0_Shift = 6,3559  NoState = 0b000,3560  ArmIn = 0b001,3561  ArmOut = 0b010,3562  ArmInOut = 0b011,3563  ArmPreserves = 0b100,3564  LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ArmPreserves << ZT0_Shift)3565};3566 3567static AAPCSBitmaskSME encodeAAPCSZAState(unsigned SMEAttrs) {3568  switch (SMEAttrs) {3569  case FunctionType::ARM_None:3570    return AAPCSBitmaskSME::NoState;3571  case FunctionType::ARM_In:3572    return AAPCSBitmaskSME::ArmIn;3573  case FunctionType::ARM_Out:3574    return AAPCSBitmaskSME::ArmOut;3575  case FunctionType::ARM_InOut:3576    return AAPCSBitmaskSME::ArmInOut;3577  case FunctionType::ARM_Preserves:3578    return AAPCSBitmaskSME::ArmPreserves;3579  default:3580    llvm_unreachable("Unrecognised SME attribute");3581  }3582}3583 3584// The mangling scheme for function types which have SME attributes is3585// implemented as a "pseudo" template:3586//3587//   '__SME_ATTRS<<normal_function_type>, <sme_state>>'3588//3589// Combining the function type with a bitmask representing the streaming and ZA3590// properties of the function's interface.3591//3592// Mangling of SME keywords is described in more detail in the AArch64 ACLE:3593// https://github.com/ARM-software/acle/blob/main/main/acle.md#c-mangling-of-sme-keywords3594//3595void CXXNameMangler::mangleSMEAttrs(unsigned SMEAttrs) {3596  if (!SMEAttrs)3597    return;3598 3599  AAPCSBitmaskSME Bitmask = AAPCSBitmaskSME(0);3600  if (SMEAttrs & FunctionType::SME_PStateSMEnabledMask)3601    Bitmask |= AAPCSBitmaskSME::ArmStreamingBit;3602  else if (SMEAttrs & FunctionType::SME_PStateSMCompatibleMask)3603    Bitmask |= AAPCSBitmaskSME::ArmStreamingCompatibleBit;3604 3605  if (SMEAttrs & FunctionType::SME_AgnosticZAStateMask)3606    Bitmask |= AAPCSBitmaskSME::ArmAgnosticSMEZAStateBit;3607  else {3608    Bitmask |= encodeAAPCSZAState(FunctionType::getArmZAState(SMEAttrs))3609               << AAPCSBitmaskSME::ZA_Shift;3610 3611    Bitmask |= encodeAAPCSZAState(FunctionType::getArmZT0State(SMEAttrs))3612               << AAPCSBitmaskSME::ZT0_Shift;3613  }3614 3615  Out << "Lj" << static_cast<unsigned>(Bitmask) << "EE";3616}3617 3618void3619CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {3620  // Vendor-specific qualifiers are emitted in reverse alphabetical order.3621 3622  // Note that these are *not* substitution candidates.  Demanglers might3623  // have trouble with this if the parameter type is fully substituted.3624 3625  switch (PI.getABI()) {3626  case ParameterABI::Ordinary:3627    break;3628 3629  // HLSL parameter mangling.3630  case ParameterABI::HLSLOut:3631  case ParameterABI::HLSLInOut:3632    mangleVendorQualifier(getParameterABISpelling(PI.getABI()));3633    break;3634 3635  // All of these start with "swift", so they come before "ns_consumed".3636  case ParameterABI::SwiftContext:3637  case ParameterABI::SwiftAsyncContext:3638  case ParameterABI::SwiftErrorResult:3639  case ParameterABI::SwiftIndirectResult:3640    mangleVendorQualifier(getParameterABISpelling(PI.getABI()));3641    break;3642  }3643 3644  if (PI.isConsumed())3645    mangleVendorQualifier("ns_consumed");3646 3647  if (PI.isNoEscape())3648    mangleVendorQualifier("noescape");3649}3650 3651// <type>          ::= <function-type>3652// <function-type> ::= [<CV-qualifiers>] F [Y]3653//                      <bare-function-type> [<ref-qualifier>] E3654void CXXNameMangler::mangleType(const FunctionProtoType *T) {3655  unsigned SMEAttrs = T->getAArch64SMEAttributes();3656 3657  if (SMEAttrs)3658    Out << "11__SME_ATTRSI";3659 3660  mangleExtFunctionInfo(T);3661 3662  // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,3663  // e.g. "const" in "int (A::*)() const".3664  mangleQualifiers(T->getMethodQuals());3665 3666  // Mangle instantiation-dependent exception-specification, if present,3667  // per cxx-abi-dev proposal on 2016-10-11.3668  if (T->hasInstantiationDependentExceptionSpec()) {3669    if (isComputedNoexcept(T->getExceptionSpecType())) {3670      Out << "DO";3671      mangleExpression(T->getNoexceptExpr());3672      Out << "E";3673    } else {3674      assert(T->getExceptionSpecType() == EST_Dynamic);3675      Out << "Dw";3676      for (auto ExceptTy : T->exceptions())3677        mangleType(ExceptTy);3678      Out << "E";3679    }3680  } else if (T->isNothrow()) {3681    Out << "Do";3682  }3683 3684  Out << 'F';3685 3686  // FIXME: We don't have enough information in the AST to produce the 'Y'3687  // encoding for extern "C" function types.3688  mangleBareFunctionType(T, /*MangleReturnType=*/true);3689 3690  // Mangle the ref-qualifier, if present.3691  mangleRefQualifier(T->getRefQualifier());3692 3693  Out << 'E';3694 3695  mangleSMEAttrs(SMEAttrs);3696}3697 3698void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {3699  // Function types without prototypes can arise when mangling a function type3700  // within an overloadable function in C. We mangle these as the absence of any3701  // parameter types (not even an empty parameter list).3702  Out << 'F';3703 3704  FunctionTypeDepthState saved = FunctionTypeDepth.push();3705 3706  FunctionTypeDepth.enterResultType();3707  mangleType(T->getReturnType());3708  FunctionTypeDepth.leaveResultType();3709 3710  FunctionTypeDepth.pop(saved);3711  Out << 'E';3712}3713 3714void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,3715                                            bool MangleReturnType,3716                                            const FunctionDecl *FD) {3717  // Record that we're in a function type.  See mangleFunctionParam3718  // for details on what we're trying to achieve here.3719  FunctionTypeDepthState saved = FunctionTypeDepth.push();3720 3721  // <bare-function-type> ::= <signature type>+3722  if (MangleReturnType) {3723    FunctionTypeDepth.enterResultType();3724 3725    // Mangle ns_returns_retained as an order-sensitive qualifier here.3726    if (Proto->getExtInfo().getProducesResult() && FD == nullptr)3727      mangleVendorQualifier("ns_returns_retained");3728 3729    // Mangle the return type without any direct ARC ownership qualifiers.3730    QualType ReturnTy = Proto->getReturnType();3731    if (ReturnTy.getObjCLifetime()) {3732      auto SplitReturnTy = ReturnTy.split();3733      SplitReturnTy.Quals.removeObjCLifetime();3734      ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);3735    }3736    mangleType(ReturnTy);3737 3738    FunctionTypeDepth.leaveResultType();3739  }3740 3741  if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {3742    //   <builtin-type> ::= v   # void3743    Out << 'v';3744  } else {3745    assert(!FD || FD->getNumParams() == Proto->getNumParams());3746    for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {3747      // Mangle extended parameter info as order-sensitive qualifiers here.3748      if (Proto->hasExtParameterInfos() && FD == nullptr) {3749        mangleExtParameterInfo(Proto->getExtParameterInfo(I));3750      }3751 3752      // Mangle the type.3753      QualType ParamTy = Proto->getParamType(I);3754      mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));3755 3756      if (FD) {3757        if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {3758          // Attr can only take 1 character, so we can hardcode the length3759          // below.3760          assert(Attr->getType() <= 9 && Attr->getType() >= 0);3761          if (Attr->isDynamic())3762            Out << "U25pass_dynamic_object_size" << Attr->getType();3763          else3764            Out << "U17pass_object_size" << Attr->getType();3765        }3766      }3767    }3768 3769    // <builtin-type>      ::= z  # ellipsis3770    if (Proto->isVariadic())3771      Out << 'z';3772  }3773 3774  if (FD) {3775    FunctionTypeDepth.enterResultType();3776    mangleRequiresClause(FD->getTrailingRequiresClause().ConstraintExpr);3777  }3778 3779  FunctionTypeDepth.pop(saved);3780}3781 3782// <type>            ::= <class-enum-type>3783// <class-enum-type> ::= <name>3784void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {3785  mangleName(T->getDecl());3786}3787 3788// <type>            ::= <class-enum-type>3789// <class-enum-type> ::= <name>3790void CXXNameMangler::mangleType(const EnumType *T) {3791  mangleType(static_cast<const TagType*>(T));3792}3793void CXXNameMangler::mangleType(const RecordType *T) {3794  mangleType(static_cast<const TagType*>(T));3795}3796void CXXNameMangler::mangleType(const TagType *T) {3797  mangleName(T->getDecl()->getDefinitionOrSelf());3798}3799 3800// <type>       ::= <array-type>3801// <array-type> ::= A <positive dimension number> _ <element type>3802//              ::= A [<dimension expression>] _ <element type>3803void CXXNameMangler::mangleType(const ConstantArrayType *T) {3804  Out << 'A' << T->getSize() << '_';3805  mangleType(T->getElementType());3806}3807void CXXNameMangler::mangleType(const VariableArrayType *T) {3808  Out << 'A';3809  // decayed vla types (size 0) will just be skipped.3810  if (T->getSizeExpr())3811    mangleExpression(T->getSizeExpr());3812  Out << '_';3813  mangleType(T->getElementType());3814}3815void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {3816  Out << 'A';3817  // A DependentSizedArrayType might not have size expression as below3818  //3819  // template<int ...N> int arr[] = {N...};3820  if (T->getSizeExpr())3821    mangleExpression(T->getSizeExpr());3822  Out << '_';3823  mangleType(T->getElementType());3824}3825void CXXNameMangler::mangleType(const IncompleteArrayType *T) {3826  Out << "A_";3827  mangleType(T->getElementType());3828}3829 3830// <type>                   ::= <pointer-to-member-type>3831// <pointer-to-member-type> ::= M <class type> <member type>3832void CXXNameMangler::mangleType(const MemberPointerType *T) {3833  Out << 'M';3834  if (auto *RD = T->getMostRecentCXXRecordDecl())3835    mangleCXXRecordDecl(RD);3836  else3837    mangleType(QualType(T->getQualifier().getAsType(), 0));3838  QualType PointeeType = T->getPointeeType();3839  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {3840    mangleType(FPT);3841 3842    // Itanium C++ ABI 5.1.8:3843    //3844    //   The type of a non-static member function is considered to be different,3845    //   for the purposes of substitution, from the type of a namespace-scope or3846    //   static member function whose type appears similar. The types of two3847    //   non-static member functions are considered to be different, for the3848    //   purposes of substitution, if the functions are members of different3849    //   classes. In other words, for the purposes of substitution, the class of3850    //   which the function is a member is considered part of the type of3851    //   function.3852 3853    // Given that we already substitute member function pointers as a3854    // whole, the net effect of this rule is just to unconditionally3855    // suppress substitution on the function type in a member pointer.3856    // We increment the SeqID here to emulate adding an entry to the3857    // substitution table.3858    ++SeqID;3859  } else3860    mangleType(PointeeType);3861}3862 3863// <type>           ::= <template-param>3864void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {3865  mangleTemplateParameter(T->getDepth(), T->getIndex());3866}3867 3868// <type>           ::= <template-param>3869void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {3870  // FIXME: not clear how to mangle this!3871  // template <class T...> class A {3872  //   template <class U...> void foo(T(*)(U) x...);3873  // };3874  Out << "_SUBSTPACK_";3875}3876 3877void CXXNameMangler::mangleType(const SubstBuiltinTemplatePackType *T) {3878  // FIXME: not clear how to mangle this!3879  // template <class T...> class A {3880  //   template <class U...> void foo(__builtin_dedup_pack<T...>(*)(U) x...);3881  // };3882  Out << "_SUBSTBUILTINPACK_";3883}3884 3885// <type> ::= P <type>   # pointer-to3886void CXXNameMangler::mangleType(const PointerType *T) {3887  Out << 'P';3888  mangleType(T->getPointeeType());3889}3890void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {3891  Out << 'P';3892  mangleType(T->getPointeeType());3893}3894 3895// <type> ::= R <type>   # reference-to3896void CXXNameMangler::mangleType(const LValueReferenceType *T) {3897  Out << 'R';3898  mangleType(T->getPointeeType());3899}3900 3901// <type> ::= O <type>   # rvalue reference-to (C++0x)3902void CXXNameMangler::mangleType(const RValueReferenceType *T) {3903  Out << 'O';3904  mangleType(T->getPointeeType());3905}3906 3907// <type> ::= C <type>   # complex pair (C 2000)3908void CXXNameMangler::mangleType(const ComplexType *T) {3909  Out << 'C';3910  mangleType(T->getElementType());3911}3912 3913// ARM's ABI for Neon vector types specifies that they should be mangled as3914// if they are structs (to match ARM's initial implementation).  The3915// vector type must be one of the special types predefined by ARM.3916void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {3917  QualType EltType = T->getElementType();3918  assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");3919  const char *EltName = nullptr;3920  if (T->getVectorKind() == VectorKind::NeonPoly) {3921    switch (cast<BuiltinType>(EltType)->getKind()) {3922    case BuiltinType::SChar:3923    case BuiltinType::UChar:3924      EltName = "poly8_t";3925      break;3926    case BuiltinType::Short:3927    case BuiltinType::UShort:3928      EltName = "poly16_t";3929      break;3930    case BuiltinType::LongLong:3931    case BuiltinType::ULongLong:3932      EltName = "poly64_t";3933      break;3934    default: llvm_unreachable("unexpected Neon polynomial vector element type");3935    }3936  } else {3937    switch (cast<BuiltinType>(EltType)->getKind()) {3938    case BuiltinType::SChar:     EltName = "int8_t"; break;3939    case BuiltinType::UChar:     EltName = "uint8_t"; break;3940    case BuiltinType::Short:     EltName = "int16_t"; break;3941    case BuiltinType::UShort:    EltName = "uint16_t"; break;3942    case BuiltinType::Int:       EltName = "int32_t"; break;3943    case BuiltinType::UInt:      EltName = "uint32_t"; break;3944    case BuiltinType::LongLong:  EltName = "int64_t"; break;3945    case BuiltinType::ULongLong: EltName = "uint64_t"; break;3946    case BuiltinType::Double:    EltName = "float64_t"; break;3947    case BuiltinType::Float:     EltName = "float32_t"; break;3948    case BuiltinType::Half:      EltName = "float16_t"; break;3949    case BuiltinType::BFloat16:  EltName = "bfloat16_t"; break;3950    case BuiltinType::MFloat8:3951      EltName = "mfloat8_t";3952      break;3953    default:3954      llvm_unreachable("unexpected Neon vector element type");3955    }3956  }3957  const char *BaseName = nullptr;3958  unsigned BitSize = (T->getNumElements() *3959                      getASTContext().getTypeSize(EltType));3960  if (BitSize == 64)3961    BaseName = "__simd64_";3962  else {3963    assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");3964    BaseName = "__simd128_";3965  }3966  Out << strlen(BaseName) + strlen(EltName);3967  Out << BaseName << EltName;3968}3969 3970void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {3971  DiagnosticsEngine &Diags = Context.getDiags();3972  unsigned DiagID = Diags.getCustomDiagID(3973      DiagnosticsEngine::Error,3974      "cannot mangle this dependent neon vector type yet");3975  Diags.Report(T->getAttributeLoc(), DiagID);3976}3977 3978static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {3979  switch (EltType->getKind()) {3980  case BuiltinType::SChar:3981    return "Int8";3982  case BuiltinType::Short:3983    return "Int16";3984  case BuiltinType::Int:3985    return "Int32";3986  case BuiltinType::Long:3987  case BuiltinType::LongLong:3988    return "Int64";3989  case BuiltinType::UChar:3990    return "Uint8";3991  case BuiltinType::UShort:3992    return "Uint16";3993  case BuiltinType::UInt:3994    return "Uint32";3995  case BuiltinType::ULong:3996  case BuiltinType::ULongLong:3997    return "Uint64";3998  case BuiltinType::Half:3999    return "Float16";4000  case BuiltinType::Float:4001    return "Float32";4002  case BuiltinType::Double:4003    return "Float64";4004  case BuiltinType::BFloat16:4005    return "Bfloat16";4006  case BuiltinType::MFloat8:4007    return "Mfloat8";4008  default:4009    llvm_unreachable("Unexpected vector element base type");4010  }4011}4012 4013// AArch64's ABI for Neon vector types specifies that they should be mangled as4014// the equivalent internal name. The vector type must be one of the special4015// types predefined by ARM.4016void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {4017  QualType EltType = T->getElementType();4018  assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");4019  unsigned BitSize =4020      (T->getNumElements() * getASTContext().getTypeSize(EltType));4021  (void)BitSize; // Silence warning.4022 4023  assert((BitSize == 64 || BitSize == 128) &&4024         "Neon vector type not 64 or 128 bits");4025 4026  StringRef EltName;4027  if (T->getVectorKind() == VectorKind::NeonPoly) {4028    switch (cast<BuiltinType>(EltType)->getKind()) {4029    case BuiltinType::UChar:4030      EltName = "Poly8";4031      break;4032    case BuiltinType::UShort:4033      EltName = "Poly16";4034      break;4035    case BuiltinType::ULong:4036    case BuiltinType::ULongLong:4037      EltName = "Poly64";4038      break;4039    default:4040      llvm_unreachable("unexpected Neon polynomial vector element type");4041    }4042  } else4043    EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));4044 4045  std::string TypeName =4046      ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();4047  Out << TypeName.length() << TypeName;4048}4049void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {4050  DiagnosticsEngine &Diags = Context.getDiags();4051  unsigned DiagID = Diags.getCustomDiagID(4052      DiagnosticsEngine::Error,4053      "cannot mangle this dependent neon vector type yet");4054  Diags.Report(T->getAttributeLoc(), DiagID);4055}4056 4057// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types4058// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS644059// type as the sizeless variants.4060//4061// The mangling scheme for VLS types is implemented as a "pseudo" template:4062//4063//   '__SVE_VLS<<type>, <vector length>>'4064//4065// Combining the existing SVE type and a specific vector length (in bits).4066// For example:4067//4068//   typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));4069//4070// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:4071//4072//   "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"4073//4074//   i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE4075//4076// The latest ACLE specification (00bet5) does not contain details of this4077// mangling scheme, it will be specified in the next revision. The mangling4078// scheme is otherwise defined in the appendices to the Procedure Call Standard4079// for the Arm Architecture, see4080// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling4081void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {4082  assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||4083          T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&4084         "expected fixed-length SVE vector!");4085 4086  QualType EltType = T->getElementType();4087  assert(EltType->isBuiltinType() &&4088         "expected builtin type for fixed-length SVE vector!");4089 4090  StringRef TypeName;4091  switch (cast<BuiltinType>(EltType)->getKind()) {4092  case BuiltinType::SChar:4093    TypeName = "__SVInt8_t";4094    break;4095  case BuiltinType::UChar: {4096    if (T->getVectorKind() == VectorKind::SveFixedLengthData)4097      TypeName = "__SVUint8_t";4098    else4099      TypeName = "__SVBool_t";4100    break;4101  }4102  case BuiltinType::Short:4103    TypeName = "__SVInt16_t";4104    break;4105  case BuiltinType::UShort:4106    TypeName = "__SVUint16_t";4107    break;4108  case BuiltinType::Int:4109    TypeName = "__SVInt32_t";4110    break;4111  case BuiltinType::UInt:4112    TypeName = "__SVUint32_t";4113    break;4114  case BuiltinType::Long:4115    TypeName = "__SVInt64_t";4116    break;4117  case BuiltinType::ULong:4118    TypeName = "__SVUint64_t";4119    break;4120  case BuiltinType::Half:4121    TypeName = "__SVFloat16_t";4122    break;4123  case BuiltinType::Float:4124    TypeName = "__SVFloat32_t";4125    break;4126  case BuiltinType::Double:4127    TypeName = "__SVFloat64_t";4128    break;4129  case BuiltinType::BFloat16:4130    TypeName = "__SVBfloat16_t";4131    break;4132  default:4133    llvm_unreachable("unexpected element type for fixed-length SVE vector!");4134  }4135 4136  unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;4137 4138  if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)4139    VecSizeInBits *= 8;4140 4141  Out << "9__SVE_VLSI";4142  mangleVendorType(TypeName);4143  Out << "Lj" << VecSizeInBits << "EE";4144}4145 4146void CXXNameMangler::mangleAArch64FixedSveVectorType(4147    const DependentVectorType *T) {4148  DiagnosticsEngine &Diags = Context.getDiags();4149  unsigned DiagID = Diags.getCustomDiagID(4150      DiagnosticsEngine::Error,4151      "cannot mangle this dependent fixed-length SVE vector type yet");4152  Diags.Report(T->getAttributeLoc(), DiagID);4153}4154 4155void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {4156  assert((T->getVectorKind() == VectorKind::RVVFixedLengthData ||4157          T->getVectorKind() == VectorKind::RVVFixedLengthMask ||4158          T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||4159          T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||4160          T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) &&4161         "expected fixed-length RVV vector!");4162 4163  QualType EltType = T->getElementType();4164  assert(EltType->isBuiltinType() &&4165         "expected builtin type for fixed-length RVV vector!");4166 4167  SmallString<20> TypeNameStr;4168  llvm::raw_svector_ostream TypeNameOS(TypeNameStr);4169  TypeNameOS << "__rvv_";4170  switch (cast<BuiltinType>(EltType)->getKind()) {4171  case BuiltinType::SChar:4172    TypeNameOS << "int8";4173    break;4174  case BuiltinType::UChar:4175    if (T->getVectorKind() == VectorKind::RVVFixedLengthData)4176      TypeNameOS << "uint8";4177    else4178      TypeNameOS << "bool";4179    break;4180  case BuiltinType::Short:4181    TypeNameOS << "int16";4182    break;4183  case BuiltinType::UShort:4184    TypeNameOS << "uint16";4185    break;4186  case BuiltinType::Int:4187    TypeNameOS << "int32";4188    break;4189  case BuiltinType::UInt:4190    TypeNameOS << "uint32";4191    break;4192  case BuiltinType::Long:4193    TypeNameOS << "int64";4194    break;4195  case BuiltinType::ULong:4196    TypeNameOS << "uint64";4197    break;4198  case BuiltinType::Float16:4199    TypeNameOS << "float16";4200    break;4201  case BuiltinType::Float:4202    TypeNameOS << "float32";4203    break;4204  case BuiltinType::Double:4205    TypeNameOS << "float64";4206    break;4207  default:4208    llvm_unreachable("unexpected element type for fixed-length RVV vector!");4209  }4210 4211  unsigned VecSizeInBits;4212  switch (T->getVectorKind()) {4213  case VectorKind::RVVFixedLengthMask_1:4214    VecSizeInBits = 1;4215    break;4216  case VectorKind::RVVFixedLengthMask_2:4217    VecSizeInBits = 2;4218    break;4219  case VectorKind::RVVFixedLengthMask_4:4220    VecSizeInBits = 4;4221    break;4222  default:4223    VecSizeInBits = getASTContext().getTypeInfo(T).Width;4224    break;4225  }4226 4227  // Apend the LMUL suffix.4228  auto VScale = getASTContext().getTargetInfo().getVScaleRange(4229      getASTContext().getLangOpts(),4230      TargetInfo::ArmStreamingKind::NotStreaming);4231  unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;4232 4233  if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {4234    TypeNameOS << 'm';4235    if (VecSizeInBits >= VLen)4236      TypeNameOS << (VecSizeInBits / VLen);4237    else4238      TypeNameOS << 'f' << (VLen / VecSizeInBits);4239  } else {4240    TypeNameOS << (VLen / VecSizeInBits);4241  }4242  TypeNameOS << "_t";4243 4244  Out << "9__RVV_VLSI";4245  mangleVendorType(TypeNameStr);4246  Out << "Lj" << VecSizeInBits << "EE";4247}4248 4249void CXXNameMangler::mangleRISCVFixedRVVVectorType(4250    const DependentVectorType *T) {4251  DiagnosticsEngine &Diags = Context.getDiags();4252  unsigned DiagID = Diags.getCustomDiagID(4253      DiagnosticsEngine::Error,4254      "cannot mangle this dependent fixed-length RVV vector type yet");4255  Diags.Report(T->getAttributeLoc(), DiagID);4256}4257 4258// GNU extension: vector types4259// <type>                  ::= <vector-type>4260// <vector-type>           ::= Dv <positive dimension number> _4261//                                    <extended element type>4262//                         ::= Dv [<dimension expression>] _ <element type>4263// <extended element type> ::= <element type>4264//                         ::= p # AltiVec vector pixel4265//                         ::= b # Altivec vector bool4266void CXXNameMangler::mangleType(const VectorType *T) {4267  if ((T->getVectorKind() == VectorKind::Neon ||4268       T->getVectorKind() == VectorKind::NeonPoly)) {4269    llvm::Triple Target = getASTContext().getTargetInfo().getTriple();4270    llvm::Triple::ArchType Arch =4271        getASTContext().getTargetInfo().getTriple().getArch();4272    if ((Arch == llvm::Triple::aarch64 ||4273         Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())4274      mangleAArch64NeonVectorType(T);4275    else4276      mangleNeonVectorType(T);4277    return;4278  } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||4279             T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {4280    mangleAArch64FixedSveVectorType(T);4281    return;4282  } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData ||4283             T->getVectorKind() == VectorKind::RVVFixedLengthMask ||4284             T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||4285             T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||4286             T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {4287    mangleRISCVFixedRVVVectorType(T);4288    return;4289  }4290  Out << "Dv" << T->getNumElements() << '_';4291  if (T->getVectorKind() == VectorKind::AltiVecPixel)4292    Out << 'p';4293  else if (T->getVectorKind() == VectorKind::AltiVecBool)4294    Out << 'b';4295  else4296    mangleType(T->getElementType());4297}4298 4299void CXXNameMangler::mangleType(const DependentVectorType *T) {4300  if ((T->getVectorKind() == VectorKind::Neon ||4301       T->getVectorKind() == VectorKind::NeonPoly)) {4302    llvm::Triple Target = getASTContext().getTargetInfo().getTriple();4303    llvm::Triple::ArchType Arch =4304        getASTContext().getTargetInfo().getTriple().getArch();4305    if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&4306        !Target.isOSDarwin())4307      mangleAArch64NeonVectorType(T);4308    else4309      mangleNeonVectorType(T);4310    return;4311  } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||4312             T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {4313    mangleAArch64FixedSveVectorType(T);4314    return;4315  } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {4316    mangleRISCVFixedRVVVectorType(T);4317    return;4318  }4319 4320  Out << "Dv";4321  mangleExpression(T->getSizeExpr());4322  Out << '_';4323  if (T->getVectorKind() == VectorKind::AltiVecPixel)4324    Out << 'p';4325  else if (T->getVectorKind() == VectorKind::AltiVecBool)4326    Out << 'b';4327  else4328    mangleType(T->getElementType());4329}4330 4331void CXXNameMangler::mangleType(const ExtVectorType *T) {4332  mangleType(static_cast<const VectorType*>(T));4333}4334void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {4335  Out << "Dv";4336  mangleExpression(T->getSizeExpr());4337  Out << '_';4338  mangleType(T->getElementType());4339}4340 4341void CXXNameMangler::mangleType(const ConstantMatrixType *T) {4342  // Mangle matrix types as a vendor extended type:4343  // u<Len>matrix_typeI<Rows><Columns><element type>E4344 4345  mangleVendorType("matrix_type");4346 4347  Out << "I";4348  auto &ASTCtx = getASTContext();4349  unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());4350  llvm::APSInt Rows(BitWidth);4351  Rows = T->getNumRows();4352  mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);4353  llvm::APSInt Columns(BitWidth);4354  Columns = T->getNumColumns();4355  mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);4356  mangleType(T->getElementType());4357  Out << "E";4358}4359 4360void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {4361  // Mangle matrix types as a vendor extended type:4362  // u<Len>matrix_typeI<row expr><column expr><element type>E4363  mangleVendorType("matrix_type");4364 4365  Out << "I";4366  mangleTemplateArgExpr(T->getRowExpr());4367  mangleTemplateArgExpr(T->getColumnExpr());4368  mangleType(T->getElementType());4369  Out << "E";4370}4371 4372void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {4373  SplitQualType split = T->getPointeeType().split();4374  mangleQualifiers(split.Quals, T);4375  mangleType(QualType(split.Ty, 0));4376}4377 4378void CXXNameMangler::mangleType(const PackExpansionType *T) {4379  // <type>  ::= Dp <type>          # pack expansion (C++0x)4380  Out << "Dp";4381  mangleType(T->getPattern());4382}4383 4384void CXXNameMangler::mangleType(const PackIndexingType *T) {4385  if (!T->hasSelectedType())4386    mangleType(T->getPattern());4387  else4388    mangleType(T->getSelectedType());4389}4390 4391void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {4392  mangleSourceName(T->getDecl()->getIdentifier());4393}4394 4395void CXXNameMangler::mangleType(const ObjCObjectType *T) {4396  // Treat __kindof as a vendor extended type qualifier.4397  if (T->isKindOfType())4398    Out << "U8__kindof";4399 4400  if (!T->qual_empty()) {4401    // Mangle protocol qualifiers.4402    SmallString<64> QualStr;4403    llvm::raw_svector_ostream QualOS(QualStr);4404    QualOS << "objcproto";4405    for (const auto *I : T->quals()) {4406      StringRef name = I->getName();4407      QualOS << name.size() << name;4408    }4409    mangleVendorQualifier(QualStr);4410  }4411 4412  mangleType(T->getBaseType());4413 4414  if (T->isSpecialized()) {4415    // Mangle type arguments as I <type>+ E4416    Out << 'I';4417    for (auto typeArg : T->getTypeArgs())4418      mangleType(typeArg);4419    Out << 'E';4420  }4421}4422 4423void CXXNameMangler::mangleType(const BlockPointerType *T) {4424  Out << "U13block_pointer";4425  mangleType(T->getPointeeType());4426}4427 4428void CXXNameMangler::mangleType(const InjectedClassNameType *T) {4429  // Mangle injected class name types as if the user had written the4430  // specialization out fully.  It may not actually be possible to see4431  // this mangling, though.4432  mangleType(4433      T->getDecl()->getCanonicalTemplateSpecializationType(getASTContext()));4434}4435 4436void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {4437  if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {4438    mangleTemplateName(TD, T->template_arguments());4439  } else {4440    Out << 'N';4441    mangleTemplatePrefix(T->getTemplateName());4442 4443    // FIXME: GCC does not appear to mangle the template arguments when4444    // the template in question is a dependent template name. Should we4445    // emulate that badness?4446    mangleTemplateArgs(T->getTemplateName(), T->template_arguments());4447    Out << 'E';4448  }4449}4450 4451void CXXNameMangler::mangleType(const DependentNameType *T) {4452  // Proposal by cxx-abi-dev, 2014-03-264453  // <class-enum-type> ::= <name>    # non-dependent or dependent type name or4454  //                                 # dependent elaborated type specifier using4455  //                                 # 'typename'4456  //                   ::= Ts <name> # dependent elaborated type specifier using4457  //                                 # 'struct' or 'class'4458  //                   ::= Tu <name> # dependent elaborated type specifier using4459  //                                 # 'union'4460  //                   ::= Te <name> # dependent elaborated type specifier using4461  //                                 # 'enum'4462  switch (T->getKeyword()) {4463  case ElaboratedTypeKeyword::None:4464  case ElaboratedTypeKeyword::Typename:4465    break;4466  case ElaboratedTypeKeyword::Struct:4467  case ElaboratedTypeKeyword::Class:4468  case ElaboratedTypeKeyword::Interface:4469    Out << "Ts";4470    break;4471  case ElaboratedTypeKeyword::Union:4472    Out << "Tu";4473    break;4474  case ElaboratedTypeKeyword::Enum:4475    Out << "Te";4476    break;4477  }4478  // Typename types are always nested4479  Out << 'N';4480  manglePrefix(T->getQualifier());4481  mangleSourceName(T->getIdentifier());4482  Out << 'E';4483}4484 4485void CXXNameMangler::mangleType(const TypeOfType *T) {4486  // FIXME: this is pretty unsatisfactory, but there isn't an obvious4487  // "extension with parameters" mangling.4488  Out << "u6typeof";4489}4490 4491void CXXNameMangler::mangleType(const TypeOfExprType *T) {4492  // FIXME: this is pretty unsatisfactory, but there isn't an obvious4493  // "extension with parameters" mangling.4494  Out << "u6typeof";4495}4496 4497void CXXNameMangler::mangleType(const DecltypeType *T) {4498  Expr *E = T->getUnderlyingExpr();4499 4500  // type ::= Dt <expression> E  # decltype of an id-expression4501  //                             #   or class member access4502  //      ::= DT <expression> E  # decltype of an expression4503 4504  // This purports to be an exhaustive list of id-expressions and4505  // class member accesses.  Note that we do not ignore parentheses;4506  // parentheses change the semantics of decltype for these4507  // expressions (and cause the mangler to use the other form).4508  if (isa<DeclRefExpr>(E) ||4509      isa<MemberExpr>(E) ||4510      isa<UnresolvedLookupExpr>(E) ||4511      isa<DependentScopeDeclRefExpr>(E) ||4512      isa<CXXDependentScopeMemberExpr>(E) ||4513      isa<UnresolvedMemberExpr>(E))4514    Out << "Dt";4515  else4516    Out << "DT";4517  mangleExpression(E);4518  Out << 'E';4519}4520 4521void CXXNameMangler::mangleType(const UnaryTransformType *T) {4522  // If this is dependent, we need to record that. If not, we simply4523  // mangle it as the underlying type since they are equivalent.4524  if (T->isDependentType()) {4525    StringRef BuiltinName;4526    switch (T->getUTTKind()) {4527#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait)                                  \4528  case UnaryTransformType::Enum:                                               \4529    BuiltinName = "__" #Trait;                                                 \4530    break;4531#include "clang/Basic/TransformTypeTraits.def"4532    }4533    mangleVendorType(BuiltinName);4534  }4535 4536  Out << "I";4537  mangleType(T->getBaseType());4538  Out << "E";4539}4540 4541void CXXNameMangler::mangleType(const AutoType *T) {4542  assert(T->getDeducedType().isNull() &&4543         "Deduced AutoType shouldn't be handled here!");4544  assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&4545         "shouldn't need to mangle __auto_type!");4546  // <builtin-type> ::= Da # auto4547  //                ::= Dc # decltype(auto)4548  //                ::= Dk # constrained auto4549  //                ::= DK # constrained decltype(auto)4550  if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {4551    Out << (T->isDecltypeAuto() ? "DK" : "Dk");4552    mangleTypeConstraint(T->getTypeConstraintConcept(),4553                         T->getTypeConstraintArguments());4554  } else {4555    Out << (T->isDecltypeAuto() ? "Dc" : "Da");4556  }4557}4558 4559void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {4560  QualType Deduced = T->getDeducedType();4561  if (!Deduced.isNull())4562    return mangleType(Deduced);4563 4564  TemplateName TN = T->getTemplateName();4565  assert(TN.getAsTemplateDecl() &&4566         "shouldn't form deduced TST unless we know we have a template");4567  mangleType(TN);4568}4569 4570void CXXNameMangler::mangleType(const AtomicType *T) {4571  // <type> ::= U <source-name> <type>  # vendor extended type qualifier4572  // (Until there's a standardized mangling...)4573  Out << "U7_Atomic";4574  mangleType(T->getValueType());4575}4576 4577void CXXNameMangler::mangleType(const PipeType *T) {4578  // Pipe type mangling rules are described in SPIR 2.0 specification4579  // A.1 Data types and A.3 Summary of changes4580  // <type> ::= 8ocl_pipe4581  Out << "8ocl_pipe";4582}4583 4584void CXXNameMangler::mangleType(const BitIntType *T) {4585  // 5.1.5.2 Builtin types4586  // <type> ::= DB <number | instantiation-dependent expression> _4587  //        ::= DU <number | instantiation-dependent expression> _4588  Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";4589}4590 4591void CXXNameMangler::mangleType(const DependentBitIntType *T) {4592  // 5.1.5.2 Builtin types4593  // <type> ::= DB <number | instantiation-dependent expression> _4594  //        ::= DU <number | instantiation-dependent expression> _4595  Out << "D" << (T->isUnsigned() ? "U" : "B");4596  mangleExpression(T->getNumBitsExpr());4597  Out << "_";4598}4599 4600void CXXNameMangler::mangleType(const ArrayParameterType *T) {4601  mangleType(cast<ConstantArrayType>(T));4602}4603 4604void CXXNameMangler::mangleType(const HLSLAttributedResourceType *T) {4605  llvm::SmallString<64> Str("_Res");4606  const HLSLAttributedResourceType::Attributes &Attrs = T->getAttrs();4607  // map resource class to HLSL virtual register letter4608  switch (Attrs.ResourceClass) {4609  case llvm::dxil::ResourceClass::UAV:4610    Str += "_u";4611    break;4612  case llvm::dxil::ResourceClass::SRV:4613    Str += "_t";4614    break;4615  case llvm::dxil::ResourceClass::CBuffer:4616    Str += "_b";4617    break;4618  case llvm::dxil::ResourceClass::Sampler:4619    Str += "_s";4620    break;4621  }4622  if (Attrs.IsROV)4623    Str += "_ROV";4624  if (Attrs.RawBuffer)4625    Str += "_Raw";4626  if (Attrs.IsCounter)4627    Str += "_Counter";4628  if (T->hasContainedType())4629    Str += "_CT";4630  mangleVendorQualifier(Str);4631 4632  if (T->hasContainedType()) {4633    mangleType(T->getContainedType());4634  }4635  mangleType(T->getWrappedType());4636}4637 4638void CXXNameMangler::mangleType(const HLSLInlineSpirvType *T) {4639  SmallString<20> TypeNameStr;4640  llvm::raw_svector_ostream TypeNameOS(TypeNameStr);4641 4642  TypeNameOS << "spirv_type";4643 4644  TypeNameOS << "_" << T->getOpcode();4645  TypeNameOS << "_" << T->getSize();4646  TypeNameOS << "_" << T->getAlignment();4647 4648  mangleVendorType(TypeNameStr);4649 4650  for (auto &Operand : T->getOperands()) {4651    using SpirvOperandKind = SpirvOperand::SpirvOperandKind;4652 4653    switch (Operand.getKind()) {4654    case SpirvOperandKind::ConstantId:4655      mangleVendorQualifier("_Const");4656      mangleIntegerLiteral(Operand.getResultType(),4657                           llvm::APSInt(Operand.getValue()));4658      break;4659    case SpirvOperandKind::Literal:4660      mangleVendorQualifier("_Lit");4661      mangleIntegerLiteral(Context.getASTContext().IntTy,4662                           llvm::APSInt(Operand.getValue()));4663      break;4664    case SpirvOperandKind::TypeId:4665      mangleVendorQualifier("_Type");4666      mangleType(Operand.getResultType());4667      break;4668    default:4669      llvm_unreachable("Invalid SpirvOperand kind");4670      break;4671    }4672    TypeNameOS << Operand.getKind();4673  }4674}4675 4676void CXXNameMangler::mangleIntegerLiteral(QualType T,4677                                          const llvm::APSInt &Value) {4678  //  <expr-primary> ::= L <type> <value number> E # integer literal4679  Out << 'L';4680 4681  mangleType(T);4682  if (T->isBooleanType()) {4683    // Boolean values are encoded as 0/1.4684    Out << (Value.getBoolValue() ? '1' : '0');4685  } else {4686    mangleNumber(Value);4687  }4688  Out << 'E';4689}4690 4691void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {4692  // Ignore member expressions involving anonymous unions.4693  while (const auto *RT = Base->getType()->getAsCanonical<RecordType>()) {4694    if (!RT->getDecl()->isAnonymousStructOrUnion())4695      break;4696    const auto *ME = dyn_cast<MemberExpr>(Base);4697    if (!ME)4698      break;4699    Base = ME->getBase();4700    IsArrow = ME->isArrow();4701  }4702 4703  if (Base->isImplicitCXXThis()) {4704    // Note: GCC mangles member expressions to the implicit 'this' as4705    // *this., whereas we represent them as this->. The Itanium C++ ABI4706    // does not specify anything here, so we follow GCC.4707    Out << "dtdefpT";4708  } else {4709    Out << (IsArrow ? "pt" : "dt");4710    mangleExpression(Base);4711  }4712}4713 4714/// Mangles a member expression.4715void CXXNameMangler::mangleMemberExpr(const Expr *base, bool isArrow,4716                                      NestedNameSpecifier Qualifier,4717                                      NamedDecl *firstQualifierLookup,4718                                      DeclarationName member,4719                                      const TemplateArgumentLoc *TemplateArgs,4720                                      unsigned NumTemplateArgs,4721                                      unsigned arity) {4722  // <expression> ::= dt <expression> <unresolved-name>4723  //              ::= pt <expression> <unresolved-name>4724  if (base)4725    mangleMemberExprBase(base, isArrow);4726  mangleUnresolvedName(Qualifier, member, TemplateArgs, NumTemplateArgs, arity);4727}4728 4729/// Look at the callee of the given call expression and determine if4730/// it's a parenthesized id-expression which would have triggered ADL4731/// otherwise.4732static bool isParenthesizedADLCallee(const CallExpr *call) {4733  const Expr *callee = call->getCallee();4734  const Expr *fn = callee->IgnoreParens();4735 4736  // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,4737  // too, but for those to appear in the callee, it would have to be4738  // parenthesized.4739  if (callee == fn) return false;4740 4741  // Must be an unresolved lookup.4742  const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);4743  if (!lookup) return false;4744 4745  assert(!lookup->requiresADL());4746 4747  // Must be an unqualified lookup.4748  if (lookup->getQualifier()) return false;4749 4750  // Must not have found a class member.  Note that if one is a class4751  // member, they're all class members.4752  if (lookup->getNumDecls() > 0 &&4753      (*lookup->decls_begin())->isCXXClassMember())4754    return false;4755 4756  // Otherwise, ADL would have been triggered.4757  return true;4758}4759 4760void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {4761  const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);4762  Out << CastEncoding;4763  mangleType(ECE->getType());4764  mangleExpression(ECE->getSubExpr());4765}4766 4767void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {4768  if (auto *Syntactic = InitList->getSyntacticForm())4769    InitList = Syntactic;4770  for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)4771    mangleExpression(InitList->getInit(i));4772}4773 4774void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,4775                                       const concepts::Requirement *Req) {4776  using concepts::Requirement;4777 4778  // TODO: We can't mangle the result of a failed substitution. It's not clear4779  // whether we should be mangling the original form prior to any substitution4780  // instead. See https://lists.isocpp.org/core/2023/04/14118.php4781  auto HandleSubstitutionFailure =4782      [&](SourceLocation Loc) {4783        DiagnosticsEngine &Diags = Context.getDiags();4784        unsigned DiagID = Diags.getCustomDiagID(4785            DiagnosticsEngine::Error, "cannot mangle this requires-expression "4786                                      "containing a substitution failure");4787        Diags.Report(Loc, DiagID);4788        Out << 'F';4789      };4790 4791  switch (Req->getKind()) {4792  case Requirement::RK_Type: {4793    const auto *TR = cast<concepts::TypeRequirement>(Req);4794    if (TR->isSubstitutionFailure())4795      return HandleSubstitutionFailure(4796          TR->getSubstitutionDiagnostic()->DiagLoc);4797 4798    Out << 'T';4799    mangleType(TR->getType()->getType());4800    break;4801  }4802 4803  case Requirement::RK_Simple:4804  case Requirement::RK_Compound: {4805    const auto *ER = cast<concepts::ExprRequirement>(Req);4806    if (ER->isExprSubstitutionFailure())4807      return HandleSubstitutionFailure(4808          ER->getExprSubstitutionDiagnostic()->DiagLoc);4809 4810    Out << 'X';4811    mangleExpression(ER->getExpr());4812 4813    if (ER->hasNoexceptRequirement())4814      Out << 'N';4815 4816    if (!ER->getReturnTypeRequirement().isEmpty()) {4817      if (ER->getReturnTypeRequirement().isSubstitutionFailure())4818        return HandleSubstitutionFailure(ER->getReturnTypeRequirement()4819                                             .getSubstitutionDiagnostic()4820                                             ->DiagLoc);4821 4822      Out << 'R';4823      mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());4824    }4825    break;4826  }4827 4828  case Requirement::RK_Nested:4829    const auto *NR = cast<concepts::NestedRequirement>(Req);4830    if (NR->hasInvalidConstraint()) {4831      // FIXME: NestedRequirement should track the location of its requires4832      // keyword.4833      return HandleSubstitutionFailure(RequiresExprLoc);4834    }4835 4836    Out << 'Q';4837    mangleExpression(NR->getConstraintExpr());4838    break;4839  }4840}4841 4842void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,4843                                      bool AsTemplateArg) {4844  // <expression> ::= <unary operator-name> <expression>4845  //              ::= <binary operator-name> <expression> <expression>4846  //              ::= <trinary operator-name> <expression> <expression> <expression>4847  //              ::= cv <type> expression           # conversion with one argument4848  //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments4849  //              ::= dc <type> <expression>         # dynamic_cast<type> (expression)4850  //              ::= sc <type> <expression>         # static_cast<type> (expression)4851  //              ::= cc <type> <expression>         # const_cast<type> (expression)4852  //              ::= rc <type> <expression>         # reinterpret_cast<type> (expression)4853  //              ::= st <type>                      # sizeof (a type)4854  //              ::= at <type>                      # alignof (a type)4855  //              ::= <template-param>4856  //              ::= <function-param>4857  //              ::= fpT                            # 'this' expression (part of <function-param>)4858  //              ::= sr <type> <unqualified-name>                   # dependent name4859  //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id4860  //              ::= ds <expression> <expression>                   # expr.*expr4861  //              ::= sZ <template-param>                            # size of a parameter pack4862  //              ::= sZ <function-param>    # size of a function parameter pack4863  //              ::= u <source-name> <template-arg>* E # vendor extended expression4864  //              ::= <expr-primary>4865  // <expr-primary> ::= L <type> <value number> E    # integer literal4866  //                ::= L <type> <value float> E     # floating literal4867  //                ::= L <type> <string type> E     # string literal4868  //                ::= L <nullptr type> E           # nullptr literal "LDnE"4869  //                ::= L <pointer type> 0 E         # null pointer template argument4870  //                ::= L <type> <real-part float> _ <imag-part float> E    # complex floating point literal (C99); not used by clang4871  //                ::= L <mangled-name> E           # external name4872  QualType ImplicitlyConvertedToType;4873 4874  // A top-level expression that's not <expr-primary> needs to be wrapped in4875  // X...E in a template arg.4876  bool IsPrimaryExpr = true;4877  auto NotPrimaryExpr = [&] {4878    if (AsTemplateArg && IsPrimaryExpr)4879      Out << 'X';4880    IsPrimaryExpr = false;4881  };4882 4883  auto MangleDeclRefExpr = [&](const NamedDecl *D) {4884    switch (D->getKind()) {4885    default:4886      //  <expr-primary> ::= L <mangled-name> E # external name4887      Out << 'L';4888      mangle(D);4889      Out << 'E';4890      break;4891 4892    case Decl::ParmVar:4893      NotPrimaryExpr();4894      mangleFunctionParam(cast<ParmVarDecl>(D));4895      break;4896 4897    case Decl::EnumConstant: {4898      // <expr-primary>4899      const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);4900      mangleIntegerLiteral(ED->getType(), ED->getInitVal());4901      break;4902    }4903 4904    case Decl::NonTypeTemplateParm:4905      NotPrimaryExpr();4906      const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);4907      mangleTemplateParameter(PD->getDepth(), PD->getIndex());4908      break;4909    }4910  };4911 4912  // 'goto recurse' is used when handling a simple "unwrapping" node which4913  // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need4914  // to be preserved.4915recurse:4916  switch (E->getStmtClass()) {4917  case Expr::NoStmtClass:4918#define ABSTRACT_STMT(Type)4919#define EXPR(Type, Base)4920#define STMT(Type, Base) \4921  case Expr::Type##Class:4922#include "clang/AST/StmtNodes.inc"4923    // fallthrough4924 4925  // These all can only appear in local or variable-initialization4926  // contexts and so should never appear in a mangling.4927  case Expr::AddrLabelExprClass:4928  case Expr::DesignatedInitUpdateExprClass:4929  case Expr::ImplicitValueInitExprClass:4930  case Expr::ArrayInitLoopExprClass:4931  case Expr::ArrayInitIndexExprClass:4932  case Expr::NoInitExprClass:4933  case Expr::ParenListExprClass:4934  case Expr::MSPropertyRefExprClass:4935  case Expr::MSPropertySubscriptExprClass:4936  case Expr::RecoveryExprClass:4937  case Expr::ArraySectionExprClass:4938  case Expr::OMPArrayShapingExprClass:4939  case Expr::OMPIteratorExprClass:4940  case Expr::CXXInheritedCtorInitExprClass:4941  case Expr::CXXParenListInitExprClass:4942  case Expr::PackIndexingExprClass:4943    llvm_unreachable("unexpected statement kind");4944 4945  case Expr::ConstantExprClass:4946    E = cast<ConstantExpr>(E)->getSubExpr();4947    goto recurse;4948 4949  // FIXME: invent manglings for all these.4950  case Expr::BlockExprClass:4951  case Expr::ChooseExprClass:4952  case Expr::CompoundLiteralExprClass:4953  case Expr::ExtVectorElementExprClass:4954  case Expr::GenericSelectionExprClass:4955  case Expr::ObjCEncodeExprClass:4956  case Expr::ObjCIsaExprClass:4957  case Expr::ObjCIvarRefExprClass:4958  case Expr::ObjCMessageExprClass:4959  case Expr::ObjCPropertyRefExprClass:4960  case Expr::ObjCProtocolExprClass:4961  case Expr::ObjCSelectorExprClass:4962  case Expr::ObjCStringLiteralClass:4963  case Expr::ObjCBoxedExprClass:4964  case Expr::ObjCArrayLiteralClass:4965  case Expr::ObjCDictionaryLiteralClass:4966  case Expr::ObjCSubscriptRefExprClass:4967  case Expr::ObjCIndirectCopyRestoreExprClass:4968  case Expr::ObjCAvailabilityCheckExprClass:4969  case Expr::OffsetOfExprClass:4970  case Expr::PredefinedExprClass:4971  case Expr::ShuffleVectorExprClass:4972  case Expr::ConvertVectorExprClass:4973  case Expr::StmtExprClass:4974  case Expr::ArrayTypeTraitExprClass:4975  case Expr::ExpressionTraitExprClass:4976  case Expr::VAArgExprClass:4977  case Expr::CUDAKernelCallExprClass:4978  case Expr::AsTypeExprClass:4979  case Expr::PseudoObjectExprClass:4980  case Expr::AtomicExprClass:4981  case Expr::SourceLocExprClass:4982  case Expr::EmbedExprClass:4983  case Expr::BuiltinBitCastExprClass: {4984    NotPrimaryExpr();4985    if (!NullOut) {4986      // As bad as this diagnostic is, it's better than crashing.4987      DiagnosticsEngine &Diags = Context.getDiags();4988      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,4989                                       "cannot yet mangle expression type %0");4990      Diags.Report(E->getExprLoc(), DiagID)4991        << E->getStmtClassName() << E->getSourceRange();4992      return;4993    }4994    break;4995  }4996 4997  case Expr::CXXUuidofExprClass: {4998    NotPrimaryExpr();4999    const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);5000    // As of clang 12, uuidof uses the vendor extended expression5001    // mangling. Previously, it used a special-cased nonstandard extension.5002    if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {5003      Out << "u8__uuidof";5004      if (UE->isTypeOperand())5005        mangleType(UE->getTypeOperand(Context.getASTContext()));5006      else5007        mangleTemplateArgExpr(UE->getExprOperand());5008      Out << 'E';5009    } else {5010      if (UE->isTypeOperand()) {5011        QualType UuidT = UE->getTypeOperand(Context.getASTContext());5012        Out << "u8__uuidoft";5013        mangleType(UuidT);5014      } else {5015        Expr *UuidExp = UE->getExprOperand();5016        Out << "u8__uuidofz";5017        mangleExpression(UuidExp);5018      }5019    }5020    break;5021  }5022 5023  // Even gcc-4.5 doesn't mangle this.5024  case Expr::BinaryConditionalOperatorClass: {5025    NotPrimaryExpr();5026    DiagnosticsEngine &Diags = Context.getDiags();5027    unsigned DiagID =5028      Diags.getCustomDiagID(DiagnosticsEngine::Error,5029                "?: operator with omitted middle operand cannot be mangled");5030    Diags.Report(E->getExprLoc(), DiagID)5031      << E->getStmtClassName() << E->getSourceRange();5032    return;5033  }5034 5035  // These are used for internal purposes and cannot be meaningfully mangled.5036  case Expr::OpaqueValueExprClass:5037    llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");5038 5039  case Expr::InitListExprClass: {5040    NotPrimaryExpr();5041    Out << "il";5042    mangleInitListElements(cast<InitListExpr>(E));5043    Out << "E";5044    break;5045  }5046 5047  case Expr::DesignatedInitExprClass: {5048    NotPrimaryExpr();5049    auto *DIE = cast<DesignatedInitExpr>(E);5050    for (const auto &Designator : DIE->designators()) {5051      if (Designator.isFieldDesignator()) {5052        Out << "di";5053        mangleSourceName(Designator.getFieldName());5054      } else if (Designator.isArrayDesignator()) {5055        Out << "dx";5056        mangleExpression(DIE->getArrayIndex(Designator));5057      } else {5058        assert(Designator.isArrayRangeDesignator() &&5059               "unknown designator kind");5060        Out << "dX";5061        mangleExpression(DIE->getArrayRangeStart(Designator));5062        mangleExpression(DIE->getArrayRangeEnd(Designator));5063      }5064    }5065    mangleExpression(DIE->getInit());5066    break;5067  }5068 5069  case Expr::CXXDefaultArgExprClass:5070    E = cast<CXXDefaultArgExpr>(E)->getExpr();5071    goto recurse;5072 5073  case Expr::CXXDefaultInitExprClass:5074    E = cast<CXXDefaultInitExpr>(E)->getExpr();5075    goto recurse;5076 5077  case Expr::CXXStdInitializerListExprClass:5078    E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();5079    goto recurse;5080 5081  case Expr::SubstNonTypeTemplateParmExprClass: {5082    // Mangle a substituted parameter the same way we mangle the template5083    // argument.5084    auto *SNTTPE = cast<SubstNonTypeTemplateParmExpr>(E);5085    if (auto *CE = dyn_cast<ConstantExpr>(SNTTPE->getReplacement())) {5086      // Pull out the constant value and mangle it as a template argument.5087      QualType ParamType = SNTTPE->getParameterType(Context.getASTContext());5088      assert(CE->hasAPValueResult() && "expected the NTTP to have an APValue");5089      mangleValueInTemplateArg(ParamType, CE->getAPValueResult(), false,5090                               /*NeedExactType=*/true);5091      break;5092    }5093    // The remaining cases all happen to be substituted with expressions that5094    // mangle the same as a corresponding template argument anyway.5095    E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();5096    goto recurse;5097  }5098 5099  case Expr::UserDefinedLiteralClass:5100    // We follow g++'s approach of mangling a UDL as a call to the literal5101    // operator.5102  case Expr::CXXMemberCallExprClass: // fallthrough5103  case Expr::CallExprClass: {5104    NotPrimaryExpr();5105    const CallExpr *CE = cast<CallExpr>(E);5106 5107    // <expression> ::= cp <simple-id> <expression>* E5108    // We use this mangling only when the call would use ADL except5109    // for being parenthesized.  Per discussion with David5110    // Vandervoorde, 2011.04.25.5111    if (isParenthesizedADLCallee(CE)) {5112      Out << "cp";5113      // The callee here is a parenthesized UnresolvedLookupExpr with5114      // no qualifier and should always get mangled as a <simple-id>5115      // anyway.5116 5117    // <expression> ::= cl <expression>* E5118    } else {5119      Out << "cl";5120    }5121 5122    unsigned CallArity = CE->getNumArgs();5123    for (const Expr *Arg : CE->arguments())5124      if (isa<PackExpansionExpr>(Arg))5125        CallArity = UnknownArity;5126 5127    mangleExpression(CE->getCallee(), CallArity);5128    for (const Expr *Arg : CE->arguments())5129      mangleExpression(Arg);5130    Out << 'E';5131    break;5132  }5133 5134  case Expr::CXXNewExprClass: {5135    NotPrimaryExpr();5136    const CXXNewExpr *New = cast<CXXNewExpr>(E);5137    if (New->isGlobalNew()) Out << "gs";5138    Out << (New->isArray() ? "na" : "nw");5139    for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),5140           E = New->placement_arg_end(); I != E; ++I)5141      mangleExpression(*I);5142    Out << '_';5143    mangleType(New->getAllocatedType());5144    if (New->hasInitializer()) {5145      if (New->getInitializationStyle() == CXXNewInitializationStyle::Braces)5146        Out << "il";5147      else5148        Out << "pi";5149      const Expr *Init = New->getInitializer();5150      if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {5151        // Directly inline the initializers.5152        for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),5153                                                  E = CCE->arg_end();5154             I != E; ++I)5155          mangleExpression(*I);5156      } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {5157        for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)5158          mangleExpression(PLE->getExpr(i));5159      } else if (New->getInitializationStyle() ==5160                     CXXNewInitializationStyle::Braces &&5161                 isa<InitListExpr>(Init)) {5162        // Only take InitListExprs apart for list-initialization.5163        mangleInitListElements(cast<InitListExpr>(Init));5164      } else5165        mangleExpression(Init);5166    }5167    Out << 'E';5168    break;5169  }5170 5171  case Expr::CXXPseudoDestructorExprClass: {5172    NotPrimaryExpr();5173    const auto *PDE = cast<CXXPseudoDestructorExpr>(E);5174    if (const Expr *Base = PDE->getBase())5175      mangleMemberExprBase(Base, PDE->isArrow());5176    NestedNameSpecifier Qualifier = PDE->getQualifier();5177    if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {5178      if (Qualifier) {5179        mangleUnresolvedPrefix(Qualifier,5180                               /*recursive=*/true);5181        mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());5182        Out << 'E';5183      } else {5184        Out << "sr";5185        if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))5186          Out << 'E';5187      }5188    } else if (Qualifier) {5189      mangleUnresolvedPrefix(Qualifier);5190    }5191    // <base-unresolved-name> ::= dn <destructor-name>5192    Out << "dn";5193    QualType DestroyedType = PDE->getDestroyedType();5194    mangleUnresolvedTypeOrSimpleId(DestroyedType);5195    break;5196  }5197 5198  case Expr::MemberExprClass: {5199    NotPrimaryExpr();5200    const MemberExpr *ME = cast<MemberExpr>(E);5201    mangleMemberExpr(ME->getBase(), ME->isArrow(),5202                     ME->getQualifier(), nullptr,5203                     ME->getMemberDecl()->getDeclName(),5204                     ME->getTemplateArgs(), ME->getNumTemplateArgs(),5205                     Arity);5206    break;5207  }5208 5209  case Expr::UnresolvedMemberExprClass: {5210    NotPrimaryExpr();5211    const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);5212    mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),5213                     ME->isArrow(), ME->getQualifier(), nullptr,5214                     ME->getMemberName(),5215                     ME->getTemplateArgs(), ME->getNumTemplateArgs(),5216                     Arity);5217    break;5218  }5219 5220  case Expr::CXXDependentScopeMemberExprClass: {5221    NotPrimaryExpr();5222    const CXXDependentScopeMemberExpr *ME5223      = cast<CXXDependentScopeMemberExpr>(E);5224    mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),5225                     ME->isArrow(), ME->getQualifier(),5226                     ME->getFirstQualifierFoundInScope(),5227                     ME->getMember(),5228                     ME->getTemplateArgs(), ME->getNumTemplateArgs(),5229                     Arity);5230    break;5231  }5232 5233  case Expr::UnresolvedLookupExprClass: {5234    NotPrimaryExpr();5235    const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);5236    mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),5237                         ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),5238                         Arity);5239    break;5240  }5241 5242  case Expr::CXXUnresolvedConstructExprClass: {5243    NotPrimaryExpr();5244    const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);5245    unsigned N = CE->getNumArgs();5246 5247    if (CE->isListInitialization()) {5248      assert(N == 1 && "unexpected form for list initialization");5249      auto *IL = cast<InitListExpr>(CE->getArg(0));5250      Out << "tl";5251      mangleType(CE->getType());5252      mangleInitListElements(IL);5253      Out << "E";5254      break;5255    }5256 5257    Out << "cv";5258    mangleType(CE->getType());5259    if (N != 1) Out << '_';5260    for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));5261    if (N != 1) Out << 'E';5262    break;5263  }5264 5265  case Expr::CXXConstructExprClass: {5266    // An implicit cast is silent, thus may contain <expr-primary>.5267    const auto *CE = cast<CXXConstructExpr>(E);5268    if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {5269      assert(5270          CE->getNumArgs() >= 1 &&5271          (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&5272          "implicit CXXConstructExpr must have one argument");5273      E = cast<CXXConstructExpr>(E)->getArg(0);5274      goto recurse;5275    }5276    NotPrimaryExpr();5277    Out << "il";5278    for (auto *E : CE->arguments())5279      mangleExpression(E);5280    Out << "E";5281    break;5282  }5283 5284  case Expr::CXXTemporaryObjectExprClass: {5285    NotPrimaryExpr();5286    const auto *CE = cast<CXXTemporaryObjectExpr>(E);5287    unsigned N = CE->getNumArgs();5288    bool List = CE->isListInitialization();5289 5290    if (List)5291      Out << "tl";5292    else5293      Out << "cv";5294    mangleType(CE->getType());5295    if (!List && N != 1)5296      Out << '_';5297    if (CE->isStdInitListInitialization()) {5298      // We implicitly created a std::initializer_list<T> for the first argument5299      // of a constructor of type U in an expression of the form U{a, b, c}.5300      // Strip all the semantic gunk off the initializer list.5301      auto *SILE =5302          cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());5303      auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());5304      mangleInitListElements(ILE);5305    } else {5306      for (auto *E : CE->arguments())5307        mangleExpression(E);5308    }5309    if (List || N != 1)5310      Out << 'E';5311    break;5312  }5313 5314  case Expr::CXXScalarValueInitExprClass:5315    NotPrimaryExpr();5316    Out << "cv";5317    mangleType(E->getType());5318    Out << "_E";5319    break;5320 5321  case Expr::CXXNoexceptExprClass:5322    NotPrimaryExpr();5323    Out << "nx";5324    mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());5325    break;5326 5327  case Expr::UnaryExprOrTypeTraitExprClass: {5328    // Non-instantiation-dependent traits are an <expr-primary> integer literal.5329    const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);5330 5331    if (!SAE->isInstantiationDependent()) {5332      // Itanium C++ ABI:5333      //   If the operand of a sizeof or alignof operator is not5334      //   instantiation-dependent it is encoded as an integer literal5335      //   reflecting the result of the operator.5336      //5337      //   If the result of the operator is implicitly converted to a known5338      //   integer type, that type is used for the literal; otherwise, the type5339      //   of std::size_t or std::ptrdiff_t is used.5340      //5341      // FIXME: We still include the operand in the profile in this case. This5342      // can lead to mangling collisions between function templates that we5343      // consider to be different.5344      QualType T = (ImplicitlyConvertedToType.isNull() ||5345                    !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()5346                                                    : ImplicitlyConvertedToType;5347      llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());5348      mangleIntegerLiteral(T, V);5349      break;5350    }5351 5352    NotPrimaryExpr(); // But otherwise, they are not.5353 5354    auto MangleAlignofSizeofArg = [&] {5355      if (SAE->isArgumentType()) {5356        Out << 't';5357        mangleType(SAE->getArgumentType());5358      } else {5359        Out << 'z';5360        mangleExpression(SAE->getArgumentExpr());5361      }5362    };5363 5364    auto MangleExtensionBuiltin = [&](const UnaryExprOrTypeTraitExpr *E,5365                                      StringRef Name = {}) {5366      if (Name.empty())5367        Name = getTraitSpelling(E->getKind());5368      mangleVendorType(Name);5369      if (SAE->isArgumentType())5370        mangleType(SAE->getArgumentType());5371      else5372        mangleTemplateArgExpr(SAE->getArgumentExpr());5373      Out << 'E';5374    };5375 5376    switch (SAE->getKind()) {5377    case UETT_SizeOf:5378      Out << 's';5379      MangleAlignofSizeofArg();5380      break;5381    case UETT_PreferredAlignOf:5382      // As of clang 12, we mangle __alignof__ differently than alignof. (They5383      // have acted differently since Clang 8, but were previously mangled the5384      // same.)5385      if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {5386        MangleExtensionBuiltin(SAE, "__alignof__");5387        break;5388      }5389      [[fallthrough]];5390    case UETT_AlignOf:5391      Out << 'a';5392      MangleAlignofSizeofArg();5393      break;5394 5395    case UETT_CountOf:5396    case UETT_VectorElements:5397    case UETT_OpenMPRequiredSimdAlign:5398    case UETT_VecStep:5399    case UETT_PtrAuthTypeDiscriminator:5400    case UETT_DataSizeOf: {5401      DiagnosticsEngine &Diags = Context.getDiags();5402      unsigned DiagID = Diags.getCustomDiagID(5403          DiagnosticsEngine::Error, "cannot yet mangle %0 expression");5404      Diags.Report(E->getExprLoc(), DiagID) << getTraitSpelling(SAE->getKind());5405      return;5406    }5407    }5408    break;5409  }5410 5411  case Expr::TypeTraitExprClass: {5412    //  <expression> ::= u <source-name> <template-arg>* E # vendor extension5413    const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);5414    NotPrimaryExpr();5415    llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());5416    mangleVendorType(Spelling);5417    for (TypeSourceInfo *TSI : TTE->getArgs()) {5418      mangleType(TSI->getType());5419    }5420    Out << 'E';5421    break;5422  }5423 5424  case Expr::CXXThrowExprClass: {5425    NotPrimaryExpr();5426    const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);5427    //  <expression> ::= tw <expression>  # throw expression5428    //               ::= tr               # rethrow5429    if (TE->getSubExpr()) {5430      Out << "tw";5431      mangleExpression(TE->getSubExpr());5432    } else {5433      Out << "tr";5434    }5435    break;5436  }5437 5438  case Expr::CXXTypeidExprClass: {5439    NotPrimaryExpr();5440    const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);5441    //  <expression> ::= ti <type>        # typeid (type)5442    //               ::= te <expression>  # typeid (expression)5443    if (TIE->isTypeOperand()) {5444      Out << "ti";5445      mangleType(TIE->getTypeOperand(Context.getASTContext()));5446    } else {5447      Out << "te";5448      mangleExpression(TIE->getExprOperand());5449    }5450    break;5451  }5452 5453  case Expr::CXXDeleteExprClass: {5454    NotPrimaryExpr();5455    const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);5456    //  <expression> ::= [gs] dl <expression>  # [::] delete expr5457    //               ::= [gs] da <expression>  # [::] delete [] expr5458    if (DE->isGlobalDelete()) Out << "gs";5459    Out << (DE->isArrayForm() ? "da" : "dl");5460    mangleExpression(DE->getArgument());5461    break;5462  }5463 5464  case Expr::UnaryOperatorClass: {5465    NotPrimaryExpr();5466    const UnaryOperator *UO = cast<UnaryOperator>(E);5467    mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),5468                       /*Arity=*/1);5469    mangleExpression(UO->getSubExpr());5470    break;5471  }5472 5473  case Expr::ArraySubscriptExprClass: {5474    NotPrimaryExpr();5475    const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);5476 5477    // Array subscript is treated as a syntactically weird form of5478    // binary operator.5479    Out << "ix";5480    mangleExpression(AE->getLHS());5481    mangleExpression(AE->getRHS());5482    break;5483  }5484 5485  case Expr::MatrixSubscriptExprClass: {5486    NotPrimaryExpr();5487    const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);5488    Out << "ixix";5489    mangleExpression(ME->getBase());5490    mangleExpression(ME->getRowIdx());5491    mangleExpression(ME->getColumnIdx());5492    break;5493  }5494 5495  case Expr::CompoundAssignOperatorClass: // fallthrough5496  case Expr::BinaryOperatorClass: {5497    NotPrimaryExpr();5498    const BinaryOperator *BO = cast<BinaryOperator>(E);5499    if (BO->getOpcode() == BO_PtrMemD)5500      Out << "ds";5501    else5502      mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),5503                         /*Arity=*/2);5504    mangleExpression(BO->getLHS());5505    mangleExpression(BO->getRHS());5506    break;5507  }5508 5509  case Expr::CXXRewrittenBinaryOperatorClass: {5510    NotPrimaryExpr();5511    // The mangled form represents the original syntax.5512    CXXRewrittenBinaryOperator::DecomposedForm Decomposed =5513        cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();5514    mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),5515                       /*Arity=*/2);5516    mangleExpression(Decomposed.LHS);5517    mangleExpression(Decomposed.RHS);5518    break;5519  }5520 5521  case Expr::ConditionalOperatorClass: {5522    NotPrimaryExpr();5523    const ConditionalOperator *CO = cast<ConditionalOperator>(E);5524    mangleOperatorName(OO_Conditional, /*Arity=*/3);5525    mangleExpression(CO->getCond());5526    mangleExpression(CO->getLHS(), Arity);5527    mangleExpression(CO->getRHS(), Arity);5528    break;5529  }5530 5531  case Expr::ImplicitCastExprClass: {5532    ImplicitlyConvertedToType = E->getType();5533    E = cast<ImplicitCastExpr>(E)->getSubExpr();5534    goto recurse;5535  }5536 5537  case Expr::ObjCBridgedCastExprClass: {5538    NotPrimaryExpr();5539    // Mangle ownership casts as a vendor extended operator __bridge,5540    // __bridge_transfer, or __bridge_retain.5541    StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();5542    Out << "v1U" << Kind.size() << Kind;5543    mangleCastExpression(E, "cv");5544    break;5545  }5546 5547  case Expr::CStyleCastExprClass:5548    NotPrimaryExpr();5549    mangleCastExpression(E, "cv");5550    break;5551 5552  case Expr::CXXFunctionalCastExprClass: {5553    NotPrimaryExpr();5554    auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();5555    // FIXME: Add isImplicit to CXXConstructExpr.5556    if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))5557      if (CCE->getParenOrBraceRange().isInvalid())5558        Sub = CCE->getArg(0)->IgnoreImplicit();5559    if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))5560      Sub = StdInitList->getSubExpr()->IgnoreImplicit();5561    if (auto *IL = dyn_cast<InitListExpr>(Sub)) {5562      Out << "tl";5563      mangleType(E->getType());5564      mangleInitListElements(IL);5565      Out << "E";5566    } else {5567      mangleCastExpression(E, "cv");5568    }5569    break;5570  }5571 5572  case Expr::CXXStaticCastExprClass:5573    NotPrimaryExpr();5574    mangleCastExpression(E, "sc");5575    break;5576  case Expr::CXXDynamicCastExprClass:5577    NotPrimaryExpr();5578    mangleCastExpression(E, "dc");5579    break;5580  case Expr::CXXReinterpretCastExprClass:5581    NotPrimaryExpr();5582    mangleCastExpression(E, "rc");5583    break;5584  case Expr::CXXConstCastExprClass:5585    NotPrimaryExpr();5586    mangleCastExpression(E, "cc");5587    break;5588  case Expr::CXXAddrspaceCastExprClass:5589    NotPrimaryExpr();5590    mangleCastExpression(E, "ac");5591    break;5592 5593  case Expr::CXXOperatorCallExprClass: {5594    NotPrimaryExpr();5595    const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);5596    unsigned NumArgs = CE->getNumArgs();5597    // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax5598    // (the enclosing MemberExpr covers the syntactic portion).5599    if (CE->getOperator() != OO_Arrow)5600      mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);5601    // Mangle the arguments.5602    for (unsigned i = 0; i != NumArgs; ++i)5603      mangleExpression(CE->getArg(i));5604    break;5605  }5606 5607  case Expr::ParenExprClass:5608    E = cast<ParenExpr>(E)->getSubExpr();5609    goto recurse;5610 5611  case Expr::ConceptSpecializationExprClass: {5612    auto *CSE = cast<ConceptSpecializationExpr>(E);5613    if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {5614      // Clang 17 and before mangled concept-ids as if they resolved to an5615      // entity, meaning that references to enclosing template arguments don't5616      // work.5617      Out << "L_Z";5618      mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());5619      Out << 'E';5620      break;5621    }5622    // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.5623    NotPrimaryExpr();5624    mangleUnresolvedName(5625        CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),5626        CSE->getConceptNameInfo().getName(),5627        CSE->getTemplateArgsAsWritten()->getTemplateArgs(),5628        CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());5629    break;5630  }5631 5632  case Expr::RequiresExprClass: {5633    // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.5634    auto *RE = cast<RequiresExpr>(E);5635    // This is a primary-expression in the C++ grammar, but does not have an5636    // <expr-primary> mangling (starting with 'L').5637    NotPrimaryExpr();5638    if (RE->getLParenLoc().isValid()) {5639      Out << "rQ";5640      FunctionTypeDepthState saved = FunctionTypeDepth.push();5641      if (RE->getLocalParameters().empty()) {5642        Out << 'v';5643      } else {5644        for (ParmVarDecl *Param : RE->getLocalParameters()) {5645          mangleType(Context.getASTContext().getSignatureParameterType(5646              Param->getType()));5647        }5648      }5649      Out << '_';5650 5651      // The rest of the mangling is in the immediate scope of the parameters.5652      FunctionTypeDepth.enterResultType();5653      for (const concepts::Requirement *Req : RE->getRequirements())5654        mangleRequirement(RE->getExprLoc(), Req);5655      FunctionTypeDepth.pop(saved);5656      Out << 'E';5657    } else {5658      Out << "rq";5659      for (const concepts::Requirement *Req : RE->getRequirements())5660        mangleRequirement(RE->getExprLoc(), Req);5661      Out << 'E';5662    }5663    break;5664  }5665 5666  case Expr::DeclRefExprClass:5667    // MangleDeclRefExpr helper handles primary-vs-nonprimary5668    MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());5669    break;5670 5671  case Expr::SubstNonTypeTemplateParmPackExprClass:5672    NotPrimaryExpr();5673    // FIXME: not clear how to mangle this!5674    // template <unsigned N...> class A {5675    //   template <class U...> void foo(U (&x)[N]...);5676    // };5677    Out << "_SUBSTPACK_";5678    break;5679 5680  case Expr::FunctionParmPackExprClass: {5681    NotPrimaryExpr();5682    // FIXME: not clear how to mangle this!5683    const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);5684    Out << "v110_SUBSTPACK";5685    MangleDeclRefExpr(FPPE->getParameterPack());5686    break;5687  }5688 5689  case Expr::DependentScopeDeclRefExprClass: {5690    NotPrimaryExpr();5691    const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);5692    mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),5693                         DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),5694                         Arity);5695    break;5696  }5697 5698  case Expr::CXXBindTemporaryExprClass:5699    E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();5700    goto recurse;5701 5702  case Expr::ExprWithCleanupsClass:5703    E = cast<ExprWithCleanups>(E)->getSubExpr();5704    goto recurse;5705 5706  case Expr::FloatingLiteralClass: {5707    // <expr-primary>5708    const FloatingLiteral *FL = cast<FloatingLiteral>(E);5709    mangleFloatLiteral(FL->getType(), FL->getValue());5710    break;5711  }5712 5713  case Expr::FixedPointLiteralClass:5714    // Currently unimplemented -- might be <expr-primary> in future?5715    mangleFixedPointLiteral();5716    break;5717 5718  case Expr::CharacterLiteralClass:5719    // <expr-primary>5720    Out << 'L';5721    mangleType(E->getType());5722    Out << cast<CharacterLiteral>(E)->getValue();5723    Out << 'E';5724    break;5725 5726  // FIXME. __objc_yes/__objc_no are mangled same as true/false5727  case Expr::ObjCBoolLiteralExprClass:5728    // <expr-primary>5729    Out << "Lb";5730    Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');5731    Out << 'E';5732    break;5733 5734  case Expr::CXXBoolLiteralExprClass:5735    // <expr-primary>5736    Out << "Lb";5737    Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');5738    Out << 'E';5739    break;5740 5741  case Expr::IntegerLiteralClass: {5742    // <expr-primary>5743    llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());5744    if (E->getType()->isSignedIntegerType())5745      Value.setIsSigned(true);5746    mangleIntegerLiteral(E->getType(), Value);5747    break;5748  }5749 5750  case Expr::ImaginaryLiteralClass: {5751    // <expr-primary>5752    const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);5753    // Mangle as if a complex literal.5754    // Proposal from David Vandevoorde, 2010.06.30.5755    Out << 'L';5756    mangleType(E->getType());5757    if (const FloatingLiteral *Imag =5758          dyn_cast<FloatingLiteral>(IE->getSubExpr())) {5759      // Mangle a floating-point zero of the appropriate type.5760      mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));5761      Out << '_';5762      mangleFloat(Imag->getValue());5763    } else {5764      Out << "0_";5765      llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());5766      if (IE->getSubExpr()->getType()->isSignedIntegerType())5767        Value.setIsSigned(true);5768      mangleNumber(Value);5769    }5770    Out << 'E';5771    break;5772  }5773 5774  case Expr::StringLiteralClass: {5775    // <expr-primary>5776    // Revised proposal from David Vandervoorde, 2010.07.15.5777    Out << 'L';5778    assert(isa<ConstantArrayType>(E->getType()));5779    mangleType(E->getType());5780    Out << 'E';5781    break;5782  }5783 5784  case Expr::GNUNullExprClass:5785    // <expr-primary>5786    // Mangle as if an integer literal 0.5787    mangleIntegerLiteral(E->getType(), llvm::APSInt(32));5788    break;5789 5790  case Expr::CXXNullPtrLiteralExprClass: {5791    // <expr-primary>5792    Out << "LDnE";5793    break;5794  }5795 5796  case Expr::LambdaExprClass: {5797    // A lambda-expression can't appear in the signature of an5798    // externally-visible declaration, so there's no standard mangling for5799    // this, but mangling as a literal of the closure type seems reasonable.5800    Out << "L";5801    mangleType(Context.getASTContext().getCanonicalTagType(5802        cast<LambdaExpr>(E)->getLambdaClass()));5803    Out << "E";5804    break;5805  }5806 5807  case Expr::PackExpansionExprClass:5808    NotPrimaryExpr();5809    Out << "sp";5810    mangleExpression(cast<PackExpansionExpr>(E)->getPattern());5811    break;5812 5813  case Expr::SizeOfPackExprClass: {5814    NotPrimaryExpr();5815    auto *SPE = cast<SizeOfPackExpr>(E);5816    if (SPE->isPartiallySubstituted()) {5817      Out << "sP";5818      for (const auto &A : SPE->getPartialArguments())5819        mangleTemplateArg(A, false);5820      Out << "E";5821      break;5822    }5823 5824    Out << "sZ";5825    const NamedDecl *Pack = SPE->getPack();5826    if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))5827      mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());5828    else if (const NonTypeTemplateParmDecl *NTTP5829                = dyn_cast<NonTypeTemplateParmDecl>(Pack))5830      mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());5831    else if (const TemplateTemplateParmDecl *TempTP5832                                    = dyn_cast<TemplateTemplateParmDecl>(Pack))5833      mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());5834    else5835      mangleFunctionParam(cast<ParmVarDecl>(Pack));5836    break;5837  }5838 5839  case Expr::MaterializeTemporaryExprClass:5840    E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();5841    goto recurse;5842 5843  case Expr::CXXFoldExprClass: {5844    NotPrimaryExpr();5845    auto *FE = cast<CXXFoldExpr>(E);5846    if (FE->isLeftFold())5847      Out << (FE->getInit() ? "fL" : "fl");5848    else5849      Out << (FE->getInit() ? "fR" : "fr");5850 5851    if (FE->getOperator() == BO_PtrMemD)5852      Out << "ds";5853    else5854      mangleOperatorName(5855          BinaryOperator::getOverloadedOperator(FE->getOperator()),5856          /*Arity=*/2);5857 5858    if (FE->getLHS())5859      mangleExpression(FE->getLHS());5860    if (FE->getRHS())5861      mangleExpression(FE->getRHS());5862    break;5863  }5864 5865  case Expr::CXXThisExprClass:5866    NotPrimaryExpr();5867    Out << "fpT";5868    break;5869 5870  case Expr::CoawaitExprClass:5871    // FIXME: Propose a non-vendor mangling.5872    NotPrimaryExpr();5873    Out << "v18co_await";5874    mangleExpression(cast<CoawaitExpr>(E)->getOperand());5875    break;5876 5877  case Expr::DependentCoawaitExprClass:5878    // FIXME: Propose a non-vendor mangling.5879    NotPrimaryExpr();5880    Out << "v18co_await";5881    mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());5882    break;5883 5884  case Expr::CoyieldExprClass:5885    // FIXME: Propose a non-vendor mangling.5886    NotPrimaryExpr();5887    Out << "v18co_yield";5888    mangleExpression(cast<CoawaitExpr>(E)->getOperand());5889    break;5890  case Expr::SYCLUniqueStableNameExprClass: {5891    const auto *USN = cast<SYCLUniqueStableNameExpr>(E);5892    NotPrimaryExpr();5893 5894    Out << "u33__builtin_sycl_unique_stable_name";5895    mangleType(USN->getTypeSourceInfo()->getType());5896 5897    Out << "E";5898    break;5899  }5900  case Expr::HLSLOutArgExprClass:5901    llvm_unreachable(5902        "cannot mangle hlsl temporary value; mangling wrong thing?");5903  case Expr::OpenACCAsteriskSizeExprClass: {5904    // We shouldn't ever be able to get here, but diagnose anyway.5905    DiagnosticsEngine &Diags = Context.getDiags();5906    unsigned DiagID = Diags.getCustomDiagID(5907        DiagnosticsEngine::Error,5908        "cannot yet mangle OpenACC Asterisk Size expression");5909    Diags.Report(DiagID);5910    return;5911  }5912  }5913 5914  if (AsTemplateArg && !IsPrimaryExpr)5915    Out << 'E';5916}5917 5918/// Mangle an expression which refers to a parameter variable.5919///5920/// <expression>     ::= <function-param>5921/// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 05922/// <function-param> ::= fp <top-level CV-qualifiers>5923///                      <parameter-2 non-negative number> _ # L == 0, I > 05924/// <function-param> ::= fL <L-1 non-negative number>5925///                      p <top-level CV-qualifiers> _       # L > 0, I == 05926/// <function-param> ::= fL <L-1 non-negative number>5927///                      p <top-level CV-qualifiers>5928///                      <I-1 non-negative number> _         # L > 0, I > 05929///5930/// L is the nesting depth of the parameter, defined as 1 if the5931/// parameter comes from the innermost function prototype scope5932/// enclosing the current context, 2 if from the next enclosing5933/// function prototype scope, and so on, with one special case: if5934/// we've processed the full parameter clause for the innermost5935/// function type, then L is one less.  This definition conveniently5936/// makes it irrelevant whether a function's result type was written5937/// trailing or leading, but is otherwise overly complicated; the5938/// numbering was first designed without considering references to5939/// parameter in locations other than return types, and then the5940/// mangling had to be generalized without changing the existing5941/// manglings.5942///5943/// I is the zero-based index of the parameter within its parameter5944/// declaration clause.  Note that the original ABI document describes5945/// this using 1-based ordinals.5946void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {5947  unsigned parmDepth = parm->getFunctionScopeDepth();5948  unsigned parmIndex = parm->getFunctionScopeIndex();5949 5950  // Compute 'L'.5951  // parmDepth does not include the declaring function prototype.5952  // FunctionTypeDepth does account for that.5953  assert(parmDepth < FunctionTypeDepth.getDepth());5954  unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;5955  if (FunctionTypeDepth.isInResultType())5956    nestingDepth--;5957 5958  if (nestingDepth == 0) {5959    Out << "fp";5960  } else {5961    Out << "fL" << (nestingDepth - 1) << 'p';5962  }5963 5964  // Top-level qualifiers.  We don't have to worry about arrays here,5965  // because parameters declared as arrays should already have been5966  // transformed to have pointer type. FIXME: apparently these don't5967  // get mangled if used as an rvalue of a known non-class type?5968  assert(!parm->getType()->isArrayType()5969         && "parameter's type is still an array type?");5970 5971  if (const DependentAddressSpaceType *DAST =5972      dyn_cast<DependentAddressSpaceType>(parm->getType())) {5973    mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);5974  } else {5975    mangleQualifiers(parm->getType().getQualifiers());5976  }5977 5978  // Parameter index.5979  if (parmIndex != 0) {5980    Out << (parmIndex - 1);5981  }5982  Out << '_';5983}5984 5985void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,5986                                       const CXXRecordDecl *InheritedFrom) {5987  // <ctor-dtor-name> ::= C1  # complete object constructor5988  //                  ::= C2  # base object constructor5989  //                  ::= CI1 <type> # complete inheriting constructor5990  //                  ::= CI2 <type> # base inheriting constructor5991  //5992  // In addition, C5 is a comdat name with C1 and C2 in it.5993  // C4 represents a ctor declaration and is used by debuggers to look up5994  // the various ctor variants.5995  Out << 'C';5996  if (InheritedFrom)5997    Out << 'I';5998  switch (T) {5999  case Ctor_Complete:6000    Out << '1';6001    break;6002  case Ctor_Base:6003    Out << '2';6004    break;6005  case Ctor_Unified:6006    Out << '4';6007    break;6008  case Ctor_Comdat:6009    Out << '5';6010    break;6011  case Ctor_DefaultClosure:6012  case Ctor_CopyingClosure:6013    llvm_unreachable("closure constructors don't exist for the Itanium ABI!");6014  }6015  if (InheritedFrom)6016    mangleName(InheritedFrom);6017}6018 6019void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {6020  // <ctor-dtor-name> ::= D0  # deleting destructor6021  //                  ::= D1  # complete object destructor6022  //                  ::= D2  # base object destructor6023  //6024  // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.6025  // D4 represents a dtor declaration and is used by debuggers to look up6026  // the various dtor variants.6027  switch (T) {6028  case Dtor_Deleting:6029    Out << "D0";6030    break;6031  case Dtor_Complete:6032    Out << "D1";6033    break;6034  case Dtor_Base:6035    Out << "D2";6036    break;6037  case Dtor_Unified:6038    Out << "D4";6039    break;6040  case Dtor_Comdat:6041    Out << "D5";6042    break;6043  }6044}6045 6046// Helper to provide ancillary information on a template used to mangle its6047// arguments.6048struct CXXNameMangler::TemplateArgManglingInfo {6049  const CXXNameMangler &Mangler;6050  TemplateDecl *ResolvedTemplate = nullptr;6051  bool SeenPackExpansionIntoNonPack = false;6052  const NamedDecl *UnresolvedExpandedPack = nullptr;6053 6054  TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN)6055      : Mangler(Mangler) {6056    if (TemplateDecl *TD = TN.getAsTemplateDecl())6057      ResolvedTemplate = TD;6058  }6059 6060  /// Information about how to mangle a template argument.6061  struct Info {6062    /// Do we need to mangle the template argument with an exactly correct type?6063    bool NeedExactType;6064    /// If we need to prefix the mangling with a mangling of the template6065    /// parameter, the corresponding parameter.6066    const NamedDecl *TemplateParameterToMangle;6067  };6068 6069  /// Determine whether the resolved template might be overloaded on its6070  /// template parameter list. If so, the mangling needs to include enough6071  /// information to reconstruct the template parameter list.6072  bool isOverloadable() {6073    // Function templates are generally overloadable. As a special case, a6074    // member function template of a generic lambda is not overloadable.6075    if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(ResolvedTemplate)) {6076      auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());6077      if (!RD || !RD->isGenericLambda())6078        return true;6079    }6080 6081    // All other templates are not overloadable. Partial specializations would6082    // be, but we never mangle them.6083    return false;6084  }6085 6086  /// Determine whether we need to prefix this <template-arg> mangling with a6087  /// <template-param-decl>. This happens if the natural template parameter for6088  /// the argument mangling is not the same as the actual template parameter.6089  bool needToMangleTemplateParam(const NamedDecl *Param,6090                                 const TemplateArgument &Arg) {6091    // For a template type parameter, the natural parameter is 'typename T'.6092    // The actual parameter might be constrained.6093    if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))6094      return TTP->hasTypeConstraint();6095 6096    if (Arg.getKind() == TemplateArgument::Pack) {6097      // For an empty pack, the natural parameter is `typename...`.6098      if (Arg.pack_size() == 0)6099        return true;6100 6101      // For any other pack, we use the first argument to determine the natural6102      // template parameter.6103      return needToMangleTemplateParam(Param, *Arg.pack_begin());6104    }6105 6106    // For a non-type template parameter, the natural parameter is `T V` (for a6107    // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the6108    // type of the argument, which we require to exactly match. If the actual6109    // parameter has a deduced or instantiation-dependent type, it is not6110    // equivalent to the natural parameter.6111    if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))6112      return NTTP->getType()->isInstantiationDependentType() ||6113             NTTP->getType()->getContainedDeducedType();6114 6115    // For a template template parameter, the template-head might differ from6116    // that of the template.6117    auto *TTP = cast<TemplateTemplateParmDecl>(Param);6118    TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern();6119    assert(!ArgTemplateName.getTemplateDeclAndDefaultArgs().second &&6120           "A DeducedTemplateName shouldn't escape partial ordering");6121    const TemplateDecl *ArgTemplate =6122        ArgTemplateName.getAsTemplateDecl(/*IgnoreDeduced=*/true);6123    if (!ArgTemplate)6124      return true;6125 6126    // Mangle the template parameter list of the parameter and argument to see6127    // if they are the same. We can't use Profile for this, because it can't6128    // model the depth difference between parameter and argument and might not6129    // necessarily have the same definition of "identical" that we use here --6130    // that is, same mangling.6131    auto MangleTemplateParamListToString =6132        [&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params,6133            unsigned DepthOffset) {6134          llvm::raw_svector_ostream Stream(Buffer);6135          CXXNameMangler(Mangler.Context, Stream,6136                         WithTemplateDepthOffset{DepthOffset})6137              .mangleTemplateParameterList(Params);6138        };6139    llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead;6140    MangleTemplateParamListToString(ParamTemplateHead,6141                                    TTP->getTemplateParameters(), 0);6142    // Add the depth of the parameter's template parameter list to all6143    // parameters appearing in the argument to make the indexes line up6144    // properly.6145    MangleTemplateParamListToString(ArgTemplateHead,6146                                    ArgTemplate->getTemplateParameters(),6147                                    TTP->getTemplateParameters()->getDepth());6148    return ParamTemplateHead != ArgTemplateHead;6149  }6150 6151  /// Determine information about how this template argument should be mangled.6152  /// This should be called exactly once for each parameter / argument pair, in6153  /// order.6154  Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg) {6155    // We need correct types when the template-name is unresolved or when it6156    // names a template that is able to be overloaded.6157    if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)6158      return {true, nullptr};6159 6160    // Move to the next parameter.6161    const NamedDecl *Param = UnresolvedExpandedPack;6162    if (!Param) {6163      assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&6164             "no parameter for argument");6165      Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);6166 6167      // If we reach a parameter pack whose argument isn't in pack form, that6168      // means Sema couldn't or didn't figure out which arguments belonged to6169      // it, because it contains a pack expansion or because Sema bailed out of6170      // computing parameter / argument correspondence before this point. Track6171      // the pack as the corresponding parameter for all further template6172      // arguments until we hit a pack expansion, at which point we don't know6173      // the correspondence between parameters and arguments at all.6174      if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {6175        UnresolvedExpandedPack = Param;6176      }6177    }6178 6179    // If we encounter a pack argument that is expanded into a non-pack6180    // parameter, we can no longer track parameter / argument correspondence,6181    // and need to use exact types from this point onwards.6182    if (Arg.isPackExpansion() &&6183        (!Param->isParameterPack() || UnresolvedExpandedPack)) {6184      SeenPackExpansionIntoNonPack = true;6185      return {true, nullptr};6186    }6187 6188    // We need exact types for arguments of a template that might be overloaded6189    // on template parameter type.6190    if (isOverloadable())6191      return {true, needToMangleTemplateParam(Param, Arg) ? Param : nullptr};6192 6193    // Otherwise, we only need a correct type if the parameter has a deduced6194    // type.6195    //6196    // Note: for an expanded parameter pack, getType() returns the type prior6197    // to expansion. We could ask for the expanded type with getExpansionType(),6198    // but it doesn't matter because substitution and expansion don't affect6199    // whether a deduced type appears in the type.6200    auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);6201    bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType();6202    return {NeedExactType, nullptr};6203  }6204 6205  /// Determine if we should mangle a requires-clause after the template6206  /// argument list. If so, returns the expression to mangle.6207  const Expr *getTrailingRequiresClauseToMangle() {6208    if (!isOverloadable())6209      return nullptr;6210    return ResolvedTemplate->getTemplateParameters()->getRequiresClause();6211  }6212};6213 6214void CXXNameMangler::mangleTemplateArgs(TemplateName TN,6215                                        const TemplateArgumentLoc *TemplateArgs,6216                                        unsigned NumTemplateArgs) {6217  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E6218  Out << 'I';6219  TemplateArgManglingInfo Info(*this, TN);6220  for (unsigned i = 0; i != NumTemplateArgs; ++i) {6221    mangleTemplateArg(Info, i, TemplateArgs[i].getArgument());6222  }6223  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());6224  Out << 'E';6225}6226 6227void CXXNameMangler::mangleTemplateArgs(TemplateName TN,6228                                        const TemplateArgumentList &AL) {6229  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E6230  Out << 'I';6231  TemplateArgManglingInfo Info(*this, TN);6232  for (unsigned i = 0, e = AL.size(); i != e; ++i) {6233    mangleTemplateArg(Info, i, AL[i]);6234  }6235  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());6236  Out << 'E';6237}6238 6239void CXXNameMangler::mangleTemplateArgs(TemplateName TN,6240                                        ArrayRef<TemplateArgument> Args) {6241  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E6242  Out << 'I';6243  TemplateArgManglingInfo Info(*this, TN);6244  for (unsigned i = 0; i != Args.size(); ++i) {6245    mangleTemplateArg(Info, i, Args[i]);6246  }6247  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());6248  Out << 'E';6249}6250 6251void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info,6252                                       unsigned Index, TemplateArgument A) {6253  TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(Index, A);6254 6255  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.6256  if (ArgInfo.TemplateParameterToMangle &&6257      !isCompatibleWith(LangOptions::ClangABI::Ver17)) {6258    // The template parameter is mangled if the mangling would otherwise be6259    // ambiguous.6260    //6261    // <template-arg> ::= <template-param-decl> <template-arg>6262    //6263    // Clang 17 and before did not do this.6264    mangleTemplateParamDecl(ArgInfo.TemplateParameterToMangle);6265  }6266 6267  mangleTemplateArg(A, ArgInfo.NeedExactType);6268}6269 6270void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {6271  // <template-arg> ::= <type>              # type or template6272  //                ::= X <expression> E    # expression6273  //                ::= <expr-primary>      # simple expressions6274  //                ::= J <template-arg>* E # argument pack6275  if (!A.isInstantiationDependent() || A.isDependent())6276    A = Context.getASTContext().getCanonicalTemplateArgument(A);6277 6278  switch (A.getKind()) {6279  case TemplateArgument::Null:6280    llvm_unreachable("Cannot mangle NULL template argument");6281 6282  case TemplateArgument::Type:6283    mangleType(A.getAsType());6284    break;6285  case TemplateArgument::Template:6286    // This is mangled as <type>.6287    mangleType(A.getAsTemplate());6288    break;6289  case TemplateArgument::TemplateExpansion:6290    // <type>  ::= Dp <type>          # pack expansion (C++0x)6291    Out << "Dp";6292    mangleType(A.getAsTemplateOrTemplatePattern());6293    break;6294  case TemplateArgument::Expression:6295    mangleTemplateArgExpr(A.getAsExpr());6296    break;6297  case TemplateArgument::Integral:6298    mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());6299    break;6300  case TemplateArgument::Declaration: {6301    //  <expr-primary> ::= L <mangled-name> E # external name6302    ValueDecl *D = A.getAsDecl();6303 6304    // Template parameter objects are modeled by reproducing a source form6305    // produced as if by aggregate initialization.6306    if (A.getParamTypeForDecl()->isRecordType()) {6307      auto *TPO = cast<TemplateParamObjectDecl>(D);6308      mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),6309                               TPO->getValue(), /*TopLevel=*/true,6310                               NeedExactType);6311      break;6312    }6313 6314    ASTContext &Ctx = Context.getASTContext();6315    APValue Value;6316    if (D->isCXXInstanceMember())6317      // Simple pointer-to-member with no conversion.6318      Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});6319    else if (D->getType()->isArrayType() &&6320             Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),6321                                A.getParamTypeForDecl()) &&6322             !isCompatibleWith(LangOptions::ClangABI::Ver11))6323      // Build a value corresponding to this implicit array-to-pointer decay.6324      Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),6325                      {APValue::LValuePathEntry::ArrayIndex(0)},6326                      /*OnePastTheEnd=*/false);6327    else6328      // Regular pointer or reference to a declaration.6329      Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),6330                      ArrayRef<APValue::LValuePathEntry>(),6331                      /*OnePastTheEnd=*/false);6332    mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,6333                             NeedExactType);6334    break;6335  }6336  case TemplateArgument::NullPtr: {6337    mangleNullPointer(A.getNullPtrType());6338    break;6339  }6340  case TemplateArgument::StructuralValue:6341    mangleValueInTemplateArg(A.getStructuralValueType(),6342                             A.getAsStructuralValue(),6343                             /*TopLevel=*/true, NeedExactType);6344    break;6345  case TemplateArgument::Pack: {6346    //  <template-arg> ::= J <template-arg>* E6347    Out << 'J';6348    for (const auto &P : A.pack_elements())6349      mangleTemplateArg(P, NeedExactType);6350    Out << 'E';6351  }6352  }6353}6354 6355void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {6356  if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {6357    mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);6358    return;6359  }6360 6361  // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>6362  // correctly in cases where the template argument was6363  // constructed from an expression rather than an already-evaluated6364  // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of6365  // 'Li0E'.6366  //6367  // We did special-case DeclRefExpr to attempt to DTRT for that one6368  // expression-kind, but while doing so, unfortunately handled ParmVarDecl6369  // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of6370  // the proper 'Xfp_E'.6371  E = E->IgnoreParenImpCasts();6372  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {6373    const ValueDecl *D = DRE->getDecl();6374    if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {6375      Out << 'L';6376      mangle(D);6377      Out << 'E';6378      return;6379    }6380  }6381  Out << 'X';6382  mangleExpression(E);6383  Out << 'E';6384}6385 6386/// Determine whether a given value is equivalent to zero-initialization for6387/// the purpose of discarding a trailing portion of a 'tl' mangling.6388///6389/// Note that this is not in general equivalent to determining whether the6390/// value has an all-zeroes bit pattern.6391static bool isZeroInitialized(QualType T, const APValue &V) {6392  // FIXME: mangleValueInTemplateArg has quadratic time complexity in6393  // pathological cases due to using this, but it's a little awkward6394  // to do this in linear time in general.6395  switch (V.getKind()) {6396  case APValue::None:6397  case APValue::Indeterminate:6398  case APValue::AddrLabelDiff:6399    return false;6400 6401  case APValue::Struct: {6402    const CXXRecordDecl *RD = T->getAsCXXRecordDecl();6403    assert(RD && "unexpected type for record value");6404    unsigned I = 0;6405    for (const CXXBaseSpecifier &BS : RD->bases()) {6406      if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))6407        return false;6408      ++I;6409    }6410    I = 0;6411    for (const FieldDecl *FD : RD->fields()) {6412      if (!FD->isUnnamedBitField() &&6413          !isZeroInitialized(FD->getType(), V.getStructField(I)))6414        return false;6415      ++I;6416    }6417    return true;6418  }6419 6420  case APValue::Union: {6421    const CXXRecordDecl *RD = T->getAsCXXRecordDecl();6422    assert(RD && "unexpected type for union value");6423    // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.6424    for (const FieldDecl *FD : RD->fields()) {6425      if (!FD->isUnnamedBitField())6426        return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&6427               isZeroInitialized(FD->getType(), V.getUnionValue());6428    }6429    // If there are no fields (other than unnamed bitfields), the value is6430    // necessarily zero-initialized.6431    return true;6432  }6433 6434  case APValue::Array: {6435    QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);6436    for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)6437      if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))6438        return false;6439    return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());6440  }6441 6442  case APValue::Vector: {6443    const VectorType *VT = T->castAs<VectorType>();6444    for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)6445      if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))6446        return false;6447    return true;6448  }6449 6450  case APValue::Int:6451    return !V.getInt();6452 6453  case APValue::Float:6454    return V.getFloat().isPosZero();6455 6456  case APValue::FixedPoint:6457    return !V.getFixedPoint().getValue();6458 6459  case APValue::ComplexFloat:6460    return V.getComplexFloatReal().isPosZero() &&6461           V.getComplexFloatImag().isPosZero();6462 6463  case APValue::ComplexInt:6464    return !V.getComplexIntReal() && !V.getComplexIntImag();6465 6466  case APValue::LValue:6467    return V.isNullPointer();6468 6469  case APValue::MemberPointer:6470    return !V.getMemberPointerDecl();6471  }6472 6473  llvm_unreachable("Unhandled APValue::ValueKind enum");6474}6475 6476static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {6477  QualType T = LV.getLValueBase().getType();6478  for (APValue::LValuePathEntry E : LV.getLValuePath()) {6479    if (const ArrayType *AT = Ctx.getAsArrayType(T))6480      T = AT->getElementType();6481    else if (const FieldDecl *FD =6482                 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))6483      T = FD->getType();6484    else6485      T = Ctx.getCanonicalTagType(6486          cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));6487  }6488  return T;6489}6490 6491static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,6492                                        DiagnosticsEngine &Diags,6493                                        const FieldDecl *FD) {6494  // According to:6495  // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous6496  // For the purposes of mangling, the name of an anonymous union is considered6497  // to be the name of the first named data member found by a pre-order,6498  // depth-first, declaration-order walk of the data members of the anonymous6499  // union.6500 6501  if (FD->getIdentifier())6502    return FD->getIdentifier();6503 6504  // The only cases where the identifer of a FieldDecl would be blank is if the6505  // field represents an anonymous record type or if it is an unnamed bitfield.6506  // There is no type to descend into in the case of a bitfield, so we can just6507  // return nullptr in that case.6508  if (FD->isBitField())6509    return nullptr;6510  const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();6511 6512  // Consider only the fields in declaration order, searched depth-first.  We6513  // don't care about the active member of the union, as all we are doing is6514  // looking for a valid name. We also don't check bases, due to guidance from6515  // the Itanium ABI folks.6516  for (const FieldDecl *RDField : RD->fields()) {6517    if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))6518      return II;6519  }6520 6521  // According to the Itanium ABI: If there is no such data member (i.e., if all6522  // of the data members in the union are unnamed), then there is no way for a6523  // program to refer to the anonymous union, and there is therefore no need to6524  // mangle its name. However, we should diagnose this anyway.6525  unsigned DiagID = Diags.getCustomDiagID(6526      DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");6527  Diags.Report(UnionLoc, DiagID);6528 6529  return nullptr;6530}6531 6532void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,6533                                              bool TopLevel,6534                                              bool NeedExactType) {6535  // Ignore all top-level cv-qualifiers, to match GCC.6536  Qualifiers Quals;6537  T = getASTContext().getUnqualifiedArrayType(T, Quals);6538 6539  // A top-level expression that's not a primary expression is wrapped in X...E.6540  bool IsPrimaryExpr = true;6541  auto NotPrimaryExpr = [&] {6542    if (TopLevel && IsPrimaryExpr)6543      Out << 'X';6544    IsPrimaryExpr = false;6545  };6546 6547  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.6548  switch (V.getKind()) {6549  case APValue::None:6550  case APValue::Indeterminate:6551    Out << 'L';6552    mangleType(T);6553    Out << 'E';6554    break;6555 6556  case APValue::AddrLabelDiff:6557    llvm_unreachable("unexpected value kind in template argument");6558 6559  case APValue::Struct: {6560    const CXXRecordDecl *RD = T->getAsCXXRecordDecl();6561    assert(RD && "unexpected type for record value");6562 6563    // Drop trailing zero-initialized elements.6564    llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());6565    while (6566        !Fields.empty() &&6567        (Fields.back()->isUnnamedBitField() ||6568         isZeroInitialized(Fields.back()->getType(),6569                           V.getStructField(Fields.back()->getFieldIndex())))) {6570      Fields.pop_back();6571    }6572    ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());6573    if (Fields.empty()) {6574      while (!Bases.empty() &&6575             isZeroInitialized(Bases.back().getType(),6576                               V.getStructBase(Bases.size() - 1)))6577        Bases = Bases.drop_back();6578    }6579 6580    // <expression> ::= tl <type> <braced-expression>* E6581    NotPrimaryExpr();6582    Out << "tl";6583    mangleType(T);6584    for (unsigned I = 0, N = Bases.size(); I != N; ++I)6585      mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);6586    for (unsigned I = 0, N = Fields.size(); I != N; ++I) {6587      if (Fields[I]->isUnnamedBitField())6588        continue;6589      mangleValueInTemplateArg(Fields[I]->getType(),6590                               V.getStructField(Fields[I]->getFieldIndex()),6591                               false);6592    }6593    Out << 'E';6594    break;6595  }6596 6597  case APValue::Union: {6598    assert(T->getAsCXXRecordDecl() && "unexpected type for union value");6599    const FieldDecl *FD = V.getUnionField();6600 6601    if (!FD) {6602      Out << 'L';6603      mangleType(T);6604      Out << 'E';6605      break;6606    }6607 6608    // <braced-expression> ::= di <field source-name> <braced-expression>6609    NotPrimaryExpr();6610    Out << "tl";6611    mangleType(T);6612    if (!isZeroInitialized(T, V)) {6613      Out << "di";6614      IdentifierInfo *II = (getUnionInitName(6615          T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));6616      if (II)6617        mangleSourceName(II);6618      mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);6619    }6620    Out << 'E';6621    break;6622  }6623 6624  case APValue::Array: {6625    QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);6626 6627    NotPrimaryExpr();6628    Out << "tl";6629    mangleType(T);6630 6631    // Drop trailing zero-initialized elements.6632    unsigned N = V.getArraySize();6633    if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {6634      N = V.getArrayInitializedElts();6635      while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))6636        --N;6637    }6638 6639    for (unsigned I = 0; I != N; ++I) {6640      const APValue &Elem = I < V.getArrayInitializedElts()6641                                ? V.getArrayInitializedElt(I)6642                                : V.getArrayFiller();6643      mangleValueInTemplateArg(ElemT, Elem, false);6644    }6645    Out << 'E';6646    break;6647  }6648 6649  case APValue::Vector: {6650    const VectorType *VT = T->castAs<VectorType>();6651 6652    NotPrimaryExpr();6653    Out << "tl";6654    mangleType(T);6655    unsigned N = V.getVectorLength();6656    while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))6657      --N;6658    for (unsigned I = 0; I != N; ++I)6659      mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);6660    Out << 'E';6661    break;6662  }6663 6664  case APValue::Int:6665    mangleIntegerLiteral(T, V.getInt());6666    break;6667 6668  case APValue::Float:6669    mangleFloatLiteral(T, V.getFloat());6670    break;6671 6672  case APValue::FixedPoint:6673    mangleFixedPointLiteral();6674    break;6675 6676  case APValue::ComplexFloat: {6677    const ComplexType *CT = T->castAs<ComplexType>();6678    NotPrimaryExpr();6679    Out << "tl";6680    mangleType(T);6681    if (!V.getComplexFloatReal().isPosZero() ||6682        !V.getComplexFloatImag().isPosZero())6683      mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());6684    if (!V.getComplexFloatImag().isPosZero())6685      mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());6686    Out << 'E';6687    break;6688  }6689 6690  case APValue::ComplexInt: {6691    const ComplexType *CT = T->castAs<ComplexType>();6692    NotPrimaryExpr();6693    Out << "tl";6694    mangleType(T);6695    if (V.getComplexIntReal().getBoolValue() ||6696        V.getComplexIntImag().getBoolValue())6697      mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());6698    if (V.getComplexIntImag().getBoolValue())6699      mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());6700    Out << 'E';6701    break;6702  }6703 6704  case APValue::LValue: {6705    // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.6706    assert((T->isPointerOrReferenceType()) &&6707           "unexpected type for LValue template arg");6708 6709    if (V.isNullPointer()) {6710      mangleNullPointer(T);6711      break;6712    }6713 6714    APValue::LValueBase B = V.getLValueBase();6715    if (!B) {6716      // Non-standard mangling for integer cast to a pointer; this can only6717      // occur as an extension.6718      CharUnits Offset = V.getLValueOffset();6719      if (Offset.isZero()) {6720        // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as6721        // a cast, because L <type> 0 E means something else.6722        NotPrimaryExpr();6723        Out << "rc";6724        mangleType(T);6725        Out << "Li0E";6726        if (TopLevel)6727          Out << 'E';6728      } else {6729        Out << "L";6730        mangleType(T);6731        Out << Offset.getQuantity() << 'E';6732      }6733      break;6734    }6735 6736    ASTContext &Ctx = Context.getASTContext();6737 6738    enum { Base, Offset, Path } Kind;6739    if (!V.hasLValuePath()) {6740      // Mangle as (T*)((char*)&base + N).6741      if (T->isReferenceType()) {6742        NotPrimaryExpr();6743        Out << "decvP";6744        mangleType(T->getPointeeType());6745      } else {6746        NotPrimaryExpr();6747        Out << "cv";6748        mangleType(T);6749      }6750      Out << "plcvPcad";6751      Kind = Offset;6752    } else {6753      // Clang 11 and before mangled an array subject to array-to-pointer decay6754      // as if it were the declaration itself.6755      bool IsArrayToPointerDecayMangledAsDecl = false;6756      if (TopLevel && Ctx.getLangOpts().getClangABICompat() <=6757                          LangOptions::ClangABI::Ver11) {6758        QualType BType = B.getType();6759        IsArrayToPointerDecayMangledAsDecl =6760            BType->isArrayType() && V.getLValuePath().size() == 1 &&6761            V.getLValuePath()[0].getAsArrayIndex() == 0 &&6762            Ctx.hasSimilarType(T, Ctx.getDecayedType(BType));6763      }6764 6765      if ((!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) &&6766          !IsArrayToPointerDecayMangledAsDecl) {6767        NotPrimaryExpr();6768        // A final conversion to the template parameter's type is usually6769        // folded into the 'so' mangling, but we can't do that for 'void*'6770        // parameters without introducing collisions.6771        if (NeedExactType && T->isVoidPointerType()) {6772          Out << "cv";6773          mangleType(T);6774        }6775        if (T->isPointerType())6776          Out << "ad";6777        Out << "so";6778        mangleType(T->isVoidPointerType()6779                       ? getLValueType(Ctx, V).getUnqualifiedType()6780                       : T->getPointeeType());6781        Kind = Path;6782      } else {6783        if (NeedExactType &&6784            !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&6785            !isCompatibleWith(LangOptions::ClangABI::Ver11)) {6786          NotPrimaryExpr();6787          Out << "cv";6788          mangleType(T);6789        }6790        if (T->isPointerType()) {6791          NotPrimaryExpr();6792          Out << "ad";6793        }6794        Kind = Base;6795      }6796    }6797 6798    QualType TypeSoFar = B.getType();6799    if (auto *VD = B.dyn_cast<const ValueDecl*>()) {6800      Out << 'L';6801      mangle(VD);6802      Out << 'E';6803    } else if (auto *E = B.dyn_cast<const Expr*>()) {6804      NotPrimaryExpr();6805      mangleExpression(E);6806    } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {6807      NotPrimaryExpr();6808      Out << "ti";6809      mangleType(QualType(TI.getType(), 0));6810    } else {6811      // We should never see dynamic allocations here.6812      llvm_unreachable("unexpected lvalue base kind in template argument");6813    }6814 6815    switch (Kind) {6816    case Base:6817      break;6818 6819    case Offset:6820      Out << 'L';6821      mangleType(Ctx.getPointerDiffType());6822      mangleNumber(V.getLValueOffset().getQuantity());6823      Out << 'E';6824      break;6825 6826    case Path:6827      // <expression> ::= so <referent type> <expr> [<offset number>]6828      //                  <union-selector>* [p] E6829      if (!V.getLValueOffset().isZero())6830        mangleNumber(V.getLValueOffset().getQuantity());6831 6832      // We model a past-the-end array pointer as array indexing with index N,6833      // not with the "past the end" flag. Compensate for that.6834      bool OnePastTheEnd = V.isLValueOnePastTheEnd();6835 6836      for (APValue::LValuePathEntry E : V.getLValuePath()) {6837        if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {6838          if (auto *CAT = dyn_cast<ConstantArrayType>(AT))6839            OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();6840          TypeSoFar = AT->getElementType();6841        } else {6842          const Decl *D = E.getAsBaseOrMember().getPointer();6843          if (auto *FD = dyn_cast<FieldDecl>(D)) {6844            // <union-selector> ::= _ <number>6845            if (FD->getParent()->isUnion()) {6846              Out << '_';6847              if (FD->getFieldIndex())6848                Out << (FD->getFieldIndex() - 1);6849            }6850            TypeSoFar = FD->getType();6851          } else {6852            TypeSoFar = Ctx.getCanonicalTagType(cast<CXXRecordDecl>(D));6853          }6854        }6855      }6856 6857      if (OnePastTheEnd)6858        Out << 'p';6859      Out << 'E';6860      break;6861    }6862 6863    break;6864  }6865 6866  case APValue::MemberPointer:6867    // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.6868    if (!V.getMemberPointerDecl()) {6869      mangleNullPointer(T);6870      break;6871    }6872 6873    ASTContext &Ctx = Context.getASTContext();6874 6875    NotPrimaryExpr();6876    if (!V.getMemberPointerPath().empty()) {6877      Out << "mc";6878      mangleType(T);6879    } else if (NeedExactType &&6880               !Ctx.hasSameType(6881                   T->castAs<MemberPointerType>()->getPointeeType(),6882                   V.getMemberPointerDecl()->getType()) &&6883               !isCompatibleWith(LangOptions::ClangABI::Ver11)) {6884      Out << "cv";6885      mangleType(T);6886    }6887    Out << "adL";6888    mangle(V.getMemberPointerDecl());6889    Out << 'E';6890    if (!V.getMemberPointerPath().empty()) {6891      CharUnits Offset =6892          Context.getASTContext().getMemberPointerPathAdjustment(V);6893      if (!Offset.isZero())6894        mangleNumber(Offset.getQuantity());6895      Out << 'E';6896    }6897    break;6898  }6899 6900  if (TopLevel && !IsPrimaryExpr)6901    Out << 'E';6902}6903 6904void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {6905  // <template-param> ::= T_    # first template parameter6906  //                  ::= T <parameter-2 non-negative number> _6907  //                  ::= TL <L-1 non-negative number> __6908  //                  ::= TL <L-1 non-negative number> _6909  //                         <parameter-2 non-negative number> _6910  //6911  // The latter two manglings are from a proposal here:6912  // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-5281221176913  Out << 'T';6914  Depth += TemplateDepthOffset;6915  if (Depth != 0)6916    Out << 'L' << (Depth - 1) << '_';6917  if (Index != 0)6918    Out << (Index - 1);6919  Out << '_';6920}6921 6922void CXXNameMangler::mangleSeqID(unsigned SeqID) {6923  if (SeqID == 0) {6924    // Nothing.6925  } else if (SeqID == 1) {6926    Out << '0';6927  } else {6928    SeqID--;6929 6930    // <seq-id> is encoded in base-36, using digits and upper case letters.6931    char Buffer[7]; // log(2**32) / log(36) ~= 76932    MutableArrayRef<char> BufferRef(Buffer);6933    MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();6934 6935    for (; SeqID != 0; SeqID /= 36) {6936      unsigned C = SeqID % 36;6937      *I++ = (C < 10 ? '0' + C : 'A' + C - 10);6938    }6939 6940    Out.write(I.base(), I - BufferRef.rbegin());6941  }6942  Out << '_';6943}6944 6945void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {6946  bool result = mangleSubstitution(tname);6947  assert(result && "no existing substitution for template name");6948  (void) result;6949}6950 6951// <substitution> ::= S <seq-id> _6952//                ::= S_6953bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {6954  // Try one of the standard substitutions first.6955  if (mangleStandardSubstitution(ND))6956    return true;6957 6958  ND = cast<NamedDecl>(ND->getCanonicalDecl());6959  return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));6960}6961 6962/// Determine whether the given type has any qualifiers that are relevant for6963/// substitutions.6964static bool hasMangledSubstitutionQualifiers(QualType T) {6965  Qualifiers Qs = T.getQualifiers();6966  return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();6967}6968 6969bool CXXNameMangler::mangleSubstitution(QualType T) {6970  if (!hasMangledSubstitutionQualifiers(T)) {6971    if (const auto *RD = T->getAsCXXRecordDecl())6972      return mangleSubstitution(RD);6973  }6974 6975  uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());6976 6977  return mangleSubstitution(TypePtr);6978}6979 6980bool CXXNameMangler::mangleSubstitution(TemplateName Template) {6981  if (TemplateDecl *TD = Template.getAsTemplateDecl())6982    return mangleSubstitution(TD);6983 6984  Template = Context.getASTContext().getCanonicalTemplateName(Template);6985  return mangleSubstitution(6986                      reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));6987}6988 6989bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {6990  llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);6991  if (I == Substitutions.end())6992    return false;6993 6994  unsigned SeqID = I->second;6995  Out << 'S';6996  mangleSeqID(SeqID);6997 6998  return true;6999}7000 7001/// Returns whether S is a template specialization of std::Name with a single7002/// argument of type A.7003bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,7004                                     QualType A) {7005  if (S.isNull())7006    return false;7007 7008  const RecordType *RT = S->getAsCanonical<RecordType>();7009  if (!RT)7010    return false;7011 7012  const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());7013  if (!SD || !SD->getIdentifier()->isStr(Name))7014    return false;7015 7016  if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))7017    return false;7018 7019  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();7020  if (TemplateArgs.size() != 1)7021    return false;7022 7023  if (TemplateArgs[0].getAsType() != A)7024    return false;7025 7026  if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())7027    return false;7028 7029  return true;7030}7031 7032/// Returns whether SD is a template specialization std::Name<char,7033/// std::char_traits<char> [, std::allocator<char>]>7034/// HasAllocator controls whether the 3rd template argument is needed.7035bool CXXNameMangler::isStdCharSpecialization(7036    const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,7037    bool HasAllocator) {7038  if (!SD->getIdentifier()->isStr(Name))7039    return false;7040 7041  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();7042  if (TemplateArgs.size() != (HasAllocator ? 3 : 2))7043    return false;7044 7045  QualType A = TemplateArgs[0].getAsType();7046  if (A.isNull())7047    return false;7048  // Plain 'char' is named Char_S or Char_U depending on the target ABI.7049  if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&7050      !A->isSpecificBuiltinType(BuiltinType::Char_U))7051    return false;7052 7053  if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))7054    return false;7055 7056  if (HasAllocator &&7057      !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))7058    return false;7059 7060  if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())7061    return false;7062 7063  return true;7064}7065 7066bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {7067  // <substitution> ::= St # ::std::7068  if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {7069    if (isStd(NS)) {7070      Out << "St";7071      return true;7072    }7073    return false;7074  }7075 7076  if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {7077    if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))7078      return false;7079 7080    if (TD->getOwningModuleForLinkage())7081      return false;7082 7083    // <substitution> ::= Sa # ::std::allocator7084    if (TD->getIdentifier()->isStr("allocator")) {7085      Out << "Sa";7086      return true;7087    }7088 7089    // <<substitution> ::= Sb # ::std::basic_string7090    if (TD->getIdentifier()->isStr("basic_string")) {7091      Out << "Sb";7092      return true;7093    }7094    return false;7095  }7096 7097  if (const ClassTemplateSpecializationDecl *SD =7098        dyn_cast<ClassTemplateSpecializationDecl>(ND)) {7099    if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))7100      return false;7101 7102    if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())7103      return false;7104 7105    //    <substitution> ::= Ss # ::std::basic_string<char,7106    //                            ::std::char_traits<char>,7107    //                            ::std::allocator<char> >7108    if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {7109      Out << "Ss";7110      return true;7111    }7112 7113    //    <substitution> ::= Si # ::std::basic_istream<char,7114    //                            ::std::char_traits<char> >7115    if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {7116      Out << "Si";7117      return true;7118    }7119 7120    //    <substitution> ::= So # ::std::basic_ostream<char,7121    //                            ::std::char_traits<char> >7122    if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {7123      Out << "So";7124      return true;7125    }7126 7127    //    <substitution> ::= Sd # ::std::basic_iostream<char,7128    //                            ::std::char_traits<char> >7129    if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {7130      Out << "Sd";7131      return true;7132    }7133    return false;7134  }7135 7136  return false;7137}7138 7139void CXXNameMangler::addSubstitution(QualType T) {7140  if (!hasMangledSubstitutionQualifiers(T)) {7141    if (const auto *RD = T->getAsCXXRecordDecl()) {7142      addSubstitution(RD);7143      return;7144    }7145  }7146 7147  uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());7148  addSubstitution(TypePtr);7149}7150 7151void CXXNameMangler::addSubstitution(TemplateName Template) {7152  if (TemplateDecl *TD = Template.getAsTemplateDecl())7153    return addSubstitution(TD);7154 7155  Template = Context.getASTContext().getCanonicalTemplateName(Template);7156  addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));7157}7158 7159void CXXNameMangler::addSubstitution(uintptr_t Ptr) {7160  assert(!Substitutions.count(Ptr) && "Substitution already exists!");7161  Substitutions[Ptr] = SeqID++;7162}7163 7164void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {7165  assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");7166  if (Other->SeqID > SeqID) {7167    Substitutions.swap(Other->Substitutions);7168    SeqID = Other->SeqID;7169  }7170}7171 7172CXXNameMangler::AbiTagList7173CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {7174  // When derived abi tags are disabled there is no need to make any list.7175  if (DisableDerivedAbiTags)7176    return AbiTagList();7177 7178  llvm::raw_null_ostream NullOutStream;7179  CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);7180  TrackReturnTypeTags.disableDerivedAbiTags();7181 7182  const FunctionProtoType *Proto =7183      cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());7184  FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();7185  TrackReturnTypeTags.FunctionTypeDepth.enterResultType();7186  TrackReturnTypeTags.mangleType(Proto->getReturnType());7187  TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();7188  TrackReturnTypeTags.FunctionTypeDepth.pop(saved);7189 7190  return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();7191}7192 7193CXXNameMangler::AbiTagList7194CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {7195  // When derived abi tags are disabled there is no need to make any list.7196  if (DisableDerivedAbiTags)7197    return AbiTagList();7198 7199  llvm::raw_null_ostream NullOutStream;7200  CXXNameMangler TrackVariableType(*this, NullOutStream);7201  TrackVariableType.disableDerivedAbiTags();7202 7203  TrackVariableType.mangleType(VD->getType());7204 7205  return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();7206}7207 7208bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,7209                                       const VarDecl *VD) {7210  llvm::raw_null_ostream NullOutStream;7211  CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);7212  TrackAbiTags.mangle(VD);7213  return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();7214}7215 7216//7217 7218/// Mangles the name of the declaration D and emits that name to the given7219/// output stream.7220///7221/// If the declaration D requires a mangled name, this routine will emit that7222/// mangled name to \p os and return true. Otherwise, \p os will be unchanged7223/// and this routine will return false. In this case, the caller should just7224/// emit the identifier of the declaration (\c D->getIdentifier()) as its7225/// name.7226void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,7227                                             raw_ostream &Out) {7228  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());7229  assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&7230         "Invalid mangleName() call, argument is not a variable or function!");7231 7232  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),7233                                 getASTContext().getSourceManager(),7234                                 "Mangling declaration");7235 7236  if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {7237    auto Type = GD.getCtorType();7238    CXXNameMangler Mangler(*this, Out, CD, Type);7239    return Mangler.mangle(GlobalDecl(CD, Type));7240  }7241 7242  if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {7243    auto Type = GD.getDtorType();7244    CXXNameMangler Mangler(*this, Out, DD, Type);7245    return Mangler.mangle(GlobalDecl(DD, Type));7246  }7247 7248  CXXNameMangler Mangler(*this, Out, D);7249  Mangler.mangle(GD);7250}7251 7252void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,7253                                                   raw_ostream &Out) {7254  CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);7255  Mangler.mangle(GlobalDecl(D, Ctor_Comdat));7256}7257 7258void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,7259                                                   raw_ostream &Out) {7260  CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);7261  Mangler.mangle(GlobalDecl(D, Dtor_Comdat));7262}7263 7264/// Mangles the pointer authentication override attribute for classes7265/// that have explicit overrides for the vtable authentication schema.7266///7267/// The override is mangled as a parameterized vendor extension as follows7268///7269///   <type> ::= U "__vtptrauth" I7270///                 <key>7271///                 <addressDiscriminated>7272///                 <extraDiscriminator>7273///              E7274///7275/// The extra discriminator encodes the explicit value derived from the7276/// override schema, e.g. if the override has specified type based7277/// discrimination the encoded value will be the discriminator derived from the7278/// type name.7279static void mangleOverrideDiscrimination(CXXNameMangler &Mangler,7280                                         ASTContext &Context,7281                                         const ThunkInfo &Thunk) {7282  auto &LangOpts = Context.getLangOpts();7283  const CXXRecordDecl *ThisRD = Thunk.ThisType->getPointeeCXXRecordDecl();7284  const CXXRecordDecl *PtrauthClassRD =7285      Context.baseForVTableAuthentication(ThisRD);7286  unsigned TypedDiscriminator =7287      Context.getPointerAuthVTablePointerDiscriminator(ThisRD);7288  Mangler.mangleVendorQualifier("__vtptrauth");7289  auto &ManglerStream = Mangler.getStream();7290  ManglerStream << "I";7291  if (const auto *ExplicitAuth =7292          PtrauthClassRD->getAttr<VTablePointerAuthenticationAttr>()) {7293    ManglerStream << "Lj" << ExplicitAuth->getKey();7294 7295    if (ExplicitAuth->getAddressDiscrimination() ==7296        VTablePointerAuthenticationAttr::DefaultAddressDiscrimination)7297      ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;7298    else7299      ManglerStream << "Lb"7300                    << (ExplicitAuth->getAddressDiscrimination() ==7301                        VTablePointerAuthenticationAttr::AddressDiscrimination);7302 7303    switch (ExplicitAuth->getExtraDiscrimination()) {7304    case VTablePointerAuthenticationAttr::DefaultExtraDiscrimination: {7305      if (LangOpts.PointerAuthVTPtrTypeDiscrimination)7306        ManglerStream << "Lj" << TypedDiscriminator;7307      else7308        ManglerStream << "Lj" << 0;7309      break;7310    }7311    case VTablePointerAuthenticationAttr::TypeDiscrimination:7312      ManglerStream << "Lj" << TypedDiscriminator;7313      break;7314    case VTablePointerAuthenticationAttr::CustomDiscrimination:7315      ManglerStream << "Lj" << ExplicitAuth->getCustomDiscriminationValue();7316      break;7317    case VTablePointerAuthenticationAttr::NoExtraDiscrimination:7318      ManglerStream << "Lj" << 0;7319      break;7320    }7321  } else {7322    ManglerStream << "Lj"7323                  << (unsigned)VTablePointerAuthenticationAttr::DefaultKey;7324    ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;7325    if (LangOpts.PointerAuthVTPtrTypeDiscrimination)7326      ManglerStream << "Lj" << TypedDiscriminator;7327    else7328      ManglerStream << "Lj" << 0;7329  }7330  ManglerStream << "E";7331}7332 7333void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,7334                                           const ThunkInfo &Thunk,7335                                           bool ElideOverrideInfo,7336                                           raw_ostream &Out) {7337  //  <special-name> ::= T <call-offset> <base encoding>7338  //                      # base is the nominal target function of thunk7339  //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>7340  //                      # base is the nominal target function of thunk7341  //                      # first call-offset is 'this' adjustment7342  //                      # second call-offset is result adjustment7343 7344  assert(!isa<CXXDestructorDecl>(MD) &&7345         "Use mangleCXXDtor for destructor decls!");7346  CXXNameMangler Mangler(*this, Out);7347  Mangler.getStream() << "_ZT";7348  if (!Thunk.Return.isEmpty())7349    Mangler.getStream() << 'c';7350 7351  // Mangle the 'this' pointer adjustment.7352  Mangler.mangleCallOffset(Thunk.This.NonVirtual,7353                           Thunk.This.Virtual.Itanium.VCallOffsetOffset);7354 7355  // Mangle the return pointer adjustment if there is one.7356  if (!Thunk.Return.isEmpty())7357    Mangler.mangleCallOffset(Thunk.Return.NonVirtual,7358                             Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);7359 7360  Mangler.mangleFunctionEncoding(MD);7361  if (!ElideOverrideInfo)7362    mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);7363}7364 7365void ItaniumMangleContextImpl::mangleCXXDtorThunk(const CXXDestructorDecl *DD,7366                                                  CXXDtorType Type,7367                                                  const ThunkInfo &Thunk,7368                                                  bool ElideOverrideInfo,7369                                                  raw_ostream &Out) {7370  //  <special-name> ::= T <call-offset> <base encoding>7371  //                      # base is the nominal target function of thunk7372  CXXNameMangler Mangler(*this, Out, DD, Type);7373  Mangler.getStream() << "_ZT";7374 7375  auto &ThisAdjustment = Thunk.This;7376  // Mangle the 'this' pointer adjustment.7377  Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,7378                           ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);7379 7380  Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));7381  if (!ElideOverrideInfo)7382    mangleOverrideDiscrimination(Mangler, getASTContext(), Thunk);7383}7384 7385/// Returns the mangled name for a guard variable for the passed in VarDecl.7386void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,7387                                                         raw_ostream &Out) {7388  //  <special-name> ::= GV <object name>       # Guard variable for one-time7389  //                                            # initialization7390  CXXNameMangler Mangler(*this, Out);7391  // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to7392  // be a bug that is fixed in trunk.7393  Mangler.getStream() << "_ZGV";7394  Mangler.mangleName(D);7395}7396 7397void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,7398                                                        raw_ostream &Out) {7399  // These symbols are internal in the Itanium ABI, so the names don't matter.7400  // Clang has traditionally used this symbol and allowed LLVM to adjust it to7401  // avoid duplicate symbols.7402  Out << "__cxx_global_var_init";7403}7404 7405void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,7406                                                             raw_ostream &Out) {7407  // Prefix the mangling of D with __dtor_.7408  CXXNameMangler Mangler(*this, Out);7409  Mangler.getStream() << "__dtor_";7410  if (shouldMangleDeclName(D))7411    Mangler.mangle(D);7412  else7413    Mangler.getStream() << D->getName();7414}7415 7416void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,7417                                                           raw_ostream &Out) {7418  // Clang generates these internal-linkage functions as part of its7419  // implementation of the XL ABI.7420  CXXNameMangler Mangler(*this, Out);7421  Mangler.getStream() << "__finalize_";7422  if (shouldMangleDeclName(D))7423    Mangler.mangle(D);7424  else7425    Mangler.getStream() << D->getName();7426}7427 7428void ItaniumMangleContextImpl::mangleSEHFilterExpression(7429    GlobalDecl EnclosingDecl, raw_ostream &Out) {7430  CXXNameMangler Mangler(*this, Out);7431  Mangler.getStream() << "__filt_";7432  auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());7433  if (shouldMangleDeclName(EnclosingFD))7434    Mangler.mangle(EnclosingDecl);7435  else7436    Mangler.getStream() << EnclosingFD->getName();7437}7438 7439void ItaniumMangleContextImpl::mangleSEHFinallyBlock(7440    GlobalDecl EnclosingDecl, raw_ostream &Out) {7441  CXXNameMangler Mangler(*this, Out);7442  Mangler.getStream() << "__fin_";7443  auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());7444  if (shouldMangleDeclName(EnclosingFD))7445    Mangler.mangle(EnclosingDecl);7446  else7447    Mangler.getStream() << EnclosingFD->getName();7448}7449 7450void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,7451                                                            raw_ostream &Out) {7452  //  <special-name> ::= TH <object name>7453  CXXNameMangler Mangler(*this, Out);7454  Mangler.getStream() << "_ZTH";7455  Mangler.mangleName(D);7456}7457 7458void7459ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,7460                                                          raw_ostream &Out) {7461  //  <special-name> ::= TW <object name>7462  CXXNameMangler Mangler(*this, Out);7463  Mangler.getStream() << "_ZTW";7464  Mangler.mangleName(D);7465}7466 7467void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,7468                                                        unsigned ManglingNumber,7469                                                        raw_ostream &Out) {7470  // We match the GCC mangling here.7471  //  <special-name> ::= GR <object name>7472  CXXNameMangler Mangler(*this, Out);7473  Mangler.getStream() << "_ZGR";7474  Mangler.mangleName(D);7475  assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");7476  Mangler.mangleSeqID(ManglingNumber - 1);7477}7478 7479void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,7480                                               raw_ostream &Out) {7481  // <special-name> ::= TV <type>  # virtual table7482  CXXNameMangler Mangler(*this, Out);7483  Mangler.getStream() << "_ZTV";7484  Mangler.mangleCXXRecordDecl(RD);7485}7486 7487void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,7488                                            raw_ostream &Out) {7489  // <special-name> ::= TT <type>  # VTT structure7490  CXXNameMangler Mangler(*this, Out);7491  Mangler.getStream() << "_ZTT";7492  Mangler.mangleCXXRecordDecl(RD);7493}7494 7495void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,7496                                                   int64_t Offset,7497                                                   const CXXRecordDecl *Type,7498                                                   raw_ostream &Out) {7499  // <special-name> ::= TC <type> <offset number> _ <base type>7500  CXXNameMangler Mangler(*this, Out);7501  Mangler.getStream() << "_ZTC";7502  // Older versions of clang did not add the record as a substitution candidate7503  // here.7504  bool SuppressSubstitution =7505      getASTContext().getLangOpts().getClangABICompat() <=7506      LangOptions::ClangABI::Ver19;7507  Mangler.mangleCXXRecordDecl(RD, SuppressSubstitution);7508  Mangler.getStream() << Offset;7509  Mangler.getStream() << '_';7510  Mangler.mangleCXXRecordDecl(Type);7511}7512 7513void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {7514  // <special-name> ::= TI <type>  # typeinfo structure7515  assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");7516  CXXNameMangler Mangler(*this, Out);7517  Mangler.getStream() << "_ZTI";7518  Mangler.mangleType(Ty);7519}7520 7521void ItaniumMangleContextImpl::mangleCXXRTTIName(7522    QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {7523  // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)7524  CXXNameMangler Mangler(*this, Out, NormalizeIntegers);7525  Mangler.getStream() << "_ZTS";7526  Mangler.mangleType(Ty);7527}7528 7529void ItaniumMangleContextImpl::mangleCanonicalTypeName(7530    QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {7531  mangleCXXRTTIName(Ty, Out, NormalizeIntegers);7532}7533 7534void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {7535  llvm_unreachable("Can't mangle string literals");7536}7537 7538void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,7539                                               raw_ostream &Out) {7540  CXXNameMangler Mangler(*this, Out);7541  Mangler.mangleLambdaSig(Lambda);7542}7543 7544void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,7545                                                       raw_ostream &Out) {7546  // <special-name> ::= GI <module-name>  # module initializer function7547  CXXNameMangler Mangler(*this, Out);7548  Mangler.getStream() << "_ZGI";7549  Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());7550  if (M->isModulePartition()) {7551    // The partition needs including, as partitions can have them too.7552    auto Partition = M->Name.find(':');7553    Mangler.mangleModuleNamePrefix(7554        StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),7555        /*IsPartition*/ true);7556  }7557}7558 7559ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,7560                                                   DiagnosticsEngine &Diags,7561                                                   bool IsAux) {7562  return new ItaniumMangleContextImpl(7563      Context, Diags,7564      [](ASTContext &, const NamedDecl *) -> UnsignedOrNone {7565        return std::nullopt;7566      },7567      IsAux);7568}7569 7570ItaniumMangleContext *7571ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,7572                             DiscriminatorOverrideTy DiscriminatorOverride,7573                             bool IsAux) {7574  return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,7575                                      IsAux);7576}7577