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-exception 6 // 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 are 11 // ABI-compatible with GCC): 12 // 13 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling 14 // 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/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Basic/Thunk.h" 35 #include "llvm/ADT/StringExtras.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/raw_ostream.h" 38 39 using namespace clang; 40 41 namespace { 42 43 static bool isLocalContainerContext(const DeclContext *DC) { 44 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC); 45 } 46 47 static const FunctionDecl *getStructor(const FunctionDecl *fn) { 48 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate()) 49 return ftd->getTemplatedDecl(); 50 51 return fn; 52 } 53 54 static const NamedDecl *getStructor(const NamedDecl *decl) { 55 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl); 56 return (fn ? getStructor(fn) : decl); 57 } 58 59 static bool isLambda(const NamedDecl *ND) { 60 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND); 61 if (!Record) 62 return false; 63 64 return Record->isLambda(); 65 } 66 67 static const unsigned UnknownArity = ~0U; 68 69 class ItaniumMangleContextImpl : public ItaniumMangleContext { 70 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy; 71 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator; 72 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier; 73 const DiscriminatorOverrideTy DiscriminatorOverride = nullptr; 74 NamespaceDecl *StdNamespace = nullptr; 75 76 bool NeedsUniqueInternalLinkageNames = false; 77 78 public: 79 explicit ItaniumMangleContextImpl( 80 ASTContext &Context, DiagnosticsEngine &Diags, 81 DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false) 82 : ItaniumMangleContext(Context, Diags, IsAux), 83 DiscriminatorOverride(DiscriminatorOverride) {} 84 85 /// @name Mangler Entry Points 86 /// @{ 87 88 bool shouldMangleCXXName(const NamedDecl *D) override; 89 bool shouldMangleStringLiteral(const StringLiteral *) override { 90 return false; 91 } 92 93 bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override; 94 void needsUniqueInternalLinkageNames() override { 95 NeedsUniqueInternalLinkageNames = true; 96 } 97 98 void mangleCXXName(GlobalDecl GD, raw_ostream &) override; 99 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, 100 raw_ostream &) override; 101 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, 102 const ThisAdjustment &ThisAdjustment, 103 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 &) override; 112 void mangleTypeName(QualType T, raw_ostream &) override; 113 114 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override; 115 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override; 116 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override; 117 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override; 118 void mangleDynamicAtExitDestructor(const VarDecl *D, 119 raw_ostream &Out) override; 120 void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override; 121 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl, 122 raw_ostream &Out) override; 123 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl, 124 raw_ostream &Out) override; 125 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override; 126 void mangleItaniumThreadLocalWrapper(const VarDecl *D, 127 raw_ostream &) override; 128 129 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override; 130 131 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override; 132 133 void mangleModuleInitializer(const Module *Module, raw_ostream &) override; 134 135 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { 136 // Lambda closure types are already numbered. 137 if (isLambda(ND)) 138 return false; 139 140 // Anonymous tags are already numbered. 141 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) { 142 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl()) 143 return false; 144 } 145 146 // Use the canonical number for externally visible decls. 147 if (ND->isExternallyVisible()) { 148 unsigned discriminator = getASTContext().getManglingNumber(ND, isAux()); 149 if (discriminator == 1) 150 return false; 151 disc = discriminator - 2; 152 return true; 153 } 154 155 // Make up a reasonable number for internal decls. 156 unsigned &discriminator = Uniquifier[ND]; 157 if (!discriminator) { 158 const DeclContext *DC = getEffectiveDeclContext(ND); 159 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())]; 160 } 161 if (discriminator == 1) 162 return false; 163 disc = discriminator-2; 164 return true; 165 } 166 167 std::string getLambdaString(const CXXRecordDecl *Lambda) override { 168 // This function matches the one in MicrosoftMangle, which returns 169 // the string that is used in lambda mangled names. 170 assert(Lambda->isLambda() && "RD must be a lambda!"); 171 std::string Name("<lambda"); 172 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl(); 173 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber(); 174 unsigned LambdaId; 175 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl); 176 const FunctionDecl *Func = 177 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr; 178 179 if (Func) { 180 unsigned DefaultArgNo = 181 Func->getNumParams() - Parm->getFunctionScopeIndex(); 182 Name += llvm::utostr(DefaultArgNo); 183 Name += "_"; 184 } 185 186 if (LambdaManglingNumber) 187 LambdaId = LambdaManglingNumber; 188 else 189 LambdaId = getAnonymousStructIdForDebugInfo(Lambda); 190 191 Name += llvm::utostr(LambdaId); 192 Name += '>'; 193 return Name; 194 } 195 196 DiscriminatorOverrideTy getDiscriminatorOverride() const override { 197 return DiscriminatorOverride; 198 } 199 200 NamespaceDecl *getStdNamespace(); 201 202 const DeclContext *getEffectiveDeclContext(const Decl *D); 203 const DeclContext *getEffectiveParentContext(const DeclContext *DC) { 204 return getEffectiveDeclContext(cast<Decl>(DC)); 205 } 206 207 bool isInternalLinkageDecl(const NamedDecl *ND); 208 const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC); 209 210 /// @} 211 }; 212 213 /// Manage the mangling of a single name. 214 class CXXNameMangler { 215 ItaniumMangleContextImpl &Context; 216 raw_ostream &Out; 217 bool NullOut = false; 218 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated. 219 /// This mode is used when mangler creates another mangler recursively to 220 /// calculate ABI tags for the function return value or the variable type. 221 /// Also it is required to avoid infinite recursion in some cases. 222 bool DisableDerivedAbiTags = false; 223 224 /// The "structor" is the top-level declaration being mangled, if 225 /// that's not a template specialization; otherwise it's the pattern 226 /// for that specialization. 227 const NamedDecl *Structor; 228 unsigned StructorType = 0; 229 230 /// The next substitution sequence number. 231 unsigned SeqID = 0; 232 233 class FunctionTypeDepthState { 234 unsigned Bits; 235 236 enum { InResultTypeMask = 1 }; 237 238 public: 239 FunctionTypeDepthState() : Bits(0) {} 240 241 /// The number of function types we're inside. 242 unsigned getDepth() const { 243 return Bits >> 1; 244 } 245 246 /// True if we're in the return type of the innermost function type. 247 bool isInResultType() const { 248 return Bits & InResultTypeMask; 249 } 250 251 FunctionTypeDepthState push() { 252 FunctionTypeDepthState tmp = *this; 253 Bits = (Bits & ~InResultTypeMask) + 2; 254 return tmp; 255 } 256 257 void enterResultType() { 258 Bits |= InResultTypeMask; 259 } 260 261 void leaveResultType() { 262 Bits &= ~InResultTypeMask; 263 } 264 265 void pop(FunctionTypeDepthState saved) { 266 assert(getDepth() == saved.getDepth() + 1); 267 Bits = saved.Bits; 268 } 269 270 } FunctionTypeDepth; 271 272 // abi_tag is a gcc attribute, taking one or more strings called "tags". 273 // The goal is to annotate against which version of a library an object was 274 // built and to be able to provide backwards compatibility ("dual abi"). 275 // For more information see docs/ItaniumMangleAbiTags.rst. 276 typedef SmallVector<StringRef, 4> AbiTagList; 277 278 // State to gather all implicit and explicit tags used in a mangled name. 279 // Must always have an instance of this while emitting any name to keep 280 // track. 281 class AbiTagState final { 282 public: 283 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) { 284 Parent = LinkHead; 285 LinkHead = this; 286 } 287 288 // No copy, no move. 289 AbiTagState(const AbiTagState &) = delete; 290 AbiTagState &operator=(const AbiTagState &) = delete; 291 292 ~AbiTagState() { pop(); } 293 294 void write(raw_ostream &Out, const NamedDecl *ND, 295 const AbiTagList *AdditionalAbiTags) { 296 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 297 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) { 298 assert( 299 !AdditionalAbiTags && 300 "only function and variables need a list of additional abi tags"); 301 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) { 302 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) { 303 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(), 304 AbiTag->tags().end()); 305 } 306 // Don't emit abi tags for namespaces. 307 return; 308 } 309 } 310 311 AbiTagList TagList; 312 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) { 313 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(), 314 AbiTag->tags().end()); 315 TagList.insert(TagList.end(), AbiTag->tags().begin(), 316 AbiTag->tags().end()); 317 } 318 319 if (AdditionalAbiTags) { 320 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(), 321 AdditionalAbiTags->end()); 322 TagList.insert(TagList.end(), AdditionalAbiTags->begin(), 323 AdditionalAbiTags->end()); 324 } 325 326 llvm::sort(TagList); 327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end()); 328 329 writeSortedUniqueAbiTags(Out, TagList); 330 } 331 332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; } 333 void setUsedAbiTags(const AbiTagList &AbiTags) { 334 UsedAbiTags = AbiTags; 335 } 336 337 const AbiTagList &getEmittedAbiTags() const { 338 return EmittedAbiTags; 339 } 340 341 const AbiTagList &getSortedUniqueUsedAbiTags() { 342 llvm::sort(UsedAbiTags); 343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()), 344 UsedAbiTags.end()); 345 return UsedAbiTags; 346 } 347 348 private: 349 //! All abi tags used implicitly or explicitly. 350 AbiTagList UsedAbiTags; 351 //! All explicit abi tags (i.e. not from namespace). 352 AbiTagList EmittedAbiTags; 353 354 AbiTagState *&LinkHead; 355 AbiTagState *Parent = nullptr; 356 357 void pop() { 358 assert(LinkHead == this && 359 "abi tag link head must point to us on destruction"); 360 if (Parent) { 361 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(), 362 UsedAbiTags.begin(), UsedAbiTags.end()); 363 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(), 364 EmittedAbiTags.begin(), 365 EmittedAbiTags.end()); 366 } 367 LinkHead = Parent; 368 } 369 370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) { 371 for (const auto &Tag : AbiTags) { 372 EmittedAbiTags.push_back(Tag); 373 Out << "B"; 374 Out << Tag.size(); 375 Out << Tag; 376 } 377 } 378 }; 379 380 AbiTagState *AbiTags = nullptr; 381 AbiTagState AbiTagsRoot; 382 383 llvm::DenseMap<uintptr_t, unsigned> Substitutions; 384 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions; 385 386 ASTContext &getASTContext() const { return Context.getASTContext(); } 387 388 bool isStd(const NamespaceDecl *NS); 389 bool isStdNamespace(const DeclContext *DC); 390 391 const RecordDecl *GetLocalClassDecl(const Decl *D); 392 const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC); 393 bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A); 394 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD, 395 llvm::StringRef Name, bool HasAllocator); 396 397 public: 398 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 399 const NamedDecl *D = nullptr, bool NullOut_ = false) 400 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)), 401 AbiTagsRoot(AbiTags) { 402 // These can't be mangled without a ctor type or dtor type. 403 assert(!D || (!isa<CXXDestructorDecl>(D) && 404 !isa<CXXConstructorDecl>(D))); 405 } 406 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 407 const CXXConstructorDecl *D, CXXCtorType Type) 408 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 409 AbiTagsRoot(AbiTags) {} 410 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 411 const CXXDestructorDecl *D, CXXDtorType Type) 412 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 413 AbiTagsRoot(AbiTags) {} 414 415 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_) 416 : Context(Outer.Context), Out(Out_), Structor(Outer.Structor), 417 StructorType(Outer.StructorType), SeqID(Outer.SeqID), 418 FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags), 419 Substitutions(Outer.Substitutions), 420 ModuleSubstitutions(Outer.ModuleSubstitutions) {} 421 422 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_) 423 : CXXNameMangler(Outer, (raw_ostream &)Out_) { 424 NullOut = true; 425 } 426 427 raw_ostream &getStream() { return Out; } 428 429 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; } 430 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD); 431 432 void mangle(GlobalDecl GD); 433 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual); 434 void mangleNumber(const llvm::APSInt &I); 435 void mangleNumber(int64_t Number); 436 void mangleFloat(const llvm::APFloat &F); 437 void mangleFunctionEncoding(GlobalDecl GD); 438 void mangleSeqID(unsigned SeqID); 439 void mangleName(GlobalDecl GD); 440 void mangleType(QualType T); 441 void mangleNameOrStandardSubstitution(const NamedDecl *ND); 442 void mangleLambdaSig(const CXXRecordDecl *Lambda); 443 void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false); 444 445 private: 446 447 bool mangleSubstitution(const NamedDecl *ND); 448 bool mangleSubstitution(NestedNameSpecifier *NNS); 449 bool mangleSubstitution(QualType T); 450 bool mangleSubstitution(TemplateName Template); 451 bool mangleSubstitution(uintptr_t Ptr); 452 453 void mangleExistingSubstitution(TemplateName name); 454 455 bool mangleStandardSubstitution(const NamedDecl *ND); 456 457 void addSubstitution(const NamedDecl *ND) { 458 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 459 460 addSubstitution(reinterpret_cast<uintptr_t>(ND)); 461 } 462 void addSubstitution(NestedNameSpecifier *NNS) { 463 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS); 464 465 addSubstitution(reinterpret_cast<uintptr_t>(NNS)); 466 } 467 void addSubstitution(QualType T); 468 void addSubstitution(TemplateName Template); 469 void addSubstitution(uintptr_t Ptr); 470 // Destructive copy substitutions from other mangler. 471 void extendSubstitutions(CXXNameMangler* Other); 472 473 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, 474 bool recursive = false); 475 void mangleUnresolvedName(NestedNameSpecifier *qualifier, 476 DeclarationName name, 477 const TemplateArgumentLoc *TemplateArgs, 478 unsigned NumTemplateArgs, 479 unsigned KnownArity = UnknownArity); 480 481 void mangleFunctionEncodingBareType(const FunctionDecl *FD); 482 483 void mangleNameWithAbiTags(GlobalDecl GD, 484 const AbiTagList *AdditionalAbiTags); 485 void mangleModuleName(const NamedDecl *ND); 486 void mangleTemplateName(const TemplateDecl *TD, 487 const TemplateArgument *TemplateArgs, 488 unsigned NumTemplateArgs); 489 void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC, 490 const AbiTagList *AdditionalAbiTags) { 491 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC, 492 UnknownArity, AdditionalAbiTags); 493 } 494 void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name, 495 const DeclContext *DC, unsigned KnownArity, 496 const AbiTagList *AdditionalAbiTags); 497 void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC, 498 const AbiTagList *AdditionalAbiTags); 499 void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC, 500 const AbiTagList *AdditionalAbiTags); 501 void mangleSourceName(const IdentifierInfo *II); 502 void mangleRegCallName(const IdentifierInfo *II); 503 void mangleDeviceStubName(const IdentifierInfo *II); 504 void mangleSourceNameWithAbiTags( 505 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr); 506 void mangleLocalName(GlobalDecl GD, 507 const AbiTagList *AdditionalAbiTags); 508 void mangleBlockForPrefix(const BlockDecl *Block); 509 void mangleUnqualifiedBlock(const BlockDecl *Block); 510 void mangleTemplateParamDecl(const NamedDecl *Decl); 511 void mangleLambda(const CXXRecordDecl *Lambda); 512 void mangleNestedName(GlobalDecl GD, const DeclContext *DC, 513 const AbiTagList *AdditionalAbiTags, 514 bool NoFunction=false); 515 void mangleNestedName(const TemplateDecl *TD, 516 const TemplateArgument *TemplateArgs, 517 unsigned NumTemplateArgs); 518 void mangleNestedNameWithClosurePrefix(GlobalDecl GD, 519 const NamedDecl *PrefixND, 520 const AbiTagList *AdditionalAbiTags); 521 void manglePrefix(NestedNameSpecifier *qualifier); 522 void manglePrefix(const DeclContext *DC, bool NoFunction=false); 523 void manglePrefix(QualType type); 524 void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false); 525 void mangleTemplatePrefix(TemplateName Template); 526 const NamedDecl *getClosurePrefix(const Decl *ND); 527 void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false); 528 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType, 529 StringRef Prefix = ""); 530 void mangleOperatorName(DeclarationName Name, unsigned Arity); 531 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity); 532 void mangleVendorQualifier(StringRef qualifier); 533 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr); 534 void mangleRefQualifier(RefQualifierKind RefQualifier); 535 536 void mangleObjCMethodName(const ObjCMethodDecl *MD); 537 538 // Declare manglers for every type class. 539 #define ABSTRACT_TYPE(CLASS, PARENT) 540 #define NON_CANONICAL_TYPE(CLASS, PARENT) 541 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T); 542 #include "clang/AST/TypeNodes.inc" 543 544 void mangleType(const TagType*); 545 void mangleType(TemplateName); 546 static StringRef getCallingConvQualifierName(CallingConv CC); 547 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info); 548 void mangleExtFunctionInfo(const FunctionType *T); 549 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType, 550 const FunctionDecl *FD = nullptr); 551 void mangleNeonVectorType(const VectorType *T); 552 void mangleNeonVectorType(const DependentVectorType *T); 553 void mangleAArch64NeonVectorType(const VectorType *T); 554 void mangleAArch64NeonVectorType(const DependentVectorType *T); 555 void mangleAArch64FixedSveVectorType(const VectorType *T); 556 void mangleAArch64FixedSveVectorType(const DependentVectorType *T); 557 558 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value); 559 void mangleFloatLiteral(QualType T, const llvm::APFloat &V); 560 void mangleFixedPointLiteral(); 561 void mangleNullPointer(QualType T); 562 563 void mangleMemberExprBase(const Expr *base, bool isArrow); 564 void mangleMemberExpr(const Expr *base, bool isArrow, 565 NestedNameSpecifier *qualifier, 566 NamedDecl *firstQualifierLookup, 567 DeclarationName name, 568 const TemplateArgumentLoc *TemplateArgs, 569 unsigned NumTemplateArgs, 570 unsigned knownArity); 571 void mangleCastExpression(const Expr *E, StringRef CastEncoding); 572 void mangleInitListElements(const InitListExpr *InitList); 573 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity, 574 bool AsTemplateArg = false); 575 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom); 576 void mangleCXXDtorType(CXXDtorType T); 577 578 void mangleTemplateArgs(TemplateName TN, 579 const TemplateArgumentLoc *TemplateArgs, 580 unsigned NumTemplateArgs); 581 void mangleTemplateArgs(TemplateName TN, const TemplateArgument *TemplateArgs, 582 unsigned NumTemplateArgs); 583 void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL); 584 void mangleTemplateArg(TemplateArgument A, bool NeedExactType); 585 void mangleTemplateArgExpr(const Expr *E); 586 void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel, 587 bool NeedExactType = false); 588 589 void mangleTemplateParameter(unsigned Depth, unsigned Index); 590 591 void mangleFunctionParam(const ParmVarDecl *parm); 592 593 void writeAbiTags(const NamedDecl *ND, 594 const AbiTagList *AdditionalAbiTags); 595 596 // Returns sorted unique list of ABI tags. 597 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD); 598 // Returns sorted unique list of ABI tags. 599 AbiTagList makeVariableTypeTags(const VarDecl *VD); 600 }; 601 602 } 603 604 NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() { 605 if (!StdNamespace) { 606 StdNamespace = NamespaceDecl::Create( 607 getASTContext(), getASTContext().getTranslationUnitDecl(), 608 /*Inline*/ false, SourceLocation(), SourceLocation(), 609 &getASTContext().Idents.get("std"), 610 /*PrevDecl*/ nullptr); 611 StdNamespace->setImplicit(); 612 } 613 return StdNamespace; 614 } 615 616 /// Retrieve the declaration context that should be used when mangling the given 617 /// declaration. 618 const DeclContext * 619 ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) { 620 // The ABI assumes that lambda closure types that occur within 621 // default arguments live in the context of the function. However, due to 622 // the way in which Clang parses and creates function declarations, this is 623 // not the case: the lambda closure type ends up living in the context 624 // where the function itself resides, because the function declaration itself 625 // had not yet been created. Fix the context here. 626 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 627 if (RD->isLambda()) 628 if (ParmVarDecl *ContextParam = 629 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl())) 630 return ContextParam->getDeclContext(); 631 } 632 633 // Perform the same check for block literals. 634 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 635 if (ParmVarDecl *ContextParam = 636 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) 637 return ContextParam->getDeclContext(); 638 } 639 640 // On ARM and AArch64, the va_list tag is always mangled as if in the std 641 // namespace. We do not represent va_list as actually being in the std 642 // namespace in C because this would result in incorrect debug info in C, 643 // among other things. It is important for both languages to have the same 644 // mangling in order for -fsanitize=cfi-icall to work. 645 if (D == getASTContext().getVaListTagDecl()) { 646 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 647 if (T.isARM() || T.isThumb() || T.isAArch64()) 648 return getStdNamespace(); 649 } 650 651 const DeclContext *DC = D->getDeclContext(); 652 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) || 653 isa<OMPDeclareMapperDecl>(DC)) { 654 return getEffectiveDeclContext(cast<Decl>(DC)); 655 } 656 657 if (const auto *VD = dyn_cast<VarDecl>(D)) 658 if (VD->isExternC()) 659 return getASTContext().getTranslationUnitDecl(); 660 661 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 662 if (FD->isExternC()) 663 return getASTContext().getTranslationUnitDecl(); 664 665 return DC->getRedeclContext(); 666 } 667 668 bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) { 669 if (ND && ND->getFormalLinkage() == InternalLinkage && 670 !ND->isExternallyVisible() && 671 getEffectiveDeclContext(ND)->isFileContext() && 672 !ND->isInAnonymousNamespace()) 673 return true; 674 return false; 675 } 676 677 // Check if this Function Decl needs a unique internal linkage name. 678 bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl( 679 const NamedDecl *ND) { 680 if (!NeedsUniqueInternalLinkageNames || !ND) 681 return false; 682 683 const auto *FD = dyn_cast<FunctionDecl>(ND); 684 if (!FD) 685 return false; 686 687 // For C functions without prototypes, return false as their 688 // names should not be mangled. 689 if (!FD->getType()->getAs<FunctionProtoType>()) 690 return false; 691 692 if (isInternalLinkageDecl(ND)) 693 return true; 694 695 return false; 696 } 697 698 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) { 699 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 700 LanguageLinkage L = FD->getLanguageLinkage(); 701 // Overloadable functions need mangling. 702 if (FD->hasAttr<OverloadableAttr>()) 703 return true; 704 705 // "main" is not mangled. 706 if (FD->isMain()) 707 return false; 708 709 // The Windows ABI expects that we would never mangle "typical" 710 // user-defined entry points regardless of visibility or freestanding-ness. 711 // 712 // N.B. This is distinct from asking about "main". "main" has a lot of 713 // special rules associated with it in the standard while these 714 // user-defined entry points are outside of the purview of the standard. 715 // For example, there can be only one definition for "main" in a standards 716 // compliant program; however nothing forbids the existence of wmain and 717 // WinMain in the same translation unit. 718 if (FD->isMSVCRTEntryPoint()) 719 return false; 720 721 // C++ functions and those whose names are not a simple identifier need 722 // mangling. 723 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage) 724 return true; 725 726 // C functions are not mangled. 727 if (L == CLanguageLinkage) 728 return false; 729 } 730 731 // Otherwise, no mangling is done outside C++ mode. 732 if (!getASTContext().getLangOpts().CPlusPlus) 733 return false; 734 735 if (const auto *VD = dyn_cast<VarDecl>(D)) { 736 // Decompositions are mangled. 737 if (isa<DecompositionDecl>(VD)) 738 return true; 739 740 // C variables are not mangled. 741 if (VD->isExternC()) 742 return false; 743 744 // Variables at global scope are not mangled unless they have internal 745 // linkage or are specializations or are attached to a named module. 746 const DeclContext *DC = getEffectiveDeclContext(D); 747 // Check for extern variable declared locally. 748 if (DC->isFunctionOrMethod() && D->hasLinkage()) 749 while (!DC->isFileContext()) 750 DC = getEffectiveParentContext(DC); 751 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage && 752 !CXXNameMangler::shouldHaveAbiTags(*this, VD) && 753 !isa<VarTemplateSpecializationDecl>(VD) && 754 !VD->getOwningModuleForLinkage()) 755 return false; 756 } 757 758 return true; 759 } 760 761 void CXXNameMangler::writeAbiTags(const NamedDecl *ND, 762 const AbiTagList *AdditionalAbiTags) { 763 assert(AbiTags && "require AbiTagState"); 764 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags); 765 } 766 767 void CXXNameMangler::mangleSourceNameWithAbiTags( 768 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) { 769 mangleSourceName(ND->getIdentifier()); 770 writeAbiTags(ND, AdditionalAbiTags); 771 } 772 773 void CXXNameMangler::mangle(GlobalDecl GD) { 774 // <mangled-name> ::= _Z <encoding> 775 // ::= <data name> 776 // ::= <special-name> 777 Out << "_Z"; 778 if (isa<FunctionDecl>(GD.getDecl())) 779 mangleFunctionEncoding(GD); 780 else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl, 781 BindingDecl>(GD.getDecl())) 782 mangleName(GD); 783 else if (const IndirectFieldDecl *IFD = 784 dyn_cast<IndirectFieldDecl>(GD.getDecl())) 785 mangleName(IFD->getAnonField()); 786 else 787 llvm_unreachable("unexpected kind of global decl"); 788 } 789 790 void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) { 791 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 792 // <encoding> ::= <function name> <bare-function-type> 793 794 // Don't mangle in the type if this isn't a decl we should typically mangle. 795 if (!Context.shouldMangleDeclName(FD)) { 796 mangleName(GD); 797 return; 798 } 799 800 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD); 801 if (ReturnTypeAbiTags.empty()) { 802 // There are no tags for return type, the simplest case. 803 mangleName(GD); 804 mangleFunctionEncodingBareType(FD); 805 return; 806 } 807 808 // Mangle function name and encoding to temporary buffer. 809 // We have to output name and encoding to the same mangler to get the same 810 // substitution as it will be in final mangling. 811 SmallString<256> FunctionEncodingBuf; 812 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf); 813 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream); 814 // Output name of the function. 815 FunctionEncodingMangler.disableDerivedAbiTags(); 816 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr); 817 818 // Remember length of the function name in the buffer. 819 size_t EncodingPositionStart = FunctionEncodingStream.str().size(); 820 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD); 821 822 // Get tags from return type that are not present in function name or 823 // encoding. 824 const AbiTagList &UsedAbiTags = 825 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 826 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size()); 827 AdditionalAbiTags.erase( 828 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(), 829 UsedAbiTags.begin(), UsedAbiTags.end(), 830 AdditionalAbiTags.begin()), 831 AdditionalAbiTags.end()); 832 833 // Output name with implicit tags and function encoding from temporary buffer. 834 mangleNameWithAbiTags(FD, &AdditionalAbiTags); 835 Out << FunctionEncodingStream.str().substr(EncodingPositionStart); 836 837 // Function encoding could create new substitutions so we have to add 838 // temp mangled substitutions to main mangler. 839 extendSubstitutions(&FunctionEncodingMangler); 840 } 841 842 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) { 843 if (FD->hasAttr<EnableIfAttr>()) { 844 FunctionTypeDepthState Saved = FunctionTypeDepth.push(); 845 Out << "Ua9enable_ifI"; 846 for (AttrVec::const_iterator I = FD->getAttrs().begin(), 847 E = FD->getAttrs().end(); 848 I != E; ++I) { 849 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I); 850 if (!EIA) 851 continue; 852 if (Context.getASTContext().getLangOpts().getClangABICompat() > 853 LangOptions::ClangABI::Ver11) { 854 mangleTemplateArgExpr(EIA->getCond()); 855 } else { 856 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument, 857 // even though <template-arg> should not include an X/E around 858 // <expr-primary>. 859 Out << 'X'; 860 mangleExpression(EIA->getCond()); 861 Out << 'E'; 862 } 863 } 864 Out << 'E'; 865 FunctionTypeDepth.pop(Saved); 866 } 867 868 // When mangling an inheriting constructor, the bare function type used is 869 // that of the inherited constructor. 870 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) 871 if (auto Inherited = CD->getInheritedConstructor()) 872 FD = Inherited.getConstructor(); 873 874 // Whether the mangling of a function type includes the return type depends on 875 // the context and the nature of the function. The rules for deciding whether 876 // the return type is included are: 877 // 878 // 1. Template functions (names or types) have return types encoded, with 879 // the exceptions listed below. 880 // 2. Function types not appearing as part of a function name mangling, 881 // e.g. parameters, pointer types, etc., have return type encoded, with the 882 // exceptions listed below. 883 // 3. Non-template function names do not have return types encoded. 884 // 885 // The exceptions mentioned in (1) and (2) above, for which the return type is 886 // never included, are 887 // 1. Constructors. 888 // 2. Destructors. 889 // 3. Conversion operator functions, e.g. operator int. 890 bool MangleReturnType = false; 891 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) { 892 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) || 893 isa<CXXConversionDecl>(FD))) 894 MangleReturnType = true; 895 896 // Mangle the type of the primary template. 897 FD = PrimaryTemplate->getTemplatedDecl(); 898 } 899 900 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(), 901 MangleReturnType, FD); 902 } 903 904 /// Return whether a given namespace is the 'std' namespace. 905 bool CXXNameMangler::isStd(const NamespaceDecl *NS) { 906 if (!Context.getEffectiveParentContext(NS)->isTranslationUnit()) 907 return false; 908 909 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); 910 return II && II->isStr("std"); 911 } 912 913 // isStdNamespace - Return whether a given decl context is a toplevel 'std' 914 // namespace. 915 bool CXXNameMangler::isStdNamespace(const DeclContext *DC) { 916 if (!DC->isNamespace()) 917 return false; 918 919 return isStd(cast<NamespaceDecl>(DC)); 920 } 921 922 static const GlobalDecl 923 isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) { 924 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 925 // Check if we have a function template. 926 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 927 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) { 928 TemplateArgs = FD->getTemplateSpecializationArgs(); 929 return GD.getWithDecl(TD); 930 } 931 } 932 933 // Check if we have a class template. 934 if (const ClassTemplateSpecializationDecl *Spec = 935 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 936 TemplateArgs = &Spec->getTemplateArgs(); 937 return GD.getWithDecl(Spec->getSpecializedTemplate()); 938 } 939 940 // Check if we have a variable template. 941 if (const VarTemplateSpecializationDecl *Spec = 942 dyn_cast<VarTemplateSpecializationDecl>(ND)) { 943 TemplateArgs = &Spec->getTemplateArgs(); 944 return GD.getWithDecl(Spec->getSpecializedTemplate()); 945 } 946 947 return GlobalDecl(); 948 } 949 950 static TemplateName asTemplateName(GlobalDecl GD) { 951 const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl()); 952 return TemplateName(const_cast<TemplateDecl*>(TD)); 953 } 954 955 void CXXNameMangler::mangleName(GlobalDecl GD) { 956 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 957 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 958 // Variables should have implicit tags from its type. 959 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD); 960 if (VariableTypeAbiTags.empty()) { 961 // Simple case no variable type tags. 962 mangleNameWithAbiTags(VD, nullptr); 963 return; 964 } 965 966 // Mangle variable name to null stream to collect tags. 967 llvm::raw_null_ostream NullOutStream; 968 CXXNameMangler VariableNameMangler(*this, NullOutStream); 969 VariableNameMangler.disableDerivedAbiTags(); 970 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr); 971 972 // Get tags from variable type that are not present in its name. 973 const AbiTagList &UsedAbiTags = 974 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 975 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size()); 976 AdditionalAbiTags.erase( 977 std::set_difference(VariableTypeAbiTags.begin(), 978 VariableTypeAbiTags.end(), UsedAbiTags.begin(), 979 UsedAbiTags.end(), AdditionalAbiTags.begin()), 980 AdditionalAbiTags.end()); 981 982 // Output name with implicit tags. 983 mangleNameWithAbiTags(VD, &AdditionalAbiTags); 984 } else { 985 mangleNameWithAbiTags(GD, nullptr); 986 } 987 } 988 989 const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) { 990 const DeclContext *DC = Context.getEffectiveDeclContext(D); 991 while (!DC->isNamespace() && !DC->isTranslationUnit()) { 992 if (isLocalContainerContext(DC)) 993 return dyn_cast<RecordDecl>(D); 994 D = cast<Decl>(DC); 995 DC = Context.getEffectiveDeclContext(D); 996 } 997 return nullptr; 998 } 999 1000 void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD, 1001 const AbiTagList *AdditionalAbiTags) { 1002 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 1003 // <name> ::= [<module-name>] <nested-name> 1004 // ::= [<module-name>] <unscoped-name> 1005 // ::= [<module-name>] <unscoped-template-name> <template-args> 1006 // ::= <local-name> 1007 // 1008 const DeclContext *DC = Context.getEffectiveDeclContext(ND); 1009 1010 // If this is an extern variable declared locally, the relevant DeclContext 1011 // is that of the containing namespace, or the translation unit. 1012 // FIXME: This is a hack; extern variables declared locally should have 1013 // a proper semantic declaration context! 1014 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND)) 1015 while (!DC->isNamespace() && !DC->isTranslationUnit()) 1016 DC = Context.getEffectiveParentContext(DC); 1017 else if (GetLocalClassDecl(ND)) { 1018 mangleLocalName(GD, AdditionalAbiTags); 1019 return; 1020 } 1021 1022 assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl"); 1023 1024 if (isLocalContainerContext(DC)) { 1025 mangleLocalName(GD, AdditionalAbiTags); 1026 return; 1027 } 1028 1029 // Closures can require a nested-name mangling even if they're semantically 1030 // in the global namespace. 1031 if (const NamedDecl *PrefixND = getClosurePrefix(ND)) { 1032 mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags); 1033 return; 1034 } 1035 1036 if (DC->isTranslationUnit() || isStdNamespace(DC)) { 1037 // Check if we have a template. 1038 const TemplateArgumentList *TemplateArgs = nullptr; 1039 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) { 1040 mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags); 1041 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 1042 return; 1043 } 1044 1045 mangleUnscopedName(GD, DC, AdditionalAbiTags); 1046 return; 1047 } 1048 1049 mangleNestedName(GD, DC, AdditionalAbiTags); 1050 } 1051 1052 void CXXNameMangler::mangleModuleName(const NamedDecl *ND) { 1053 if (ND->isExternallyVisible()) 1054 if (Module *M = ND->getOwningModuleForLinkage()) 1055 mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName()); 1056 } 1057 1058 // <module-name> ::= <module-subname> 1059 // ::= <module-name> <module-subname> 1060 // ::= <substitution> 1061 // <module-subname> ::= W <source-name> 1062 // ::= W P <source-name> 1063 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) { 1064 // <substitution> ::= S <seq-id> _ 1065 auto It = ModuleSubstitutions.find(Name); 1066 if (It != ModuleSubstitutions.end()) { 1067 Out << 'S'; 1068 mangleSeqID(It->second); 1069 return; 1070 } 1071 1072 // FIXME: Preserve hierarchy in module names rather than flattening 1073 // them to strings; use Module*s as substitution keys. 1074 auto Parts = Name.rsplit('.'); 1075 if (Parts.second.empty()) 1076 Parts.second = Parts.first; 1077 else { 1078 mangleModuleNamePrefix(Parts.first, IsPartition); 1079 IsPartition = false; 1080 } 1081 1082 Out << 'W'; 1083 if (IsPartition) 1084 Out << 'P'; 1085 Out << Parts.second.size() << Parts.second; 1086 ModuleSubstitutions.insert({Name, SeqID++}); 1087 } 1088 1089 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD, 1090 const TemplateArgument *TemplateArgs, 1091 unsigned NumTemplateArgs) { 1092 const DeclContext *DC = Context.getEffectiveDeclContext(TD); 1093 1094 if (DC->isTranslationUnit() || isStdNamespace(DC)) { 1095 mangleUnscopedTemplateName(TD, DC, nullptr); 1096 mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs); 1097 } else { 1098 mangleNestedName(TD, TemplateArgs, NumTemplateArgs); 1099 } 1100 } 1101 1102 void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC, 1103 const AbiTagList *AdditionalAbiTags) { 1104 // <unscoped-name> ::= <unqualified-name> 1105 // ::= St <unqualified-name> # ::std:: 1106 1107 assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl"); 1108 if (isStdNamespace(DC)) 1109 Out << "St"; 1110 1111 mangleUnqualifiedName(GD, DC, AdditionalAbiTags); 1112 } 1113 1114 void CXXNameMangler::mangleUnscopedTemplateName( 1115 GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) { 1116 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl()); 1117 // <unscoped-template-name> ::= <unscoped-name> 1118 // ::= <substitution> 1119 if (mangleSubstitution(ND)) 1120 return; 1121 1122 // <template-template-param> ::= <template-param> 1123 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) { 1124 assert(!AdditionalAbiTags && 1125 "template template param cannot have abi tags"); 1126 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 1127 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) { 1128 mangleUnscopedName(GD, DC, AdditionalAbiTags); 1129 } else { 1130 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC, 1131 AdditionalAbiTags); 1132 } 1133 1134 addSubstitution(ND); 1135 } 1136 1137 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) { 1138 // ABI: 1139 // Floating-point literals are encoded using a fixed-length 1140 // lowercase hexadecimal string corresponding to the internal 1141 // representation (IEEE on Itanium), high-order bytes first, 1142 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f 1143 // on Itanium. 1144 // The 'without leading zeroes' thing seems to be an editorial 1145 // mistake; see the discussion on cxx-abi-dev beginning on 1146 // 2012-01-16. 1147 1148 // Our requirements here are just barely weird enough to justify 1149 // using a custom algorithm instead of post-processing APInt::toString(). 1150 1151 llvm::APInt valueBits = f.bitcastToAPInt(); 1152 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4; 1153 assert(numCharacters != 0); 1154 1155 // Allocate a buffer of the right number of characters. 1156 SmallVector<char, 20> buffer(numCharacters); 1157 1158 // Fill the buffer left-to-right. 1159 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) { 1160 // The bit-index of the next hex digit. 1161 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1); 1162 1163 // Project out 4 bits starting at 'digitIndex'. 1164 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64]; 1165 hexDigit >>= (digitBitIndex % 64); 1166 hexDigit &= 0xF; 1167 1168 // Map that over to a lowercase hex digit. 1169 static const char charForHex[16] = { 1170 '0', '1', '2', '3', '4', '5', '6', '7', 1171 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 1172 }; 1173 buffer[stringIndex] = charForHex[hexDigit]; 1174 } 1175 1176 Out.write(buffer.data(), numCharacters); 1177 } 1178 1179 void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) { 1180 Out << 'L'; 1181 mangleType(T); 1182 mangleFloat(V); 1183 Out << 'E'; 1184 } 1185 1186 void CXXNameMangler::mangleFixedPointLiteral() { 1187 DiagnosticsEngine &Diags = Context.getDiags(); 1188 unsigned DiagID = Diags.getCustomDiagID( 1189 DiagnosticsEngine::Error, "cannot mangle fixed point literals yet"); 1190 Diags.Report(DiagID); 1191 } 1192 1193 void CXXNameMangler::mangleNullPointer(QualType T) { 1194 // <expr-primary> ::= L <type> 0 E 1195 Out << 'L'; 1196 mangleType(T); 1197 Out << "0E"; 1198 } 1199 1200 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) { 1201 if (Value.isSigned() && Value.isNegative()) { 1202 Out << 'n'; 1203 Value.abs().print(Out, /*signed*/ false); 1204 } else { 1205 Value.print(Out, /*signed*/ false); 1206 } 1207 } 1208 1209 void CXXNameMangler::mangleNumber(int64_t Number) { 1210 // <number> ::= [n] <non-negative decimal integer> 1211 if (Number < 0) { 1212 Out << 'n'; 1213 Number = -Number; 1214 } 1215 1216 Out << Number; 1217 } 1218 1219 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) { 1220 // <call-offset> ::= h <nv-offset> _ 1221 // ::= v <v-offset> _ 1222 // <nv-offset> ::= <offset number> # non-virtual base override 1223 // <v-offset> ::= <offset number> _ <virtual offset number> 1224 // # virtual base override, with vcall offset 1225 if (!Virtual) { 1226 Out << 'h'; 1227 mangleNumber(NonVirtual); 1228 Out << '_'; 1229 return; 1230 } 1231 1232 Out << 'v'; 1233 mangleNumber(NonVirtual); 1234 Out << '_'; 1235 mangleNumber(Virtual); 1236 Out << '_'; 1237 } 1238 1239 void CXXNameMangler::manglePrefix(QualType type) { 1240 if (const auto *TST = type->getAs<TemplateSpecializationType>()) { 1241 if (!mangleSubstitution(QualType(TST, 0))) { 1242 mangleTemplatePrefix(TST->getTemplateName()); 1243 1244 // FIXME: GCC does not appear to mangle the template arguments when 1245 // the template in question is a dependent template name. Should we 1246 // emulate that badness? 1247 mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(), 1248 TST->getNumArgs()); 1249 addSubstitution(QualType(TST, 0)); 1250 } 1251 } else if (const auto *DTST = 1252 type->getAs<DependentTemplateSpecializationType>()) { 1253 if (!mangleSubstitution(QualType(DTST, 0))) { 1254 TemplateName Template = getASTContext().getDependentTemplateName( 1255 DTST->getQualifier(), DTST->getIdentifier()); 1256 mangleTemplatePrefix(Template); 1257 1258 // FIXME: GCC does not appear to mangle the template arguments when 1259 // the template in question is a dependent template name. Should we 1260 // emulate that badness? 1261 mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs()); 1262 addSubstitution(QualType(DTST, 0)); 1263 } 1264 } else { 1265 // We use the QualType mangle type variant here because it handles 1266 // substitutions. 1267 mangleType(type); 1268 } 1269 } 1270 1271 /// Mangle everything prior to the base-unresolved-name in an unresolved-name. 1272 /// 1273 /// \param recursive - true if this is being called recursively, 1274 /// i.e. if there is more prefix "to the right". 1275 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, 1276 bool recursive) { 1277 1278 // x, ::x 1279 // <unresolved-name> ::= [gs] <base-unresolved-name> 1280 1281 // T::x / decltype(p)::x 1282 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name> 1283 1284 // T::N::x /decltype(p)::N::x 1285 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E 1286 // <base-unresolved-name> 1287 1288 // A::x, N::y, A<T>::z; "gs" means leading "::" 1289 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E 1290 // <base-unresolved-name> 1291 1292 switch (qualifier->getKind()) { 1293 case NestedNameSpecifier::Global: 1294 Out << "gs"; 1295 1296 // We want an 'sr' unless this is the entire NNS. 1297 if (recursive) 1298 Out << "sr"; 1299 1300 // We never want an 'E' here. 1301 return; 1302 1303 case NestedNameSpecifier::Super: 1304 llvm_unreachable("Can't mangle __super specifier"); 1305 1306 case NestedNameSpecifier::Namespace: 1307 if (qualifier->getPrefix()) 1308 mangleUnresolvedPrefix(qualifier->getPrefix(), 1309 /*recursive*/ true); 1310 else 1311 Out << "sr"; 1312 mangleSourceNameWithAbiTags(qualifier->getAsNamespace()); 1313 break; 1314 case NestedNameSpecifier::NamespaceAlias: 1315 if (qualifier->getPrefix()) 1316 mangleUnresolvedPrefix(qualifier->getPrefix(), 1317 /*recursive*/ true); 1318 else 1319 Out << "sr"; 1320 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias()); 1321 break; 1322 1323 case NestedNameSpecifier::TypeSpec: 1324 case NestedNameSpecifier::TypeSpecWithTemplate: { 1325 const Type *type = qualifier->getAsType(); 1326 1327 // We only want to use an unresolved-type encoding if this is one of: 1328 // - a decltype 1329 // - a template type parameter 1330 // - a template template parameter with arguments 1331 // In all of these cases, we should have no prefix. 1332 if (qualifier->getPrefix()) { 1333 mangleUnresolvedPrefix(qualifier->getPrefix(), 1334 /*recursive*/ true); 1335 } else { 1336 // Otherwise, all the cases want this. 1337 Out << "sr"; 1338 } 1339 1340 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : "")) 1341 return; 1342 1343 break; 1344 } 1345 1346 case NestedNameSpecifier::Identifier: 1347 // Member expressions can have these without prefixes. 1348 if (qualifier->getPrefix()) 1349 mangleUnresolvedPrefix(qualifier->getPrefix(), 1350 /*recursive*/ true); 1351 else 1352 Out << "sr"; 1353 1354 mangleSourceName(qualifier->getAsIdentifier()); 1355 // An Identifier has no type information, so we can't emit abi tags for it. 1356 break; 1357 } 1358 1359 // If this was the innermost part of the NNS, and we fell out to 1360 // here, append an 'E'. 1361 if (!recursive) 1362 Out << 'E'; 1363 } 1364 1365 /// Mangle an unresolved-name, which is generally used for names which 1366 /// weren't resolved to specific entities. 1367 void CXXNameMangler::mangleUnresolvedName( 1368 NestedNameSpecifier *qualifier, DeclarationName name, 1369 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs, 1370 unsigned knownArity) { 1371 if (qualifier) mangleUnresolvedPrefix(qualifier); 1372 switch (name.getNameKind()) { 1373 // <base-unresolved-name> ::= <simple-id> 1374 case DeclarationName::Identifier: 1375 mangleSourceName(name.getAsIdentifierInfo()); 1376 break; 1377 // <base-unresolved-name> ::= dn <destructor-name> 1378 case DeclarationName::CXXDestructorName: 1379 Out << "dn"; 1380 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType()); 1381 break; 1382 // <base-unresolved-name> ::= on <operator-name> 1383 case DeclarationName::CXXConversionFunctionName: 1384 case DeclarationName::CXXLiteralOperatorName: 1385 case DeclarationName::CXXOperatorName: 1386 Out << "on"; 1387 mangleOperatorName(name, knownArity); 1388 break; 1389 case DeclarationName::CXXConstructorName: 1390 llvm_unreachable("Can't mangle a constructor name!"); 1391 case DeclarationName::CXXUsingDirective: 1392 llvm_unreachable("Can't mangle a using directive name!"); 1393 case DeclarationName::CXXDeductionGuideName: 1394 llvm_unreachable("Can't mangle a deduction guide name!"); 1395 case DeclarationName::ObjCMultiArgSelector: 1396 case DeclarationName::ObjCOneArgSelector: 1397 case DeclarationName::ObjCZeroArgSelector: 1398 llvm_unreachable("Can't mangle Objective-C selector names here!"); 1399 } 1400 1401 // The <simple-id> and on <operator-name> productions end in an optional 1402 // <template-args>. 1403 if (TemplateArgs) 1404 mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs); 1405 } 1406 1407 void CXXNameMangler::mangleUnqualifiedName( 1408 GlobalDecl GD, DeclarationName Name, const DeclContext *DC, 1409 unsigned KnownArity, const AbiTagList *AdditionalAbiTags) { 1410 const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl()); 1411 // <unqualified-name> ::= [<module-name>] <operator-name> 1412 // ::= <ctor-dtor-name> 1413 // ::= [<module-name>] <source-name> 1414 // ::= [<module-name>] DC <source-name>* E 1415 1416 if (ND && DC && DC->isFileContext()) 1417 mangleModuleName(ND); 1418 1419 unsigned Arity = KnownArity; 1420 switch (Name.getNameKind()) { 1421 case DeclarationName::Identifier: { 1422 const IdentifierInfo *II = Name.getAsIdentifierInfo(); 1423 1424 // We mangle decomposition declarations as the names of their bindings. 1425 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) { 1426 // FIXME: Non-standard mangling for decomposition declarations: 1427 // 1428 // <unqualified-name> ::= DC <source-name>* E 1429 // 1430 // Proposed on cxx-abi-dev on 2016-08-12 1431 Out << "DC"; 1432 for (auto *BD : DD->bindings()) 1433 mangleSourceName(BD->getDeclName().getAsIdentifierInfo()); 1434 Out << 'E'; 1435 writeAbiTags(ND, AdditionalAbiTags); 1436 break; 1437 } 1438 1439 if (auto *GD = dyn_cast<MSGuidDecl>(ND)) { 1440 // We follow MSVC in mangling GUID declarations as if they were variables 1441 // with a particular reserved name. Continue the pretense here. 1442 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID; 1443 llvm::raw_svector_ostream GUIDOS(GUID); 1444 Context.mangleMSGuidDecl(GD, GUIDOS); 1445 Out << GUID.size() << GUID; 1446 break; 1447 } 1448 1449 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) { 1450 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63. 1451 Out << "TA"; 1452 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(), 1453 TPO->getValue(), /*TopLevel=*/true); 1454 break; 1455 } 1456 1457 if (II) { 1458 // Match GCC's naming convention for internal linkage symbols, for 1459 // symbols that are not actually visible outside of this TU. GCC 1460 // distinguishes between internal and external linkage symbols in 1461 // its mangling, to support cases like this that were valid C++ prior 1462 // to DR426: 1463 // 1464 // void test() { extern void foo(); } 1465 // static void foo(); 1466 // 1467 // Don't bother with the L marker for names in anonymous namespaces; the 1468 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better 1469 // matches GCC anyway, because GCC does not treat anonymous namespaces as 1470 // implying internal linkage. 1471 if (Context.isInternalLinkageDecl(ND)) 1472 Out << 'L'; 1473 1474 auto *FD = dyn_cast<FunctionDecl>(ND); 1475 bool IsRegCall = FD && 1476 FD->getType()->castAs<FunctionType>()->getCallConv() == 1477 clang::CC_X86RegCall; 1478 bool IsDeviceStub = 1479 FD && FD->hasAttr<CUDAGlobalAttr>() && 1480 GD.getKernelReferenceKind() == KernelReferenceKind::Stub; 1481 if (IsDeviceStub) 1482 mangleDeviceStubName(II); 1483 else if (IsRegCall) 1484 mangleRegCallName(II); 1485 else 1486 mangleSourceName(II); 1487 1488 writeAbiTags(ND, AdditionalAbiTags); 1489 break; 1490 } 1491 1492 // Otherwise, an anonymous entity. We must have a declaration. 1493 assert(ND && "mangling empty name without declaration"); 1494 1495 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 1496 if (NS->isAnonymousNamespace()) { 1497 // This is how gcc mangles these names. 1498 Out << "12_GLOBAL__N_1"; 1499 break; 1500 } 1501 } 1502 1503 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1504 // We must have an anonymous union or struct declaration. 1505 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl(); 1506 1507 // Itanium C++ ABI 5.1.2: 1508 // 1509 // For the purposes of mangling, the name of an anonymous union is 1510 // considered to be the name of the first named data member found by a 1511 // pre-order, depth-first, declaration-order walk of the data members of 1512 // the anonymous union. If there is no such data member (i.e., if all of 1513 // the data members in the union are unnamed), then there is no way for 1514 // a program to refer to the anonymous union, and there is therefore no 1515 // need to mangle its name. 1516 assert(RD->isAnonymousStructOrUnion() 1517 && "Expected anonymous struct or union!"); 1518 const FieldDecl *FD = RD->findFirstNamedDataMember(); 1519 1520 // It's actually possible for various reasons for us to get here 1521 // with an empty anonymous struct / union. Fortunately, it 1522 // doesn't really matter what name we generate. 1523 if (!FD) break; 1524 assert(FD->getIdentifier() && "Data member name isn't an identifier!"); 1525 1526 mangleSourceName(FD->getIdentifier()); 1527 // Not emitting abi tags: internal name anyway. 1528 break; 1529 } 1530 1531 // Class extensions have no name as a category, and it's possible 1532 // for them to be the semantic parent of certain declarations 1533 // (primarily, tag decls defined within declarations). Such 1534 // declarations will always have internal linkage, so the name 1535 // doesn't really matter, but we shouldn't crash on them. For 1536 // safety, just handle all ObjC containers here. 1537 if (isa<ObjCContainerDecl>(ND)) 1538 break; 1539 1540 // We must have an anonymous struct. 1541 const TagDecl *TD = cast<TagDecl>(ND); 1542 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { 1543 assert(TD->getDeclContext() == D->getDeclContext() && 1544 "Typedef should not be in another decl context!"); 1545 assert(D->getDeclName().getAsIdentifierInfo() && 1546 "Typedef was not named!"); 1547 mangleSourceName(D->getDeclName().getAsIdentifierInfo()); 1548 assert(!AdditionalAbiTags && "Type cannot have additional abi tags"); 1549 // Explicit abi tags are still possible; take from underlying type, not 1550 // from typedef. 1551 writeAbiTags(TD, nullptr); 1552 break; 1553 } 1554 1555 // <unnamed-type-name> ::= <closure-type-name> 1556 // 1557 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ 1558 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+ 1559 // # Parameter types or 'v' for 'void'. 1560 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { 1561 llvm::Optional<unsigned> DeviceNumber = 1562 Context.getDiscriminatorOverride()(Context.getASTContext(), Record); 1563 1564 // If we have a device-number via the discriminator, use that to mangle 1565 // the lambda, otherwise use the typical lambda-mangling-number. In either 1566 // case, a '0' should be mangled as a normal unnamed class instead of as a 1567 // lambda. 1568 if (Record->isLambda() && 1569 ((DeviceNumber && *DeviceNumber > 0) || 1570 (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) { 1571 assert(!AdditionalAbiTags && 1572 "Lambda type cannot have additional abi tags"); 1573 mangleLambda(Record); 1574 break; 1575 } 1576 } 1577 1578 if (TD->isExternallyVisible()) { 1579 unsigned UnnamedMangle = 1580 getASTContext().getManglingNumber(TD, Context.isAux()); 1581 Out << "Ut"; 1582 if (UnnamedMangle > 1) 1583 Out << UnnamedMangle - 2; 1584 Out << '_'; 1585 writeAbiTags(TD, AdditionalAbiTags); 1586 break; 1587 } 1588 1589 // Get a unique id for the anonymous struct. If it is not a real output 1590 // ID doesn't matter so use fake one. 1591 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD); 1592 1593 // Mangle it as a source name in the form 1594 // [n] $_<id> 1595 // where n is the length of the string. 1596 SmallString<8> Str; 1597 Str += "$_"; 1598 Str += llvm::utostr(AnonStructId); 1599 1600 Out << Str.size(); 1601 Out << Str; 1602 break; 1603 } 1604 1605 case DeclarationName::ObjCZeroArgSelector: 1606 case DeclarationName::ObjCOneArgSelector: 1607 case DeclarationName::ObjCMultiArgSelector: 1608 llvm_unreachable("Can't mangle Objective-C selector names here!"); 1609 1610 case DeclarationName::CXXConstructorName: { 1611 const CXXRecordDecl *InheritedFrom = nullptr; 1612 TemplateName InheritedTemplateName; 1613 const TemplateArgumentList *InheritedTemplateArgs = nullptr; 1614 if (auto Inherited = 1615 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) { 1616 InheritedFrom = Inherited.getConstructor()->getParent(); 1617 InheritedTemplateName = 1618 TemplateName(Inherited.getConstructor()->getPrimaryTemplate()); 1619 InheritedTemplateArgs = 1620 Inherited.getConstructor()->getTemplateSpecializationArgs(); 1621 } 1622 1623 if (ND == Structor) 1624 // If the named decl is the C++ constructor we're mangling, use the type 1625 // we were given. 1626 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom); 1627 else 1628 // Otherwise, use the complete constructor name. This is relevant if a 1629 // class with a constructor is declared within a constructor. 1630 mangleCXXCtorType(Ctor_Complete, InheritedFrom); 1631 1632 // FIXME: The template arguments are part of the enclosing prefix or 1633 // nested-name, but it's more convenient to mangle them here. 1634 if (InheritedTemplateArgs) 1635 mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs); 1636 1637 writeAbiTags(ND, AdditionalAbiTags); 1638 break; 1639 } 1640 1641 case DeclarationName::CXXDestructorName: 1642 if (ND == Structor) 1643 // If the named decl is the C++ destructor we're mangling, use the type we 1644 // were given. 1645 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType)); 1646 else 1647 // Otherwise, use the complete destructor name. This is relevant if a 1648 // class with a destructor is declared within a destructor. 1649 mangleCXXDtorType(Dtor_Complete); 1650 writeAbiTags(ND, AdditionalAbiTags); 1651 break; 1652 1653 case DeclarationName::CXXOperatorName: 1654 if (ND && Arity == UnknownArity) { 1655 Arity = cast<FunctionDecl>(ND)->getNumParams(); 1656 1657 // If we have a member function, we need to include the 'this' pointer. 1658 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND)) 1659 if (!MD->isStatic()) 1660 Arity++; 1661 } 1662 LLVM_FALLTHROUGH; 1663 case DeclarationName::CXXConversionFunctionName: 1664 case DeclarationName::CXXLiteralOperatorName: 1665 mangleOperatorName(Name, Arity); 1666 writeAbiTags(ND, AdditionalAbiTags); 1667 break; 1668 1669 case DeclarationName::CXXDeductionGuideName: 1670 llvm_unreachable("Can't mangle a deduction guide name!"); 1671 1672 case DeclarationName::CXXUsingDirective: 1673 llvm_unreachable("Can't mangle a using directive name!"); 1674 } 1675 } 1676 1677 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) { 1678 // <source-name> ::= <positive length number> __regcall3__ <identifier> 1679 // <number> ::= [n] <non-negative decimal integer> 1680 // <identifier> ::= <unqualified source code identifier> 1681 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__" 1682 << II->getName(); 1683 } 1684 1685 void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) { 1686 // <source-name> ::= <positive length number> __device_stub__ <identifier> 1687 // <number> ::= [n] <non-negative decimal integer> 1688 // <identifier> ::= <unqualified source code identifier> 1689 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__" 1690 << II->getName(); 1691 } 1692 1693 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) { 1694 // <source-name> ::= <positive length number> <identifier> 1695 // <number> ::= [n] <non-negative decimal integer> 1696 // <identifier> ::= <unqualified source code identifier> 1697 Out << II->getLength() << II->getName(); 1698 } 1699 1700 void CXXNameMangler::mangleNestedName(GlobalDecl GD, 1701 const DeclContext *DC, 1702 const AbiTagList *AdditionalAbiTags, 1703 bool NoFunction) { 1704 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 1705 // <nested-name> 1706 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E 1707 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> 1708 // <template-args> E 1709 1710 Out << 'N'; 1711 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) { 1712 Qualifiers MethodQuals = Method->getMethodQualifiers(); 1713 // We do not consider restrict a distinguishing attribute for overloading 1714 // purposes so we must not mangle it. 1715 MethodQuals.removeRestrict(); 1716 mangleQualifiers(MethodQuals); 1717 mangleRefQualifier(Method->getRefQualifier()); 1718 } 1719 1720 // Check if we have a template. 1721 const TemplateArgumentList *TemplateArgs = nullptr; 1722 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) { 1723 mangleTemplatePrefix(TD, NoFunction); 1724 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 1725 } else { 1726 manglePrefix(DC, NoFunction); 1727 mangleUnqualifiedName(GD, DC, AdditionalAbiTags); 1728 } 1729 1730 Out << 'E'; 1731 } 1732 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD, 1733 const TemplateArgument *TemplateArgs, 1734 unsigned NumTemplateArgs) { 1735 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E 1736 1737 Out << 'N'; 1738 1739 mangleTemplatePrefix(TD); 1740 mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs); 1741 1742 Out << 'E'; 1743 } 1744 1745 void CXXNameMangler::mangleNestedNameWithClosurePrefix( 1746 GlobalDecl GD, const NamedDecl *PrefixND, 1747 const AbiTagList *AdditionalAbiTags) { 1748 // A <closure-prefix> represents a variable or field, not a regular 1749 // DeclContext, so needs special handling. In this case we're mangling a 1750 // limited form of <nested-name>: 1751 // 1752 // <nested-name> ::= N <closure-prefix> <closure-type-name> E 1753 1754 Out << 'N'; 1755 1756 mangleClosurePrefix(PrefixND); 1757 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags); 1758 1759 Out << 'E'; 1760 } 1761 1762 static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) { 1763 GlobalDecl GD; 1764 // The Itanium spec says: 1765 // For entities in constructors and destructors, the mangling of the 1766 // complete object constructor or destructor is used as the base function 1767 // name, i.e. the C1 or D1 version. 1768 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 1769 GD = GlobalDecl(CD, Ctor_Complete); 1770 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 1771 GD = GlobalDecl(DD, Dtor_Complete); 1772 else 1773 GD = GlobalDecl(cast<FunctionDecl>(DC)); 1774 return GD; 1775 } 1776 1777 void CXXNameMangler::mangleLocalName(GlobalDecl GD, 1778 const AbiTagList *AdditionalAbiTags) { 1779 const Decl *D = GD.getDecl(); 1780 // <local-name> := Z <function encoding> E <entity name> [<discriminator>] 1781 // := Z <function encoding> E s [<discriminator>] 1782 // <local-name> := Z <function encoding> E d [ <parameter number> ] 1783 // _ <entity name> 1784 // <discriminator> := _ <non-negative number> 1785 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D)); 1786 const RecordDecl *RD = GetLocalClassDecl(D); 1787 const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D); 1788 1789 Out << 'Z'; 1790 1791 { 1792 AbiTagState LocalAbiTags(AbiTags); 1793 1794 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) 1795 mangleObjCMethodName(MD); 1796 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) 1797 mangleBlockForPrefix(BD); 1798 else 1799 mangleFunctionEncoding(getParentOfLocalEntity(DC)); 1800 1801 // Implicit ABI tags (from namespace) are not available in the following 1802 // entity; reset to actually emitted tags, which are available. 1803 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags()); 1804 } 1805 1806 Out << 'E'; 1807 1808 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 1809 // be a bug that is fixed in trunk. 1810 1811 if (RD) { 1812 // The parameter number is omitted for the last parameter, 0 for the 1813 // second-to-last parameter, 1 for the third-to-last parameter, etc. The 1814 // <entity name> will of course contain a <closure-type-name>: Its 1815 // numbering will be local to the particular argument in which it appears 1816 // -- other default arguments do not affect its encoding. 1817 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1818 if (CXXRD && CXXRD->isLambda()) { 1819 if (const ParmVarDecl *Parm 1820 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) { 1821 if (const FunctionDecl *Func 1822 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) { 1823 Out << 'd'; 1824 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); 1825 if (Num > 1) 1826 mangleNumber(Num - 2); 1827 Out << '_'; 1828 } 1829 } 1830 } 1831 1832 // Mangle the name relative to the closest enclosing function. 1833 // equality ok because RD derived from ND above 1834 if (D == RD) { 1835 mangleUnqualifiedName(RD, DC, AdditionalAbiTags); 1836 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 1837 if (const NamedDecl *PrefixND = getClosurePrefix(BD)) 1838 mangleClosurePrefix(PrefixND, true /*NoFunction*/); 1839 else 1840 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/); 1841 assert(!AdditionalAbiTags && "Block cannot have additional abi tags"); 1842 mangleUnqualifiedBlock(BD); 1843 } else { 1844 const NamedDecl *ND = cast<NamedDecl>(D); 1845 mangleNestedName(GD, Context.getEffectiveDeclContext(ND), 1846 AdditionalAbiTags, true /*NoFunction*/); 1847 } 1848 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 1849 // Mangle a block in a default parameter; see above explanation for 1850 // lambdas. 1851 if (const ParmVarDecl *Parm 1852 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) { 1853 if (const FunctionDecl *Func 1854 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) { 1855 Out << 'd'; 1856 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); 1857 if (Num > 1) 1858 mangleNumber(Num - 2); 1859 Out << '_'; 1860 } 1861 } 1862 1863 assert(!AdditionalAbiTags && "Block cannot have additional abi tags"); 1864 mangleUnqualifiedBlock(BD); 1865 } else { 1866 mangleUnqualifiedName(GD, DC, AdditionalAbiTags); 1867 } 1868 1869 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) { 1870 unsigned disc; 1871 if (Context.getNextDiscriminator(ND, disc)) { 1872 if (disc < 10) 1873 Out << '_' << disc; 1874 else 1875 Out << "__" << disc << '_'; 1876 } 1877 } 1878 } 1879 1880 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) { 1881 if (GetLocalClassDecl(Block)) { 1882 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr); 1883 return; 1884 } 1885 const DeclContext *DC = Context.getEffectiveDeclContext(Block); 1886 if (isLocalContainerContext(DC)) { 1887 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr); 1888 return; 1889 } 1890 if (const NamedDecl *PrefixND = getClosurePrefix(Block)) 1891 mangleClosurePrefix(PrefixND); 1892 else 1893 manglePrefix(DC); 1894 mangleUnqualifiedBlock(Block); 1895 } 1896 1897 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) { 1898 // When trying to be ABI-compatibility with clang 12 and before, mangle a 1899 // <data-member-prefix> now, with no substitutions and no <template-args>. 1900 if (Decl *Context = Block->getBlockManglingContextDecl()) { 1901 if (getASTContext().getLangOpts().getClangABICompat() <= 1902 LangOptions::ClangABI::Ver12 && 1903 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) && 1904 Context->getDeclContext()->isRecord()) { 1905 const auto *ND = cast<NamedDecl>(Context); 1906 if (ND->getIdentifier()) { 1907 mangleSourceNameWithAbiTags(ND); 1908 Out << 'M'; 1909 } 1910 } 1911 } 1912 1913 // If we have a block mangling number, use it. 1914 unsigned Number = Block->getBlockManglingNumber(); 1915 // Otherwise, just make up a number. It doesn't matter what it is because 1916 // the symbol in question isn't externally visible. 1917 if (!Number) 1918 Number = Context.getBlockId(Block, false); 1919 else { 1920 // Stored mangling numbers are 1-based. 1921 --Number; 1922 } 1923 Out << "Ub"; 1924 if (Number > 0) 1925 Out << Number - 1; 1926 Out << '_'; 1927 } 1928 1929 // <template-param-decl> 1930 // ::= Ty # template type parameter 1931 // ::= Tn <type> # template non-type parameter 1932 // ::= Tt <template-param-decl>* E # template template parameter 1933 // ::= Tp <template-param-decl> # template parameter pack 1934 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) { 1935 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) { 1936 if (Ty->isParameterPack()) 1937 Out << "Tp"; 1938 Out << "Ty"; 1939 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) { 1940 if (Tn->isExpandedParameterPack()) { 1941 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) { 1942 Out << "Tn"; 1943 mangleType(Tn->getExpansionType(I)); 1944 } 1945 } else { 1946 QualType T = Tn->getType(); 1947 if (Tn->isParameterPack()) { 1948 Out << "Tp"; 1949 if (auto *PackExpansion = T->getAs<PackExpansionType>()) 1950 T = PackExpansion->getPattern(); 1951 } 1952 Out << "Tn"; 1953 mangleType(T); 1954 } 1955 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) { 1956 if (Tt->isExpandedParameterPack()) { 1957 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N; 1958 ++I) { 1959 Out << "Tt"; 1960 for (auto *Param : *Tt->getExpansionTemplateParameters(I)) 1961 mangleTemplateParamDecl(Param); 1962 Out << "E"; 1963 } 1964 } else { 1965 if (Tt->isParameterPack()) 1966 Out << "Tp"; 1967 Out << "Tt"; 1968 for (auto *Param : *Tt->getTemplateParameters()) 1969 mangleTemplateParamDecl(Param); 1970 Out << "E"; 1971 } 1972 } 1973 } 1974 1975 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { 1976 // When trying to be ABI-compatibility with clang 12 and before, mangle a 1977 // <data-member-prefix> now, with no substitutions. 1978 if (Decl *Context = Lambda->getLambdaContextDecl()) { 1979 if (getASTContext().getLangOpts().getClangABICompat() <= 1980 LangOptions::ClangABI::Ver12 && 1981 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) && 1982 !isa<ParmVarDecl>(Context)) { 1983 if (const IdentifierInfo *Name 1984 = cast<NamedDecl>(Context)->getIdentifier()) { 1985 mangleSourceName(Name); 1986 const TemplateArgumentList *TemplateArgs = nullptr; 1987 if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs)) 1988 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 1989 Out << 'M'; 1990 } 1991 } 1992 } 1993 1994 Out << "Ul"; 1995 mangleLambdaSig(Lambda); 1996 Out << "E"; 1997 1998 // The number is omitted for the first closure type with a given 1999 // <lambda-sig> in a given context; it is n-2 for the nth closure type 2000 // (in lexical order) with that same <lambda-sig> and context. 2001 // 2002 // The AST keeps track of the number for us. 2003 // 2004 // In CUDA/HIP, to ensure the consistent lamba numbering between the device- 2005 // and host-side compilations, an extra device mangle context may be created 2006 // if the host-side CXX ABI has different numbering for lambda. In such case, 2007 // if the mangle context is that device-side one, use the device-side lambda 2008 // mangling number for this lambda. 2009 llvm::Optional<unsigned> DeviceNumber = 2010 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda); 2011 unsigned Number = 2012 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber(); 2013 2014 assert(Number > 0 && "Lambda should be mangled as an unnamed class"); 2015 if (Number > 1) 2016 mangleNumber(Number - 2); 2017 Out << '_'; 2018 } 2019 2020 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) { 2021 for (auto *D : Lambda->getLambdaExplicitTemplateParameters()) 2022 mangleTemplateParamDecl(D); 2023 auto *Proto = 2024 Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>(); 2025 mangleBareFunctionType(Proto, /*MangleReturnType=*/false, 2026 Lambda->getLambdaStaticInvoker()); 2027 } 2028 2029 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) { 2030 switch (qualifier->getKind()) { 2031 case NestedNameSpecifier::Global: 2032 // nothing 2033 return; 2034 2035 case NestedNameSpecifier::Super: 2036 llvm_unreachable("Can't mangle __super specifier"); 2037 2038 case NestedNameSpecifier::Namespace: 2039 mangleName(qualifier->getAsNamespace()); 2040 return; 2041 2042 case NestedNameSpecifier::NamespaceAlias: 2043 mangleName(qualifier->getAsNamespaceAlias()->getNamespace()); 2044 return; 2045 2046 case NestedNameSpecifier::TypeSpec: 2047 case NestedNameSpecifier::TypeSpecWithTemplate: 2048 manglePrefix(QualType(qualifier->getAsType(), 0)); 2049 return; 2050 2051 case NestedNameSpecifier::Identifier: 2052 // Clang 14 and before did not consider this substitutable. 2053 bool Clang14Compat = getASTContext().getLangOpts().getClangABICompat() <= 2054 LangOptions::ClangABI::Ver14; 2055 if (!Clang14Compat && mangleSubstitution(qualifier)) 2056 return; 2057 2058 // Member expressions can have these without prefixes, but that 2059 // should end up in mangleUnresolvedPrefix instead. 2060 assert(qualifier->getPrefix()); 2061 manglePrefix(qualifier->getPrefix()); 2062 2063 mangleSourceName(qualifier->getAsIdentifier()); 2064 2065 if (!Clang14Compat) 2066 addSubstitution(qualifier); 2067 return; 2068 } 2069 2070 llvm_unreachable("unexpected nested name specifier"); 2071 } 2072 2073 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { 2074 // <prefix> ::= <prefix> <unqualified-name> 2075 // ::= <template-prefix> <template-args> 2076 // ::= <closure-prefix> 2077 // ::= <template-param> 2078 // ::= # empty 2079 // ::= <substitution> 2080 2081 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl"); 2082 2083 if (DC->isTranslationUnit()) 2084 return; 2085 2086 if (NoFunction && isLocalContainerContext(DC)) 2087 return; 2088 2089 assert(!isLocalContainerContext(DC)); 2090 2091 const NamedDecl *ND = cast<NamedDecl>(DC); 2092 if (mangleSubstitution(ND)) 2093 return; 2094 2095 // Check if we have a template-prefix or a closure-prefix. 2096 const TemplateArgumentList *TemplateArgs = nullptr; 2097 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) { 2098 mangleTemplatePrefix(TD); 2099 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 2100 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) { 2101 mangleClosurePrefix(PrefixND, NoFunction); 2102 mangleUnqualifiedName(ND, nullptr, nullptr); 2103 } else { 2104 const DeclContext *DC = Context.getEffectiveDeclContext(ND); 2105 manglePrefix(DC, NoFunction); 2106 mangleUnqualifiedName(ND, DC, nullptr); 2107 } 2108 2109 addSubstitution(ND); 2110 } 2111 2112 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) { 2113 // <template-prefix> ::= <prefix> <template unqualified-name> 2114 // ::= <template-param> 2115 // ::= <substitution> 2116 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 2117 return mangleTemplatePrefix(TD); 2118 2119 DependentTemplateName *Dependent = Template.getAsDependentTemplateName(); 2120 assert(Dependent && "unexpected template name kind"); 2121 2122 // Clang 11 and before mangled the substitution for a dependent template name 2123 // after already having emitted (a substitution for) the prefix. 2124 bool Clang11Compat = getASTContext().getLangOpts().getClangABICompat() <= 2125 LangOptions::ClangABI::Ver11; 2126 if (!Clang11Compat && mangleSubstitution(Template)) 2127 return; 2128 2129 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier()) 2130 manglePrefix(Qualifier); 2131 2132 if (Clang11Compat && mangleSubstitution(Template)) 2133 return; 2134 2135 if (const IdentifierInfo *Id = Dependent->getIdentifier()) 2136 mangleSourceName(Id); 2137 else 2138 mangleOperatorName(Dependent->getOperator(), UnknownArity); 2139 2140 addSubstitution(Template); 2141 } 2142 2143 void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD, 2144 bool NoFunction) { 2145 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl()); 2146 // <template-prefix> ::= <prefix> <template unqualified-name> 2147 // ::= <template-param> 2148 // ::= <substitution> 2149 // <template-template-param> ::= <template-param> 2150 // <substitution> 2151 2152 if (mangleSubstitution(ND)) 2153 return; 2154 2155 // <template-template-param> ::= <template-param> 2156 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) { 2157 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 2158 } else { 2159 const DeclContext *DC = Context.getEffectiveDeclContext(ND); 2160 manglePrefix(DC, NoFunction); 2161 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) 2162 mangleUnqualifiedName(GD, DC, nullptr); 2163 else 2164 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC, 2165 nullptr); 2166 } 2167 2168 addSubstitution(ND); 2169 } 2170 2171 const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) { 2172 if (getASTContext().getLangOpts().getClangABICompat() <= 2173 LangOptions::ClangABI::Ver12) 2174 return nullptr; 2175 2176 const NamedDecl *Context = nullptr; 2177 if (auto *Block = dyn_cast<BlockDecl>(ND)) { 2178 Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl()); 2179 } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) { 2180 if (RD->isLambda()) 2181 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl()); 2182 } 2183 if (!Context) 2184 return nullptr; 2185 2186 // Only lambdas within the initializer of a non-local variable or non-static 2187 // data member get a <closure-prefix>. 2188 if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) || 2189 isa<FieldDecl>(Context)) 2190 return Context; 2191 2192 return nullptr; 2193 } 2194 2195 void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) { 2196 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M 2197 // ::= <template-prefix> <template-args> M 2198 if (mangleSubstitution(ND)) 2199 return; 2200 2201 const TemplateArgumentList *TemplateArgs = nullptr; 2202 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) { 2203 mangleTemplatePrefix(TD, NoFunction); 2204 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 2205 } else { 2206 const auto *DC = Context.getEffectiveDeclContext(ND); 2207 manglePrefix(DC, NoFunction); 2208 mangleUnqualifiedName(ND, DC, nullptr); 2209 } 2210 2211 Out << 'M'; 2212 2213 addSubstitution(ND); 2214 } 2215 2216 /// Mangles a template name under the production <type>. Required for 2217 /// template template arguments. 2218 /// <type> ::= <class-enum-type> 2219 /// ::= <template-param> 2220 /// ::= <substitution> 2221 void CXXNameMangler::mangleType(TemplateName TN) { 2222 if (mangleSubstitution(TN)) 2223 return; 2224 2225 TemplateDecl *TD = nullptr; 2226 2227 switch (TN.getKind()) { 2228 case TemplateName::QualifiedTemplate: 2229 case TemplateName::UsingTemplate: 2230 case TemplateName::Template: 2231 TD = TN.getAsTemplateDecl(); 2232 goto HaveDecl; 2233 2234 HaveDecl: 2235 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD)) 2236 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 2237 else 2238 mangleName(TD); 2239 break; 2240 2241 case TemplateName::OverloadedTemplate: 2242 case TemplateName::AssumedTemplate: 2243 llvm_unreachable("can't mangle an overloaded template name as a <type>"); 2244 2245 case TemplateName::DependentTemplate: { 2246 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName(); 2247 assert(Dependent->isIdentifier()); 2248 2249 // <class-enum-type> ::= <name> 2250 // <name> ::= <nested-name> 2251 mangleUnresolvedPrefix(Dependent->getQualifier()); 2252 mangleSourceName(Dependent->getIdentifier()); 2253 break; 2254 } 2255 2256 case TemplateName::SubstTemplateTemplateParm: { 2257 // Substituted template parameters are mangled as the substituted 2258 // template. This will check for the substitution twice, which is 2259 // fine, but we have to return early so that we don't try to *add* 2260 // the substitution twice. 2261 SubstTemplateTemplateParmStorage *subst 2262 = TN.getAsSubstTemplateTemplateParm(); 2263 mangleType(subst->getReplacement()); 2264 return; 2265 } 2266 2267 case TemplateName::SubstTemplateTemplateParmPack: { 2268 // FIXME: not clear how to mangle this! 2269 // template <template <class> class T...> class A { 2270 // template <template <class> class U...> void foo(B<T,U> x...); 2271 // }; 2272 Out << "_SUBSTPACK_"; 2273 break; 2274 } 2275 } 2276 2277 addSubstitution(TN); 2278 } 2279 2280 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty, 2281 StringRef Prefix) { 2282 // Only certain other types are valid as prefixes; enumerate them. 2283 switch (Ty->getTypeClass()) { 2284 case Type::Builtin: 2285 case Type::Complex: 2286 case Type::Adjusted: 2287 case Type::Decayed: 2288 case Type::Pointer: 2289 case Type::BlockPointer: 2290 case Type::LValueReference: 2291 case Type::RValueReference: 2292 case Type::MemberPointer: 2293 case Type::ConstantArray: 2294 case Type::IncompleteArray: 2295 case Type::VariableArray: 2296 case Type::DependentSizedArray: 2297 case Type::DependentAddressSpace: 2298 case Type::DependentVector: 2299 case Type::DependentSizedExtVector: 2300 case Type::Vector: 2301 case Type::ExtVector: 2302 case Type::ConstantMatrix: 2303 case Type::DependentSizedMatrix: 2304 case Type::FunctionProto: 2305 case Type::FunctionNoProto: 2306 case Type::Paren: 2307 case Type::Attributed: 2308 case Type::BTFTagAttributed: 2309 case Type::Auto: 2310 case Type::DeducedTemplateSpecialization: 2311 case Type::PackExpansion: 2312 case Type::ObjCObject: 2313 case Type::ObjCInterface: 2314 case Type::ObjCObjectPointer: 2315 case Type::ObjCTypeParam: 2316 case Type::Atomic: 2317 case Type::Pipe: 2318 case Type::MacroQualified: 2319 case Type::BitInt: 2320 case Type::DependentBitInt: 2321 llvm_unreachable("type is illegal as a nested name specifier"); 2322 2323 case Type::SubstTemplateTypeParmPack: 2324 // FIXME: not clear how to mangle this! 2325 // template <class T...> class A { 2326 // template <class U...> void foo(decltype(T::foo(U())) x...); 2327 // }; 2328 Out << "_SUBSTPACK_"; 2329 break; 2330 2331 // <unresolved-type> ::= <template-param> 2332 // ::= <decltype> 2333 // ::= <template-template-param> <template-args> 2334 // (this last is not official yet) 2335 case Type::TypeOfExpr: 2336 case Type::TypeOf: 2337 case Type::Decltype: 2338 case Type::TemplateTypeParm: 2339 case Type::UnaryTransform: 2340 case Type::SubstTemplateTypeParm: 2341 unresolvedType: 2342 // Some callers want a prefix before the mangled type. 2343 Out << Prefix; 2344 2345 // This seems to do everything we want. It's not really 2346 // sanctioned for a substituted template parameter, though. 2347 mangleType(Ty); 2348 2349 // We never want to print 'E' directly after an unresolved-type, 2350 // so we return directly. 2351 return true; 2352 2353 case Type::Typedef: 2354 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl()); 2355 break; 2356 2357 case Type::UnresolvedUsing: 2358 mangleSourceNameWithAbiTags( 2359 cast<UnresolvedUsingType>(Ty)->getDecl()); 2360 break; 2361 2362 case Type::Enum: 2363 case Type::Record: 2364 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl()); 2365 break; 2366 2367 case Type::TemplateSpecialization: { 2368 const TemplateSpecializationType *TST = 2369 cast<TemplateSpecializationType>(Ty); 2370 TemplateName TN = TST->getTemplateName(); 2371 switch (TN.getKind()) { 2372 case TemplateName::Template: 2373 case TemplateName::QualifiedTemplate: { 2374 TemplateDecl *TD = TN.getAsTemplateDecl(); 2375 2376 // If the base is a template template parameter, this is an 2377 // unresolved type. 2378 assert(TD && "no template for template specialization type"); 2379 if (isa<TemplateTemplateParmDecl>(TD)) 2380 goto unresolvedType; 2381 2382 mangleSourceNameWithAbiTags(TD); 2383 break; 2384 } 2385 2386 case TemplateName::OverloadedTemplate: 2387 case TemplateName::AssumedTemplate: 2388 case TemplateName::DependentTemplate: 2389 llvm_unreachable("invalid base for a template specialization type"); 2390 2391 case TemplateName::SubstTemplateTemplateParm: { 2392 SubstTemplateTemplateParmStorage *subst = 2393 TN.getAsSubstTemplateTemplateParm(); 2394 mangleExistingSubstitution(subst->getReplacement()); 2395 break; 2396 } 2397 2398 case TemplateName::SubstTemplateTemplateParmPack: { 2399 // FIXME: not clear how to mangle this! 2400 // template <template <class U> class T...> class A { 2401 // template <class U...> void foo(decltype(T<U>::foo) x...); 2402 // }; 2403 Out << "_SUBSTPACK_"; 2404 break; 2405 } 2406 case TemplateName::UsingTemplate: { 2407 TemplateDecl *TD = TN.getAsTemplateDecl(); 2408 assert(TD && !isa<TemplateTemplateParmDecl>(TD)); 2409 mangleSourceNameWithAbiTags(TD); 2410 break; 2411 } 2412 } 2413 2414 // Note: we don't pass in the template name here. We are mangling the 2415 // original source-level template arguments, so we shouldn't consider 2416 // conversions to the corresponding template parameter. 2417 // FIXME: Other compilers mangle partially-resolved template arguments in 2418 // unresolved-qualifier-levels. 2419 mangleTemplateArgs(TemplateName(), TST->getArgs(), TST->getNumArgs()); 2420 break; 2421 } 2422 2423 case Type::InjectedClassName: 2424 mangleSourceNameWithAbiTags( 2425 cast<InjectedClassNameType>(Ty)->getDecl()); 2426 break; 2427 2428 case Type::DependentName: 2429 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier()); 2430 break; 2431 2432 case Type::DependentTemplateSpecialization: { 2433 const DependentTemplateSpecializationType *DTST = 2434 cast<DependentTemplateSpecializationType>(Ty); 2435 TemplateName Template = getASTContext().getDependentTemplateName( 2436 DTST->getQualifier(), DTST->getIdentifier()); 2437 mangleSourceName(DTST->getIdentifier()); 2438 mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs()); 2439 break; 2440 } 2441 2442 case Type::Using: 2443 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(), 2444 Prefix); 2445 case Type::Elaborated: 2446 return mangleUnresolvedTypeOrSimpleId( 2447 cast<ElaboratedType>(Ty)->getNamedType(), Prefix); 2448 } 2449 2450 return false; 2451 } 2452 2453 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) { 2454 switch (Name.getNameKind()) { 2455 case DeclarationName::CXXConstructorName: 2456 case DeclarationName::CXXDestructorName: 2457 case DeclarationName::CXXDeductionGuideName: 2458 case DeclarationName::CXXUsingDirective: 2459 case DeclarationName::Identifier: 2460 case DeclarationName::ObjCMultiArgSelector: 2461 case DeclarationName::ObjCOneArgSelector: 2462 case DeclarationName::ObjCZeroArgSelector: 2463 llvm_unreachable("Not an operator name"); 2464 2465 case DeclarationName::CXXConversionFunctionName: 2466 // <operator-name> ::= cv <type> # (cast) 2467 Out << "cv"; 2468 mangleType(Name.getCXXNameType()); 2469 break; 2470 2471 case DeclarationName::CXXLiteralOperatorName: 2472 Out << "li"; 2473 mangleSourceName(Name.getCXXLiteralIdentifier()); 2474 return; 2475 2476 case DeclarationName::CXXOperatorName: 2477 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity); 2478 break; 2479 } 2480 } 2481 2482 void 2483 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) { 2484 switch (OO) { 2485 // <operator-name> ::= nw # new 2486 case OO_New: Out << "nw"; break; 2487 // ::= na # new[] 2488 case OO_Array_New: Out << "na"; break; 2489 // ::= dl # delete 2490 case OO_Delete: Out << "dl"; break; 2491 // ::= da # delete[] 2492 case OO_Array_Delete: Out << "da"; break; 2493 // ::= ps # + (unary) 2494 // ::= pl # + (binary or unknown) 2495 case OO_Plus: 2496 Out << (Arity == 1? "ps" : "pl"); break; 2497 // ::= ng # - (unary) 2498 // ::= mi # - (binary or unknown) 2499 case OO_Minus: 2500 Out << (Arity == 1? "ng" : "mi"); break; 2501 // ::= ad # & (unary) 2502 // ::= an # & (binary or unknown) 2503 case OO_Amp: 2504 Out << (Arity == 1? "ad" : "an"); break; 2505 // ::= de # * (unary) 2506 // ::= ml # * (binary or unknown) 2507 case OO_Star: 2508 // Use binary when unknown. 2509 Out << (Arity == 1? "de" : "ml"); break; 2510 // ::= co # ~ 2511 case OO_Tilde: Out << "co"; break; 2512 // ::= dv # / 2513 case OO_Slash: Out << "dv"; break; 2514 // ::= rm # % 2515 case OO_Percent: Out << "rm"; break; 2516 // ::= or # | 2517 case OO_Pipe: Out << "or"; break; 2518 // ::= eo # ^ 2519 case OO_Caret: Out << "eo"; break; 2520 // ::= aS # = 2521 case OO_Equal: Out << "aS"; break; 2522 // ::= pL # += 2523 case OO_PlusEqual: Out << "pL"; break; 2524 // ::= mI # -= 2525 case OO_MinusEqual: Out << "mI"; break; 2526 // ::= mL # *= 2527 case OO_StarEqual: Out << "mL"; break; 2528 // ::= dV # /= 2529 case OO_SlashEqual: Out << "dV"; break; 2530 // ::= rM # %= 2531 case OO_PercentEqual: Out << "rM"; break; 2532 // ::= aN # &= 2533 case OO_AmpEqual: Out << "aN"; break; 2534 // ::= oR # |= 2535 case OO_PipeEqual: Out << "oR"; break; 2536 // ::= eO # ^= 2537 case OO_CaretEqual: Out << "eO"; break; 2538 // ::= ls # << 2539 case OO_LessLess: Out << "ls"; break; 2540 // ::= rs # >> 2541 case OO_GreaterGreater: Out << "rs"; break; 2542 // ::= lS # <<= 2543 case OO_LessLessEqual: Out << "lS"; break; 2544 // ::= rS # >>= 2545 case OO_GreaterGreaterEqual: Out << "rS"; break; 2546 // ::= eq # == 2547 case OO_EqualEqual: Out << "eq"; break; 2548 // ::= ne # != 2549 case OO_ExclaimEqual: Out << "ne"; break; 2550 // ::= lt # < 2551 case OO_Less: Out << "lt"; break; 2552 // ::= gt # > 2553 case OO_Greater: Out << "gt"; break; 2554 // ::= le # <= 2555 case OO_LessEqual: Out << "le"; break; 2556 // ::= ge # >= 2557 case OO_GreaterEqual: Out << "ge"; break; 2558 // ::= nt # ! 2559 case OO_Exclaim: Out << "nt"; break; 2560 // ::= aa # && 2561 case OO_AmpAmp: Out << "aa"; break; 2562 // ::= oo # || 2563 case OO_PipePipe: Out << "oo"; break; 2564 // ::= pp # ++ 2565 case OO_PlusPlus: Out << "pp"; break; 2566 // ::= mm # -- 2567 case OO_MinusMinus: Out << "mm"; break; 2568 // ::= cm # , 2569 case OO_Comma: Out << "cm"; break; 2570 // ::= pm # ->* 2571 case OO_ArrowStar: Out << "pm"; break; 2572 // ::= pt # -> 2573 case OO_Arrow: Out << "pt"; break; 2574 // ::= cl # () 2575 case OO_Call: Out << "cl"; break; 2576 // ::= ix # [] 2577 case OO_Subscript: Out << "ix"; break; 2578 2579 // ::= qu # ? 2580 // The conditional operator can't be overloaded, but we still handle it when 2581 // mangling expressions. 2582 case OO_Conditional: Out << "qu"; break; 2583 // Proposal on cxx-abi-dev, 2015-10-21. 2584 // ::= aw # co_await 2585 case OO_Coawait: Out << "aw"; break; 2586 // Proposed in cxx-abi github issue 43. 2587 // ::= ss # <=> 2588 case OO_Spaceship: Out << "ss"; break; 2589 2590 case OO_None: 2591 case NUM_OVERLOADED_OPERATORS: 2592 llvm_unreachable("Not an overloaded operator"); 2593 } 2594 } 2595 2596 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) { 2597 // Vendor qualifiers come first and if they are order-insensitive they must 2598 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5. 2599 2600 // <type> ::= U <addrspace-expr> 2601 if (DAST) { 2602 Out << "U2ASI"; 2603 mangleExpression(DAST->getAddrSpaceExpr()); 2604 Out << "E"; 2605 } 2606 2607 // Address space qualifiers start with an ordinary letter. 2608 if (Quals.hasAddressSpace()) { 2609 // Address space extension: 2610 // 2611 // <type> ::= U <target-addrspace> 2612 // <type> ::= U <OpenCL-addrspace> 2613 // <type> ::= U <CUDA-addrspace> 2614 2615 SmallString<64> ASString; 2616 LangAS AS = Quals.getAddressSpace(); 2617 2618 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) { 2619 // <target-addrspace> ::= "AS" <address-space-number> 2620 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS); 2621 if (TargetAS != 0 || 2622 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0) 2623 ASString = "AS" + llvm::utostr(TargetAS); 2624 } else { 2625 switch (AS) { 2626 default: llvm_unreachable("Not a language specific address space"); 2627 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" | 2628 // "private"| "generic" | "device" | 2629 // "host" ] 2630 case LangAS::opencl_global: 2631 ASString = "CLglobal"; 2632 break; 2633 case LangAS::opencl_global_device: 2634 ASString = "CLdevice"; 2635 break; 2636 case LangAS::opencl_global_host: 2637 ASString = "CLhost"; 2638 break; 2639 case LangAS::opencl_local: 2640 ASString = "CLlocal"; 2641 break; 2642 case LangAS::opencl_constant: 2643 ASString = "CLconstant"; 2644 break; 2645 case LangAS::opencl_private: 2646 ASString = "CLprivate"; 2647 break; 2648 case LangAS::opencl_generic: 2649 ASString = "CLgeneric"; 2650 break; 2651 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" | 2652 // "device" | "host" ] 2653 case LangAS::sycl_global: 2654 ASString = "SYglobal"; 2655 break; 2656 case LangAS::sycl_global_device: 2657 ASString = "SYdevice"; 2658 break; 2659 case LangAS::sycl_global_host: 2660 ASString = "SYhost"; 2661 break; 2662 case LangAS::sycl_local: 2663 ASString = "SYlocal"; 2664 break; 2665 case LangAS::sycl_private: 2666 ASString = "SYprivate"; 2667 break; 2668 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ] 2669 case LangAS::cuda_device: 2670 ASString = "CUdevice"; 2671 break; 2672 case LangAS::cuda_constant: 2673 ASString = "CUconstant"; 2674 break; 2675 case LangAS::cuda_shared: 2676 ASString = "CUshared"; 2677 break; 2678 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ] 2679 case LangAS::ptr32_sptr: 2680 ASString = "ptr32_sptr"; 2681 break; 2682 case LangAS::ptr32_uptr: 2683 ASString = "ptr32_uptr"; 2684 break; 2685 case LangAS::ptr64: 2686 ASString = "ptr64"; 2687 break; 2688 } 2689 } 2690 if (!ASString.empty()) 2691 mangleVendorQualifier(ASString); 2692 } 2693 2694 // The ARC ownership qualifiers start with underscores. 2695 // Objective-C ARC Extension: 2696 // 2697 // <type> ::= U "__strong" 2698 // <type> ::= U "__weak" 2699 // <type> ::= U "__autoreleasing" 2700 // 2701 // Note: we emit __weak first to preserve the order as 2702 // required by the Itanium ABI. 2703 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak) 2704 mangleVendorQualifier("__weak"); 2705 2706 // __unaligned (from -fms-extensions) 2707 if (Quals.hasUnaligned()) 2708 mangleVendorQualifier("__unaligned"); 2709 2710 // Remaining ARC ownership qualifiers. 2711 switch (Quals.getObjCLifetime()) { 2712 case Qualifiers::OCL_None: 2713 break; 2714 2715 case Qualifiers::OCL_Weak: 2716 // Do nothing as we already handled this case above. 2717 break; 2718 2719 case Qualifiers::OCL_Strong: 2720 mangleVendorQualifier("__strong"); 2721 break; 2722 2723 case Qualifiers::OCL_Autoreleasing: 2724 mangleVendorQualifier("__autoreleasing"); 2725 break; 2726 2727 case Qualifiers::OCL_ExplicitNone: 2728 // The __unsafe_unretained qualifier is *not* mangled, so that 2729 // __unsafe_unretained types in ARC produce the same manglings as the 2730 // equivalent (but, naturally, unqualified) types in non-ARC, providing 2731 // better ABI compatibility. 2732 // 2733 // It's safe to do this because unqualified 'id' won't show up 2734 // in any type signatures that need to be mangled. 2735 break; 2736 } 2737 2738 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const 2739 if (Quals.hasRestrict()) 2740 Out << 'r'; 2741 if (Quals.hasVolatile()) 2742 Out << 'V'; 2743 if (Quals.hasConst()) 2744 Out << 'K'; 2745 } 2746 2747 void CXXNameMangler::mangleVendorQualifier(StringRef name) { 2748 Out << 'U' << name.size() << name; 2749 } 2750 2751 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 2752 // <ref-qualifier> ::= R # lvalue reference 2753 // ::= O # rvalue-reference 2754 switch (RefQualifier) { 2755 case RQ_None: 2756 break; 2757 2758 case RQ_LValue: 2759 Out << 'R'; 2760 break; 2761 2762 case RQ_RValue: 2763 Out << 'O'; 2764 break; 2765 } 2766 } 2767 2768 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 2769 Context.mangleObjCMethodNameAsSourceName(MD, Out); 2770 } 2771 2772 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty, 2773 ASTContext &Ctx) { 2774 if (Quals) 2775 return true; 2776 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel)) 2777 return true; 2778 if (Ty->isOpenCLSpecificType()) 2779 return true; 2780 if (Ty->isBuiltinType()) 2781 return false; 2782 // Through to Clang 6.0, we accidentally treated undeduced auto types as 2783 // substitution candidates. 2784 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 && 2785 isa<AutoType>(Ty)) 2786 return false; 2787 // A placeholder type for class template deduction is substitutable with 2788 // its corresponding template name; this is handled specially when mangling 2789 // the type. 2790 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>()) 2791 if (DeducedTST->getDeducedType().isNull()) 2792 return false; 2793 return true; 2794 } 2795 2796 void CXXNameMangler::mangleType(QualType T) { 2797 // If our type is instantiation-dependent but not dependent, we mangle 2798 // it as it was written in the source, removing any top-level sugar. 2799 // Otherwise, use the canonical type. 2800 // 2801 // FIXME: This is an approximation of the instantiation-dependent name 2802 // mangling rules, since we should really be using the type as written and 2803 // augmented via semantic analysis (i.e., with implicit conversions and 2804 // default template arguments) for any instantiation-dependent type. 2805 // Unfortunately, that requires several changes to our AST: 2806 // - Instantiation-dependent TemplateSpecializationTypes will need to be 2807 // uniqued, so that we can handle substitutions properly 2808 // - Default template arguments will need to be represented in the 2809 // TemplateSpecializationType, since they need to be mangled even though 2810 // they aren't written. 2811 // - Conversions on non-type template arguments need to be expressed, since 2812 // they can affect the mangling of sizeof/alignof. 2813 // 2814 // FIXME: This is wrong when mapping to the canonical type for a dependent 2815 // type discards instantiation-dependent portions of the type, such as for: 2816 // 2817 // template<typename T, int N> void f(T (&)[sizeof(N)]); 2818 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17) 2819 // 2820 // It's also wrong in the opposite direction when instantiation-dependent, 2821 // canonically-equivalent types differ in some irrelevant portion of inner 2822 // type sugar. In such cases, we fail to form correct substitutions, eg: 2823 // 2824 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*)); 2825 // 2826 // We should instead canonicalize the non-instantiation-dependent parts, 2827 // regardless of whether the type as a whole is dependent or instantiation 2828 // dependent. 2829 if (!T->isInstantiationDependentType() || T->isDependentType()) 2830 T = T.getCanonicalType(); 2831 else { 2832 // Desugar any types that are purely sugar. 2833 do { 2834 // Don't desugar through template specialization types that aren't 2835 // type aliases. We need to mangle the template arguments as written. 2836 if (const TemplateSpecializationType *TST 2837 = dyn_cast<TemplateSpecializationType>(T)) 2838 if (!TST->isTypeAlias()) 2839 break; 2840 2841 // FIXME: We presumably shouldn't strip off ElaboratedTypes with 2842 // instantation-dependent qualifiers. See 2843 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114. 2844 2845 QualType Desugared 2846 = T.getSingleStepDesugaredType(Context.getASTContext()); 2847 if (Desugared == T) 2848 break; 2849 2850 T = Desugared; 2851 } while (true); 2852 } 2853 SplitQualType split = T.split(); 2854 Qualifiers quals = split.Quals; 2855 const Type *ty = split.Ty; 2856 2857 bool isSubstitutable = 2858 isTypeSubstitutable(quals, ty, Context.getASTContext()); 2859 if (isSubstitutable && mangleSubstitution(T)) 2860 return; 2861 2862 // If we're mangling a qualified array type, push the qualifiers to 2863 // the element type. 2864 if (quals && isa<ArrayType>(T)) { 2865 ty = Context.getASTContext().getAsArrayType(T); 2866 quals = Qualifiers(); 2867 2868 // Note that we don't update T: we want to add the 2869 // substitution at the original type. 2870 } 2871 2872 if (quals || ty->isDependentAddressSpaceType()) { 2873 if (const DependentAddressSpaceType *DAST = 2874 dyn_cast<DependentAddressSpaceType>(ty)) { 2875 SplitQualType splitDAST = DAST->getPointeeType().split(); 2876 mangleQualifiers(splitDAST.Quals, DAST); 2877 mangleType(QualType(splitDAST.Ty, 0)); 2878 } else { 2879 mangleQualifiers(quals); 2880 2881 // Recurse: even if the qualified type isn't yet substitutable, 2882 // the unqualified type might be. 2883 mangleType(QualType(ty, 0)); 2884 } 2885 } else { 2886 switch (ty->getTypeClass()) { 2887 #define ABSTRACT_TYPE(CLASS, PARENT) 2888 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 2889 case Type::CLASS: \ 2890 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 2891 return; 2892 #define TYPE(CLASS, PARENT) \ 2893 case Type::CLASS: \ 2894 mangleType(static_cast<const CLASS##Type*>(ty)); \ 2895 break; 2896 #include "clang/AST/TypeNodes.inc" 2897 } 2898 } 2899 2900 // Add the substitution. 2901 if (isSubstitutable) 2902 addSubstitution(T); 2903 } 2904 2905 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) { 2906 if (!mangleStandardSubstitution(ND)) 2907 mangleName(ND); 2908 } 2909 2910 void CXXNameMangler::mangleType(const BuiltinType *T) { 2911 // <type> ::= <builtin-type> 2912 // <builtin-type> ::= v # void 2913 // ::= w # wchar_t 2914 // ::= b # bool 2915 // ::= c # char 2916 // ::= a # signed char 2917 // ::= h # unsigned char 2918 // ::= s # short 2919 // ::= t # unsigned short 2920 // ::= i # int 2921 // ::= j # unsigned int 2922 // ::= l # long 2923 // ::= m # unsigned long 2924 // ::= x # long long, __int64 2925 // ::= y # unsigned long long, __int64 2926 // ::= n # __int128 2927 // ::= o # unsigned __int128 2928 // ::= f # float 2929 // ::= d # double 2930 // ::= e # long double, __float80 2931 // ::= g # __float128 2932 // ::= g # __ibm128 2933 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) 2934 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) 2935 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) 2936 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 2937 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits); 2938 // ::= Di # char32_t 2939 // ::= Ds # char16_t 2940 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 2941 // ::= u <source-name> # vendor extended type 2942 std::string type_name; 2943 switch (T->getKind()) { 2944 case BuiltinType::Void: 2945 Out << 'v'; 2946 break; 2947 case BuiltinType::Bool: 2948 Out << 'b'; 2949 break; 2950 case BuiltinType::Char_U: 2951 case BuiltinType::Char_S: 2952 Out << 'c'; 2953 break; 2954 case BuiltinType::UChar: 2955 Out << 'h'; 2956 break; 2957 case BuiltinType::UShort: 2958 Out << 't'; 2959 break; 2960 case BuiltinType::UInt: 2961 Out << 'j'; 2962 break; 2963 case BuiltinType::ULong: 2964 Out << 'm'; 2965 break; 2966 case BuiltinType::ULongLong: 2967 Out << 'y'; 2968 break; 2969 case BuiltinType::UInt128: 2970 Out << 'o'; 2971 break; 2972 case BuiltinType::SChar: 2973 Out << 'a'; 2974 break; 2975 case BuiltinType::WChar_S: 2976 case BuiltinType::WChar_U: 2977 Out << 'w'; 2978 break; 2979 case BuiltinType::Char8: 2980 Out << "Du"; 2981 break; 2982 case BuiltinType::Char16: 2983 Out << "Ds"; 2984 break; 2985 case BuiltinType::Char32: 2986 Out << "Di"; 2987 break; 2988 case BuiltinType::Short: 2989 Out << 's'; 2990 break; 2991 case BuiltinType::Int: 2992 Out << 'i'; 2993 break; 2994 case BuiltinType::Long: 2995 Out << 'l'; 2996 break; 2997 case BuiltinType::LongLong: 2998 Out << 'x'; 2999 break; 3000 case BuiltinType::Int128: 3001 Out << 'n'; 3002 break; 3003 case BuiltinType::Float16: 3004 Out << "DF16_"; 3005 break; 3006 case BuiltinType::ShortAccum: 3007 case BuiltinType::Accum: 3008 case BuiltinType::LongAccum: 3009 case BuiltinType::UShortAccum: 3010 case BuiltinType::UAccum: 3011 case BuiltinType::ULongAccum: 3012 case BuiltinType::ShortFract: 3013 case BuiltinType::Fract: 3014 case BuiltinType::LongFract: 3015 case BuiltinType::UShortFract: 3016 case BuiltinType::UFract: 3017 case BuiltinType::ULongFract: 3018 case BuiltinType::SatShortAccum: 3019 case BuiltinType::SatAccum: 3020 case BuiltinType::SatLongAccum: 3021 case BuiltinType::SatUShortAccum: 3022 case BuiltinType::SatUAccum: 3023 case BuiltinType::SatULongAccum: 3024 case BuiltinType::SatShortFract: 3025 case BuiltinType::SatFract: 3026 case BuiltinType::SatLongFract: 3027 case BuiltinType::SatUShortFract: 3028 case BuiltinType::SatUFract: 3029 case BuiltinType::SatULongFract: 3030 llvm_unreachable("Fixed point types are disabled for c++"); 3031 case BuiltinType::Half: 3032 Out << "Dh"; 3033 break; 3034 case BuiltinType::Float: 3035 Out << 'f'; 3036 break; 3037 case BuiltinType::Double: 3038 Out << 'd'; 3039 break; 3040 case BuiltinType::LongDouble: { 3041 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP && 3042 getASTContext().getLangOpts().OpenMPIsDevice 3043 ? getASTContext().getAuxTargetInfo() 3044 : &getASTContext().getTargetInfo(); 3045 Out << TI->getLongDoubleMangling(); 3046 break; 3047 } 3048 case BuiltinType::Float128: { 3049 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP && 3050 getASTContext().getLangOpts().OpenMPIsDevice 3051 ? getASTContext().getAuxTargetInfo() 3052 : &getASTContext().getTargetInfo(); 3053 Out << TI->getFloat128Mangling(); 3054 break; 3055 } 3056 case BuiltinType::BFloat16: { 3057 const TargetInfo *TI = &getASTContext().getTargetInfo(); 3058 Out << TI->getBFloat16Mangling(); 3059 break; 3060 } 3061 case BuiltinType::Ibm128: { 3062 const TargetInfo *TI = &getASTContext().getTargetInfo(); 3063 Out << TI->getIbm128Mangling(); 3064 break; 3065 } 3066 case BuiltinType::NullPtr: 3067 Out << "Dn"; 3068 break; 3069 3070 #define BUILTIN_TYPE(Id, SingletonId) 3071 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 3072 case BuiltinType::Id: 3073 #include "clang/AST/BuiltinTypes.def" 3074 case BuiltinType::Dependent: 3075 if (!NullOut) 3076 llvm_unreachable("mangling a placeholder type"); 3077 break; 3078 case BuiltinType::ObjCId: 3079 Out << "11objc_object"; 3080 break; 3081 case BuiltinType::ObjCClass: 3082 Out << "10objc_class"; 3083 break; 3084 case BuiltinType::ObjCSel: 3085 Out << "13objc_selector"; 3086 break; 3087 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3088 case BuiltinType::Id: \ 3089 type_name = "ocl_" #ImgType "_" #Suffix; \ 3090 Out << type_name.size() << type_name; \ 3091 break; 3092 #include "clang/Basic/OpenCLImageTypes.def" 3093 case BuiltinType::OCLSampler: 3094 Out << "11ocl_sampler"; 3095 break; 3096 case BuiltinType::OCLEvent: 3097 Out << "9ocl_event"; 3098 break; 3099 case BuiltinType::OCLClkEvent: 3100 Out << "12ocl_clkevent"; 3101 break; 3102 case BuiltinType::OCLQueue: 3103 Out << "9ocl_queue"; 3104 break; 3105 case BuiltinType::OCLReserveID: 3106 Out << "13ocl_reserveid"; 3107 break; 3108 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 3109 case BuiltinType::Id: \ 3110 type_name = "ocl_" #ExtType; \ 3111 Out << type_name.size() << type_name; \ 3112 break; 3113 #include "clang/Basic/OpenCLExtensionTypes.def" 3114 // The SVE types are effectively target-specific. The mangling scheme 3115 // is defined in the appendices to the Procedure Call Standard for the 3116 // Arm Architecture. 3117 #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \ 3118 ElBits, IsSigned, IsFP, IsBF) \ 3119 case BuiltinType::Id: \ 3120 type_name = MangledName; \ 3121 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 3122 << type_name; \ 3123 break; 3124 #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \ 3125 case BuiltinType::Id: \ 3126 type_name = MangledName; \ 3127 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 3128 << type_name; \ 3129 break; 3130 #include "clang/Basic/AArch64SVEACLETypes.def" 3131 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 3132 case BuiltinType::Id: \ 3133 type_name = #Name; \ 3134 Out << 'u' << type_name.size() << type_name; \ 3135 break; 3136 #include "clang/Basic/PPCTypes.def" 3137 // TODO: Check the mangling scheme for RISC-V V. 3138 #define RVV_TYPE(Name, Id, SingletonId) \ 3139 case BuiltinType::Id: \ 3140 type_name = Name; \ 3141 Out << 'u' << type_name.size() << type_name; \ 3142 break; 3143 #include "clang/Basic/RISCVVTypes.def" 3144 } 3145 } 3146 3147 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) { 3148 switch (CC) { 3149 case CC_C: 3150 return ""; 3151 3152 case CC_X86VectorCall: 3153 case CC_X86Pascal: 3154 case CC_X86RegCall: 3155 case CC_AAPCS: 3156 case CC_AAPCS_VFP: 3157 case CC_AArch64VectorCall: 3158 case CC_AArch64SVEPCS: 3159 case CC_AMDGPUKernelCall: 3160 case CC_IntelOclBicc: 3161 case CC_SpirFunction: 3162 case CC_OpenCLKernel: 3163 case CC_PreserveMost: 3164 case CC_PreserveAll: 3165 // FIXME: we should be mangling all of the above. 3166 return ""; 3167 3168 case CC_X86ThisCall: 3169 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is 3170 // used explicitly. At this point, we don't have that much information in 3171 // the AST, since clang tends to bake the convention into the canonical 3172 // function type. thiscall only rarely used explicitly, so don't mangle it 3173 // for now. 3174 return ""; 3175 3176 case CC_X86StdCall: 3177 return "stdcall"; 3178 case CC_X86FastCall: 3179 return "fastcall"; 3180 case CC_X86_64SysV: 3181 return "sysv_abi"; 3182 case CC_Win64: 3183 return "ms_abi"; 3184 case CC_Swift: 3185 return "swiftcall"; 3186 case CC_SwiftAsync: 3187 return "swiftasynccall"; 3188 } 3189 llvm_unreachable("bad calling convention"); 3190 } 3191 3192 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) { 3193 // Fast path. 3194 if (T->getExtInfo() == FunctionType::ExtInfo()) 3195 return; 3196 3197 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 3198 // This will get more complicated in the future if we mangle other 3199 // things here; but for now, since we mangle ns_returns_retained as 3200 // a qualifier on the result type, we can get away with this: 3201 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC()); 3202 if (!CCQualifier.empty()) 3203 mangleVendorQualifier(CCQualifier); 3204 3205 // FIXME: regparm 3206 // FIXME: noreturn 3207 } 3208 3209 void 3210 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { 3211 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 3212 3213 // Note that these are *not* substitution candidates. Demanglers might 3214 // have trouble with this if the parameter type is fully substituted. 3215 3216 switch (PI.getABI()) { 3217 case ParameterABI::Ordinary: 3218 break; 3219 3220 // All of these start with "swift", so they come before "ns_consumed". 3221 case ParameterABI::SwiftContext: 3222 case ParameterABI::SwiftAsyncContext: 3223 case ParameterABI::SwiftErrorResult: 3224 case ParameterABI::SwiftIndirectResult: 3225 mangleVendorQualifier(getParameterABISpelling(PI.getABI())); 3226 break; 3227 } 3228 3229 if (PI.isConsumed()) 3230 mangleVendorQualifier("ns_consumed"); 3231 3232 if (PI.isNoEscape()) 3233 mangleVendorQualifier("noescape"); 3234 } 3235 3236 // <type> ::= <function-type> 3237 // <function-type> ::= [<CV-qualifiers>] F [Y] 3238 // <bare-function-type> [<ref-qualifier>] E 3239 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 3240 mangleExtFunctionInfo(T); 3241 3242 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 3243 // e.g. "const" in "int (A::*)() const". 3244 mangleQualifiers(T->getMethodQuals()); 3245 3246 // Mangle instantiation-dependent exception-specification, if present, 3247 // per cxx-abi-dev proposal on 2016-10-11. 3248 if (T->hasInstantiationDependentExceptionSpec()) { 3249 if (isComputedNoexcept(T->getExceptionSpecType())) { 3250 Out << "DO"; 3251 mangleExpression(T->getNoexceptExpr()); 3252 Out << "E"; 3253 } else { 3254 assert(T->getExceptionSpecType() == EST_Dynamic); 3255 Out << "Dw"; 3256 for (auto ExceptTy : T->exceptions()) 3257 mangleType(ExceptTy); 3258 Out << "E"; 3259 } 3260 } else if (T->isNothrow()) { 3261 Out << "Do"; 3262 } 3263 3264 Out << 'F'; 3265 3266 // FIXME: We don't have enough information in the AST to produce the 'Y' 3267 // encoding for extern "C" function types. 3268 mangleBareFunctionType(T, /*MangleReturnType=*/true); 3269 3270 // Mangle the ref-qualifier, if present. 3271 mangleRefQualifier(T->getRefQualifier()); 3272 3273 Out << 'E'; 3274 } 3275 3276 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 3277 // Function types without prototypes can arise when mangling a function type 3278 // within an overloadable function in C. We mangle these as the absence of any 3279 // parameter types (not even an empty parameter list). 3280 Out << 'F'; 3281 3282 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3283 3284 FunctionTypeDepth.enterResultType(); 3285 mangleType(T->getReturnType()); 3286 FunctionTypeDepth.leaveResultType(); 3287 3288 FunctionTypeDepth.pop(saved); 3289 Out << 'E'; 3290 } 3291 3292 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto, 3293 bool MangleReturnType, 3294 const FunctionDecl *FD) { 3295 // Record that we're in a function type. See mangleFunctionParam 3296 // for details on what we're trying to achieve here. 3297 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3298 3299 // <bare-function-type> ::= <signature type>+ 3300 if (MangleReturnType) { 3301 FunctionTypeDepth.enterResultType(); 3302 3303 // Mangle ns_returns_retained as an order-sensitive qualifier here. 3304 if (Proto->getExtInfo().getProducesResult() && FD == nullptr) 3305 mangleVendorQualifier("ns_returns_retained"); 3306 3307 // Mangle the return type without any direct ARC ownership qualifiers. 3308 QualType ReturnTy = Proto->getReturnType(); 3309 if (ReturnTy.getObjCLifetime()) { 3310 auto SplitReturnTy = ReturnTy.split(); 3311 SplitReturnTy.Quals.removeObjCLifetime(); 3312 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy); 3313 } 3314 mangleType(ReturnTy); 3315 3316 FunctionTypeDepth.leaveResultType(); 3317 } 3318 3319 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 3320 // <builtin-type> ::= v # void 3321 Out << 'v'; 3322 3323 FunctionTypeDepth.pop(saved); 3324 return; 3325 } 3326 3327 assert(!FD || FD->getNumParams() == Proto->getNumParams()); 3328 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 3329 // Mangle extended parameter info as order-sensitive qualifiers here. 3330 if (Proto->hasExtParameterInfos() && FD == nullptr) { 3331 mangleExtParameterInfo(Proto->getExtParameterInfo(I)); 3332 } 3333 3334 // Mangle the type. 3335 QualType ParamTy = Proto->getParamType(I); 3336 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy)); 3337 3338 if (FD) { 3339 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) { 3340 // Attr can only take 1 character, so we can hardcode the length below. 3341 assert(Attr->getType() <= 9 && Attr->getType() >= 0); 3342 if (Attr->isDynamic()) 3343 Out << "U25pass_dynamic_object_size" << Attr->getType(); 3344 else 3345 Out << "U17pass_object_size" << Attr->getType(); 3346 } 3347 } 3348 } 3349 3350 FunctionTypeDepth.pop(saved); 3351 3352 // <builtin-type> ::= z # ellipsis 3353 if (Proto->isVariadic()) 3354 Out << 'z'; 3355 } 3356 3357 // <type> ::= <class-enum-type> 3358 // <class-enum-type> ::= <name> 3359 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 3360 mangleName(T->getDecl()); 3361 } 3362 3363 // <type> ::= <class-enum-type> 3364 // <class-enum-type> ::= <name> 3365 void CXXNameMangler::mangleType(const EnumType *T) { 3366 mangleType(static_cast<const TagType*>(T)); 3367 } 3368 void CXXNameMangler::mangleType(const RecordType *T) { 3369 mangleType(static_cast<const TagType*>(T)); 3370 } 3371 void CXXNameMangler::mangleType(const TagType *T) { 3372 mangleName(T->getDecl()); 3373 } 3374 3375 // <type> ::= <array-type> 3376 // <array-type> ::= A <positive dimension number> _ <element type> 3377 // ::= A [<dimension expression>] _ <element type> 3378 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 3379 Out << 'A' << T->getSize() << '_'; 3380 mangleType(T->getElementType()); 3381 } 3382 void CXXNameMangler::mangleType(const VariableArrayType *T) { 3383 Out << 'A'; 3384 // decayed vla types (size 0) will just be skipped. 3385 if (T->getSizeExpr()) 3386 mangleExpression(T->getSizeExpr()); 3387 Out << '_'; 3388 mangleType(T->getElementType()); 3389 } 3390 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 3391 Out << 'A'; 3392 // A DependentSizedArrayType might not have size expression as below 3393 // 3394 // template<int ...N> int arr[] = {N...}; 3395 if (T->getSizeExpr()) 3396 mangleExpression(T->getSizeExpr()); 3397 Out << '_'; 3398 mangleType(T->getElementType()); 3399 } 3400 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 3401 Out << "A_"; 3402 mangleType(T->getElementType()); 3403 } 3404 3405 // <type> ::= <pointer-to-member-type> 3406 // <pointer-to-member-type> ::= M <class type> <member type> 3407 void CXXNameMangler::mangleType(const MemberPointerType *T) { 3408 Out << 'M'; 3409 mangleType(QualType(T->getClass(), 0)); 3410 QualType PointeeType = T->getPointeeType(); 3411 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 3412 mangleType(FPT); 3413 3414 // Itanium C++ ABI 5.1.8: 3415 // 3416 // The type of a non-static member function is considered to be different, 3417 // for the purposes of substitution, from the type of a namespace-scope or 3418 // static member function whose type appears similar. The types of two 3419 // non-static member functions are considered to be different, for the 3420 // purposes of substitution, if the functions are members of different 3421 // classes. In other words, for the purposes of substitution, the class of 3422 // which the function is a member is considered part of the type of 3423 // function. 3424 3425 // Given that we already substitute member function pointers as a 3426 // whole, the net effect of this rule is just to unconditionally 3427 // suppress substitution on the function type in a member pointer. 3428 // We increment the SeqID here to emulate adding an entry to the 3429 // substitution table. 3430 ++SeqID; 3431 } else 3432 mangleType(PointeeType); 3433 } 3434 3435 // <type> ::= <template-param> 3436 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 3437 mangleTemplateParameter(T->getDepth(), T->getIndex()); 3438 } 3439 3440 // <type> ::= <template-param> 3441 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 3442 // FIXME: not clear how to mangle this! 3443 // template <class T...> class A { 3444 // template <class U...> void foo(T(*)(U) x...); 3445 // }; 3446 Out << "_SUBSTPACK_"; 3447 } 3448 3449 // <type> ::= P <type> # pointer-to 3450 void CXXNameMangler::mangleType(const PointerType *T) { 3451 Out << 'P'; 3452 mangleType(T->getPointeeType()); 3453 } 3454 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 3455 Out << 'P'; 3456 mangleType(T->getPointeeType()); 3457 } 3458 3459 // <type> ::= R <type> # reference-to 3460 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 3461 Out << 'R'; 3462 mangleType(T->getPointeeType()); 3463 } 3464 3465 // <type> ::= O <type> # rvalue reference-to (C++0x) 3466 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 3467 Out << 'O'; 3468 mangleType(T->getPointeeType()); 3469 } 3470 3471 // <type> ::= C <type> # complex pair (C 2000) 3472 void CXXNameMangler::mangleType(const ComplexType *T) { 3473 Out << 'C'; 3474 mangleType(T->getElementType()); 3475 } 3476 3477 // ARM's ABI for Neon vector types specifies that they should be mangled as 3478 // if they are structs (to match ARM's initial implementation). The 3479 // vector type must be one of the special types predefined by ARM. 3480 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 3481 QualType EltType = T->getElementType(); 3482 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3483 const char *EltName = nullptr; 3484 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3485 switch (cast<BuiltinType>(EltType)->getKind()) { 3486 case BuiltinType::SChar: 3487 case BuiltinType::UChar: 3488 EltName = "poly8_t"; 3489 break; 3490 case BuiltinType::Short: 3491 case BuiltinType::UShort: 3492 EltName = "poly16_t"; 3493 break; 3494 case BuiltinType::LongLong: 3495 case BuiltinType::ULongLong: 3496 EltName = "poly64_t"; 3497 break; 3498 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 3499 } 3500 } else { 3501 switch (cast<BuiltinType>(EltType)->getKind()) { 3502 case BuiltinType::SChar: EltName = "int8_t"; break; 3503 case BuiltinType::UChar: EltName = "uint8_t"; break; 3504 case BuiltinType::Short: EltName = "int16_t"; break; 3505 case BuiltinType::UShort: EltName = "uint16_t"; break; 3506 case BuiltinType::Int: EltName = "int32_t"; break; 3507 case BuiltinType::UInt: EltName = "uint32_t"; break; 3508 case BuiltinType::LongLong: EltName = "int64_t"; break; 3509 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 3510 case BuiltinType::Double: EltName = "float64_t"; break; 3511 case BuiltinType::Float: EltName = "float32_t"; break; 3512 case BuiltinType::Half: EltName = "float16_t"; break; 3513 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break; 3514 default: 3515 llvm_unreachable("unexpected Neon vector element type"); 3516 } 3517 } 3518 const char *BaseName = nullptr; 3519 unsigned BitSize = (T->getNumElements() * 3520 getASTContext().getTypeSize(EltType)); 3521 if (BitSize == 64) 3522 BaseName = "__simd64_"; 3523 else { 3524 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 3525 BaseName = "__simd128_"; 3526 } 3527 Out << strlen(BaseName) + strlen(EltName); 3528 Out << BaseName << EltName; 3529 } 3530 3531 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) { 3532 DiagnosticsEngine &Diags = Context.getDiags(); 3533 unsigned DiagID = Diags.getCustomDiagID( 3534 DiagnosticsEngine::Error, 3535 "cannot mangle this dependent neon vector type yet"); 3536 Diags.Report(T->getAttributeLoc(), DiagID); 3537 } 3538 3539 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 3540 switch (EltType->getKind()) { 3541 case BuiltinType::SChar: 3542 return "Int8"; 3543 case BuiltinType::Short: 3544 return "Int16"; 3545 case BuiltinType::Int: 3546 return "Int32"; 3547 case BuiltinType::Long: 3548 case BuiltinType::LongLong: 3549 return "Int64"; 3550 case BuiltinType::UChar: 3551 return "Uint8"; 3552 case BuiltinType::UShort: 3553 return "Uint16"; 3554 case BuiltinType::UInt: 3555 return "Uint32"; 3556 case BuiltinType::ULong: 3557 case BuiltinType::ULongLong: 3558 return "Uint64"; 3559 case BuiltinType::Half: 3560 return "Float16"; 3561 case BuiltinType::Float: 3562 return "Float32"; 3563 case BuiltinType::Double: 3564 return "Float64"; 3565 case BuiltinType::BFloat16: 3566 return "Bfloat16"; 3567 default: 3568 llvm_unreachable("Unexpected vector element base type"); 3569 } 3570 } 3571 3572 // AArch64's ABI for Neon vector types specifies that they should be mangled as 3573 // the equivalent internal name. The vector type must be one of the special 3574 // types predefined by ARM. 3575 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 3576 QualType EltType = T->getElementType(); 3577 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3578 unsigned BitSize = 3579 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 3580 (void)BitSize; // Silence warning. 3581 3582 assert((BitSize == 64 || BitSize == 128) && 3583 "Neon vector type not 64 or 128 bits"); 3584 3585 StringRef EltName; 3586 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3587 switch (cast<BuiltinType>(EltType)->getKind()) { 3588 case BuiltinType::UChar: 3589 EltName = "Poly8"; 3590 break; 3591 case BuiltinType::UShort: 3592 EltName = "Poly16"; 3593 break; 3594 case BuiltinType::ULong: 3595 case BuiltinType::ULongLong: 3596 EltName = "Poly64"; 3597 break; 3598 default: 3599 llvm_unreachable("unexpected Neon polynomial vector element type"); 3600 } 3601 } else 3602 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 3603 3604 std::string TypeName = 3605 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str(); 3606 Out << TypeName.length() << TypeName; 3607 } 3608 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) { 3609 DiagnosticsEngine &Diags = Context.getDiags(); 3610 unsigned DiagID = Diags.getCustomDiagID( 3611 DiagnosticsEngine::Error, 3612 "cannot mangle this dependent neon vector type yet"); 3613 Diags.Report(T->getAttributeLoc(), DiagID); 3614 } 3615 3616 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types 3617 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64 3618 // type as the sizeless variants. 3619 // 3620 // The mangling scheme for VLS types is implemented as a "pseudo" template: 3621 // 3622 // '__SVE_VLS<<type>, <vector length>>' 3623 // 3624 // Combining the existing SVE type and a specific vector length (in bits). 3625 // For example: 3626 // 3627 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512))); 3628 // 3629 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as: 3630 // 3631 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE" 3632 // 3633 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE 3634 // 3635 // The latest ACLE specification (00bet5) does not contain details of this 3636 // mangling scheme, it will be specified in the next revision. The mangling 3637 // scheme is otherwise defined in the appendices to the Procedure Call Standard 3638 // for the Arm Architecture, see 3639 // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling 3640 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) { 3641 assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3642 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && 3643 "expected fixed-length SVE vector!"); 3644 3645 QualType EltType = T->getElementType(); 3646 assert(EltType->isBuiltinType() && 3647 "expected builtin type for fixed-length SVE vector!"); 3648 3649 StringRef TypeName; 3650 switch (cast<BuiltinType>(EltType)->getKind()) { 3651 case BuiltinType::SChar: 3652 TypeName = "__SVInt8_t"; 3653 break; 3654 case BuiltinType::UChar: { 3655 if (T->getVectorKind() == VectorType::SveFixedLengthDataVector) 3656 TypeName = "__SVUint8_t"; 3657 else 3658 TypeName = "__SVBool_t"; 3659 break; 3660 } 3661 case BuiltinType::Short: 3662 TypeName = "__SVInt16_t"; 3663 break; 3664 case BuiltinType::UShort: 3665 TypeName = "__SVUint16_t"; 3666 break; 3667 case BuiltinType::Int: 3668 TypeName = "__SVInt32_t"; 3669 break; 3670 case BuiltinType::UInt: 3671 TypeName = "__SVUint32_t"; 3672 break; 3673 case BuiltinType::Long: 3674 TypeName = "__SVInt64_t"; 3675 break; 3676 case BuiltinType::ULong: 3677 TypeName = "__SVUint64_t"; 3678 break; 3679 case BuiltinType::Half: 3680 TypeName = "__SVFloat16_t"; 3681 break; 3682 case BuiltinType::Float: 3683 TypeName = "__SVFloat32_t"; 3684 break; 3685 case BuiltinType::Double: 3686 TypeName = "__SVFloat64_t"; 3687 break; 3688 case BuiltinType::BFloat16: 3689 TypeName = "__SVBfloat16_t"; 3690 break; 3691 default: 3692 llvm_unreachable("unexpected element type for fixed-length SVE vector!"); 3693 } 3694 3695 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width; 3696 3697 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 3698 VecSizeInBits *= 8; 3699 3700 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj" 3701 << VecSizeInBits << "EE"; 3702 } 3703 3704 void CXXNameMangler::mangleAArch64FixedSveVectorType( 3705 const DependentVectorType *T) { 3706 DiagnosticsEngine &Diags = Context.getDiags(); 3707 unsigned DiagID = Diags.getCustomDiagID( 3708 DiagnosticsEngine::Error, 3709 "cannot mangle this dependent fixed-length SVE vector type yet"); 3710 Diags.Report(T->getAttributeLoc(), DiagID); 3711 } 3712 3713 // GNU extension: vector types 3714 // <type> ::= <vector-type> 3715 // <vector-type> ::= Dv <positive dimension number> _ 3716 // <extended element type> 3717 // ::= Dv [<dimension expression>] _ <element type> 3718 // <extended element type> ::= <element type> 3719 // ::= p # AltiVec vector pixel 3720 // ::= b # Altivec vector bool 3721 void CXXNameMangler::mangleType(const VectorType *T) { 3722 if ((T->getVectorKind() == VectorType::NeonVector || 3723 T->getVectorKind() == VectorType::NeonPolyVector)) { 3724 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3725 llvm::Triple::ArchType Arch = 3726 getASTContext().getTargetInfo().getTriple().getArch(); 3727 if ((Arch == llvm::Triple::aarch64 || 3728 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 3729 mangleAArch64NeonVectorType(T); 3730 else 3731 mangleNeonVectorType(T); 3732 return; 3733 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3734 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 3735 mangleAArch64FixedSveVectorType(T); 3736 return; 3737 } 3738 Out << "Dv" << T->getNumElements() << '_'; 3739 if (T->getVectorKind() == VectorType::AltiVecPixel) 3740 Out << 'p'; 3741 else if (T->getVectorKind() == VectorType::AltiVecBool) 3742 Out << 'b'; 3743 else 3744 mangleType(T->getElementType()); 3745 } 3746 3747 void CXXNameMangler::mangleType(const DependentVectorType *T) { 3748 if ((T->getVectorKind() == VectorType::NeonVector || 3749 T->getVectorKind() == VectorType::NeonPolyVector)) { 3750 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3751 llvm::Triple::ArchType Arch = 3752 getASTContext().getTargetInfo().getTriple().getArch(); 3753 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) && 3754 !Target.isOSDarwin()) 3755 mangleAArch64NeonVectorType(T); 3756 else 3757 mangleNeonVectorType(T); 3758 return; 3759 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3760 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 3761 mangleAArch64FixedSveVectorType(T); 3762 return; 3763 } 3764 3765 Out << "Dv"; 3766 mangleExpression(T->getSizeExpr()); 3767 Out << '_'; 3768 if (T->getVectorKind() == VectorType::AltiVecPixel) 3769 Out << 'p'; 3770 else if (T->getVectorKind() == VectorType::AltiVecBool) 3771 Out << 'b'; 3772 else 3773 mangleType(T->getElementType()); 3774 } 3775 3776 void CXXNameMangler::mangleType(const ExtVectorType *T) { 3777 mangleType(static_cast<const VectorType*>(T)); 3778 } 3779 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 3780 Out << "Dv"; 3781 mangleExpression(T->getSizeExpr()); 3782 Out << '_'; 3783 mangleType(T->getElementType()); 3784 } 3785 3786 void CXXNameMangler::mangleType(const ConstantMatrixType *T) { 3787 // Mangle matrix types as a vendor extended type: 3788 // u<Len>matrix_typeI<Rows><Columns><element type>E 3789 3790 StringRef VendorQualifier = "matrix_type"; 3791 Out << "u" << VendorQualifier.size() << VendorQualifier; 3792 3793 Out << "I"; 3794 auto &ASTCtx = getASTContext(); 3795 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType()); 3796 llvm::APSInt Rows(BitWidth); 3797 Rows = T->getNumRows(); 3798 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows); 3799 llvm::APSInt Columns(BitWidth); 3800 Columns = T->getNumColumns(); 3801 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns); 3802 mangleType(T->getElementType()); 3803 Out << "E"; 3804 } 3805 3806 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) { 3807 // Mangle matrix types as a vendor extended type: 3808 // u<Len>matrix_typeI<row expr><column expr><element type>E 3809 StringRef VendorQualifier = "matrix_type"; 3810 Out << "u" << VendorQualifier.size() << VendorQualifier; 3811 3812 Out << "I"; 3813 mangleTemplateArgExpr(T->getRowExpr()); 3814 mangleTemplateArgExpr(T->getColumnExpr()); 3815 mangleType(T->getElementType()); 3816 Out << "E"; 3817 } 3818 3819 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) { 3820 SplitQualType split = T->getPointeeType().split(); 3821 mangleQualifiers(split.Quals, T); 3822 mangleType(QualType(split.Ty, 0)); 3823 } 3824 3825 void CXXNameMangler::mangleType(const PackExpansionType *T) { 3826 // <type> ::= Dp <type> # pack expansion (C++0x) 3827 Out << "Dp"; 3828 mangleType(T->getPattern()); 3829 } 3830 3831 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 3832 mangleSourceName(T->getDecl()->getIdentifier()); 3833 } 3834 3835 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 3836 // Treat __kindof as a vendor extended type qualifier. 3837 if (T->isKindOfType()) 3838 Out << "U8__kindof"; 3839 3840 if (!T->qual_empty()) { 3841 // Mangle protocol qualifiers. 3842 SmallString<64> QualStr; 3843 llvm::raw_svector_ostream QualOS(QualStr); 3844 QualOS << "objcproto"; 3845 for (const auto *I : T->quals()) { 3846 StringRef name = I->getName(); 3847 QualOS << name.size() << name; 3848 } 3849 Out << 'U' << QualStr.size() << QualStr; 3850 } 3851 3852 mangleType(T->getBaseType()); 3853 3854 if (T->isSpecialized()) { 3855 // Mangle type arguments as I <type>+ E 3856 Out << 'I'; 3857 for (auto typeArg : T->getTypeArgs()) 3858 mangleType(typeArg); 3859 Out << 'E'; 3860 } 3861 } 3862 3863 void CXXNameMangler::mangleType(const BlockPointerType *T) { 3864 Out << "U13block_pointer"; 3865 mangleType(T->getPointeeType()); 3866 } 3867 3868 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 3869 // Mangle injected class name types as if the user had written the 3870 // specialization out fully. It may not actually be possible to see 3871 // this mangling, though. 3872 mangleType(T->getInjectedSpecializationType()); 3873 } 3874 3875 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 3876 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 3877 mangleTemplateName(TD, T->getArgs(), T->getNumArgs()); 3878 } else { 3879 if (mangleSubstitution(QualType(T, 0))) 3880 return; 3881 3882 mangleTemplatePrefix(T->getTemplateName()); 3883 3884 // FIXME: GCC does not appear to mangle the template arguments when 3885 // the template in question is a dependent template name. Should we 3886 // emulate that badness? 3887 mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs()); 3888 addSubstitution(QualType(T, 0)); 3889 } 3890 } 3891 3892 void CXXNameMangler::mangleType(const DependentNameType *T) { 3893 // Proposal by cxx-abi-dev, 2014-03-26 3894 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 3895 // # dependent elaborated type specifier using 3896 // # 'typename' 3897 // ::= Ts <name> # dependent elaborated type specifier using 3898 // # 'struct' or 'class' 3899 // ::= Tu <name> # dependent elaborated type specifier using 3900 // # 'union' 3901 // ::= Te <name> # dependent elaborated type specifier using 3902 // # 'enum' 3903 switch (T->getKeyword()) { 3904 case ETK_None: 3905 case ETK_Typename: 3906 break; 3907 case ETK_Struct: 3908 case ETK_Class: 3909 case ETK_Interface: 3910 Out << "Ts"; 3911 break; 3912 case ETK_Union: 3913 Out << "Tu"; 3914 break; 3915 case ETK_Enum: 3916 Out << "Te"; 3917 break; 3918 } 3919 // Typename types are always nested 3920 Out << 'N'; 3921 manglePrefix(T->getQualifier()); 3922 mangleSourceName(T->getIdentifier()); 3923 Out << 'E'; 3924 } 3925 3926 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 3927 // Dependently-scoped template types are nested if they have a prefix. 3928 Out << 'N'; 3929 3930 // TODO: avoid making this TemplateName. 3931 TemplateName Prefix = 3932 getASTContext().getDependentTemplateName(T->getQualifier(), 3933 T->getIdentifier()); 3934 mangleTemplatePrefix(Prefix); 3935 3936 // FIXME: GCC does not appear to mangle the template arguments when 3937 // the template in question is a dependent template name. Should we 3938 // emulate that badness? 3939 mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs()); 3940 Out << 'E'; 3941 } 3942 3943 void CXXNameMangler::mangleType(const TypeOfType *T) { 3944 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3945 // "extension with parameters" mangling. 3946 Out << "u6typeof"; 3947 } 3948 3949 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 3950 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3951 // "extension with parameters" mangling. 3952 Out << "u6typeof"; 3953 } 3954 3955 void CXXNameMangler::mangleType(const DecltypeType *T) { 3956 Expr *E = T->getUnderlyingExpr(); 3957 3958 // type ::= Dt <expression> E # decltype of an id-expression 3959 // # or class member access 3960 // ::= DT <expression> E # decltype of an expression 3961 3962 // This purports to be an exhaustive list of id-expressions and 3963 // class member accesses. Note that we do not ignore parentheses; 3964 // parentheses change the semantics of decltype for these 3965 // expressions (and cause the mangler to use the other form). 3966 if (isa<DeclRefExpr>(E) || 3967 isa<MemberExpr>(E) || 3968 isa<UnresolvedLookupExpr>(E) || 3969 isa<DependentScopeDeclRefExpr>(E) || 3970 isa<CXXDependentScopeMemberExpr>(E) || 3971 isa<UnresolvedMemberExpr>(E)) 3972 Out << "Dt"; 3973 else 3974 Out << "DT"; 3975 mangleExpression(E); 3976 Out << 'E'; 3977 } 3978 3979 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 3980 // If this is dependent, we need to record that. If not, we simply 3981 // mangle it as the underlying type since they are equivalent. 3982 if (T->isDependentType()) { 3983 Out << 'U'; 3984 3985 switch (T->getUTTKind()) { 3986 case UnaryTransformType::EnumUnderlyingType: 3987 Out << "3eut"; 3988 break; 3989 } 3990 } 3991 3992 mangleType(T->getBaseType()); 3993 } 3994 3995 void CXXNameMangler::mangleType(const AutoType *T) { 3996 assert(T->getDeducedType().isNull() && 3997 "Deduced AutoType shouldn't be handled here!"); 3998 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType && 3999 "shouldn't need to mangle __auto_type!"); 4000 // <builtin-type> ::= Da # auto 4001 // ::= Dc # decltype(auto) 4002 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 4003 } 4004 4005 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) { 4006 QualType Deduced = T->getDeducedType(); 4007 if (!Deduced.isNull()) 4008 return mangleType(Deduced); 4009 4010 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl(); 4011 assert(TD && "shouldn't form deduced TST unless we know we have a template"); 4012 4013 if (mangleSubstitution(TD)) 4014 return; 4015 4016 mangleName(GlobalDecl(TD)); 4017 addSubstitution(TD); 4018 } 4019 4020 void CXXNameMangler::mangleType(const AtomicType *T) { 4021 // <type> ::= U <source-name> <type> # vendor extended type qualifier 4022 // (Until there's a standardized mangling...) 4023 Out << "U7_Atomic"; 4024 mangleType(T->getValueType()); 4025 } 4026 4027 void CXXNameMangler::mangleType(const PipeType *T) { 4028 // Pipe type mangling rules are described in SPIR 2.0 specification 4029 // A.1 Data types and A.3 Summary of changes 4030 // <type> ::= 8ocl_pipe 4031 Out << "8ocl_pipe"; 4032 } 4033 4034 void CXXNameMangler::mangleType(const BitIntType *T) { 4035 // 5.1.5.2 Builtin types 4036 // <type> ::= DB <number | instantiation-dependent expression> _ 4037 // ::= DU <number | instantiation-dependent expression> _ 4038 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_"; 4039 } 4040 4041 void CXXNameMangler::mangleType(const DependentBitIntType *T) { 4042 // 5.1.5.2 Builtin types 4043 // <type> ::= DB <number | instantiation-dependent expression> _ 4044 // ::= DU <number | instantiation-dependent expression> _ 4045 Out << "D" << (T->isUnsigned() ? "U" : "B"); 4046 mangleExpression(T->getNumBitsExpr()); 4047 Out << "_"; 4048 } 4049 4050 void CXXNameMangler::mangleIntegerLiteral(QualType T, 4051 const llvm::APSInt &Value) { 4052 // <expr-primary> ::= L <type> <value number> E # integer literal 4053 Out << 'L'; 4054 4055 mangleType(T); 4056 if (T->isBooleanType()) { 4057 // Boolean values are encoded as 0/1. 4058 Out << (Value.getBoolValue() ? '1' : '0'); 4059 } else { 4060 mangleNumber(Value); 4061 } 4062 Out << 'E'; 4063 4064 } 4065 4066 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) { 4067 // Ignore member expressions involving anonymous unions. 4068 while (const auto *RT = Base->getType()->getAs<RecordType>()) { 4069 if (!RT->getDecl()->isAnonymousStructOrUnion()) 4070 break; 4071 const auto *ME = dyn_cast<MemberExpr>(Base); 4072 if (!ME) 4073 break; 4074 Base = ME->getBase(); 4075 IsArrow = ME->isArrow(); 4076 } 4077 4078 if (Base->isImplicitCXXThis()) { 4079 // Note: GCC mangles member expressions to the implicit 'this' as 4080 // *this., whereas we represent them as this->. The Itanium C++ ABI 4081 // does not specify anything here, so we follow GCC. 4082 Out << "dtdefpT"; 4083 } else { 4084 Out << (IsArrow ? "pt" : "dt"); 4085 mangleExpression(Base); 4086 } 4087 } 4088 4089 /// Mangles a member expression. 4090 void CXXNameMangler::mangleMemberExpr(const Expr *base, 4091 bool isArrow, 4092 NestedNameSpecifier *qualifier, 4093 NamedDecl *firstQualifierLookup, 4094 DeclarationName member, 4095 const TemplateArgumentLoc *TemplateArgs, 4096 unsigned NumTemplateArgs, 4097 unsigned arity) { 4098 // <expression> ::= dt <expression> <unresolved-name> 4099 // ::= pt <expression> <unresolved-name> 4100 if (base) 4101 mangleMemberExprBase(base, isArrow); 4102 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity); 4103 } 4104 4105 /// Look at the callee of the given call expression and determine if 4106 /// it's a parenthesized id-expression which would have triggered ADL 4107 /// otherwise. 4108 static bool isParenthesizedADLCallee(const CallExpr *call) { 4109 const Expr *callee = call->getCallee(); 4110 const Expr *fn = callee->IgnoreParens(); 4111 4112 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 4113 // too, but for those to appear in the callee, it would have to be 4114 // parenthesized. 4115 if (callee == fn) return false; 4116 4117 // Must be an unresolved lookup. 4118 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 4119 if (!lookup) return false; 4120 4121 assert(!lookup->requiresADL()); 4122 4123 // Must be an unqualified lookup. 4124 if (lookup->getQualifier()) return false; 4125 4126 // Must not have found a class member. Note that if one is a class 4127 // member, they're all class members. 4128 if (lookup->getNumDecls() > 0 && 4129 (*lookup->decls_begin())->isCXXClassMember()) 4130 return false; 4131 4132 // Otherwise, ADL would have been triggered. 4133 return true; 4134 } 4135 4136 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 4137 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 4138 Out << CastEncoding; 4139 mangleType(ECE->getType()); 4140 mangleExpression(ECE->getSubExpr()); 4141 } 4142 4143 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) { 4144 if (auto *Syntactic = InitList->getSyntacticForm()) 4145 InitList = Syntactic; 4146 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 4147 mangleExpression(InitList->getInit(i)); 4148 } 4149 4150 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity, 4151 bool AsTemplateArg) { 4152 // <expression> ::= <unary operator-name> <expression> 4153 // ::= <binary operator-name> <expression> <expression> 4154 // ::= <trinary operator-name> <expression> <expression> <expression> 4155 // ::= cv <type> expression # conversion with one argument 4156 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 4157 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 4158 // ::= sc <type> <expression> # static_cast<type> (expression) 4159 // ::= cc <type> <expression> # const_cast<type> (expression) 4160 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 4161 // ::= st <type> # sizeof (a type) 4162 // ::= at <type> # alignof (a type) 4163 // ::= <template-param> 4164 // ::= <function-param> 4165 // ::= fpT # 'this' expression (part of <function-param>) 4166 // ::= sr <type> <unqualified-name> # dependent name 4167 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 4168 // ::= ds <expression> <expression> # expr.*expr 4169 // ::= sZ <template-param> # size of a parameter pack 4170 // ::= sZ <function-param> # size of a function parameter pack 4171 // ::= u <source-name> <template-arg>* E # vendor extended expression 4172 // ::= <expr-primary> 4173 // <expr-primary> ::= L <type> <value number> E # integer literal 4174 // ::= L <type> <value float> E # floating literal 4175 // ::= L <type> <string type> E # string literal 4176 // ::= L <nullptr type> E # nullptr literal "LDnE" 4177 // ::= L <pointer type> 0 E # null pointer template argument 4178 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang 4179 // ::= L <mangled-name> E # external name 4180 QualType ImplicitlyConvertedToType; 4181 4182 // A top-level expression that's not <expr-primary> needs to be wrapped in 4183 // X...E in a template arg. 4184 bool IsPrimaryExpr = true; 4185 auto NotPrimaryExpr = [&] { 4186 if (AsTemplateArg && IsPrimaryExpr) 4187 Out << 'X'; 4188 IsPrimaryExpr = false; 4189 }; 4190 4191 auto MangleDeclRefExpr = [&](const NamedDecl *D) { 4192 switch (D->getKind()) { 4193 default: 4194 // <expr-primary> ::= L <mangled-name> E # external name 4195 Out << 'L'; 4196 mangle(D); 4197 Out << 'E'; 4198 break; 4199 4200 case Decl::ParmVar: 4201 NotPrimaryExpr(); 4202 mangleFunctionParam(cast<ParmVarDecl>(D)); 4203 break; 4204 4205 case Decl::EnumConstant: { 4206 // <expr-primary> 4207 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 4208 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 4209 break; 4210 } 4211 4212 case Decl::NonTypeTemplateParm: 4213 NotPrimaryExpr(); 4214 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 4215 mangleTemplateParameter(PD->getDepth(), PD->getIndex()); 4216 break; 4217 } 4218 }; 4219 4220 // 'goto recurse' is used when handling a simple "unwrapping" node which 4221 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need 4222 // to be preserved. 4223 recurse: 4224 switch (E->getStmtClass()) { 4225 case Expr::NoStmtClass: 4226 #define ABSTRACT_STMT(Type) 4227 #define EXPR(Type, Base) 4228 #define STMT(Type, Base) \ 4229 case Expr::Type##Class: 4230 #include "clang/AST/StmtNodes.inc" 4231 // fallthrough 4232 4233 // These all can only appear in local or variable-initialization 4234 // contexts and so should never appear in a mangling. 4235 case Expr::AddrLabelExprClass: 4236 case Expr::DesignatedInitUpdateExprClass: 4237 case Expr::ImplicitValueInitExprClass: 4238 case Expr::ArrayInitLoopExprClass: 4239 case Expr::ArrayInitIndexExprClass: 4240 case Expr::NoInitExprClass: 4241 case Expr::ParenListExprClass: 4242 case Expr::MSPropertyRefExprClass: 4243 case Expr::MSPropertySubscriptExprClass: 4244 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 4245 case Expr::RecoveryExprClass: 4246 case Expr::OMPArraySectionExprClass: 4247 case Expr::OMPArrayShapingExprClass: 4248 case Expr::OMPIteratorExprClass: 4249 case Expr::CXXInheritedCtorInitExprClass: 4250 llvm_unreachable("unexpected statement kind"); 4251 4252 case Expr::ConstantExprClass: 4253 E = cast<ConstantExpr>(E)->getSubExpr(); 4254 goto recurse; 4255 4256 // FIXME: invent manglings for all these. 4257 case Expr::BlockExprClass: 4258 case Expr::ChooseExprClass: 4259 case Expr::CompoundLiteralExprClass: 4260 case Expr::ExtVectorElementExprClass: 4261 case Expr::GenericSelectionExprClass: 4262 case Expr::ObjCEncodeExprClass: 4263 case Expr::ObjCIsaExprClass: 4264 case Expr::ObjCIvarRefExprClass: 4265 case Expr::ObjCMessageExprClass: 4266 case Expr::ObjCPropertyRefExprClass: 4267 case Expr::ObjCProtocolExprClass: 4268 case Expr::ObjCSelectorExprClass: 4269 case Expr::ObjCStringLiteralClass: 4270 case Expr::ObjCBoxedExprClass: 4271 case Expr::ObjCArrayLiteralClass: 4272 case Expr::ObjCDictionaryLiteralClass: 4273 case Expr::ObjCSubscriptRefExprClass: 4274 case Expr::ObjCIndirectCopyRestoreExprClass: 4275 case Expr::ObjCAvailabilityCheckExprClass: 4276 case Expr::OffsetOfExprClass: 4277 case Expr::PredefinedExprClass: 4278 case Expr::ShuffleVectorExprClass: 4279 case Expr::ConvertVectorExprClass: 4280 case Expr::StmtExprClass: 4281 case Expr::TypeTraitExprClass: 4282 case Expr::RequiresExprClass: 4283 case Expr::ArrayTypeTraitExprClass: 4284 case Expr::ExpressionTraitExprClass: 4285 case Expr::VAArgExprClass: 4286 case Expr::CUDAKernelCallExprClass: 4287 case Expr::AsTypeExprClass: 4288 case Expr::PseudoObjectExprClass: 4289 case Expr::AtomicExprClass: 4290 case Expr::SourceLocExprClass: 4291 case Expr::BuiltinBitCastExprClass: 4292 { 4293 NotPrimaryExpr(); 4294 if (!NullOut) { 4295 // As bad as this diagnostic is, it's better than crashing. 4296 DiagnosticsEngine &Diags = Context.getDiags(); 4297 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4298 "cannot yet mangle expression type %0"); 4299 Diags.Report(E->getExprLoc(), DiagID) 4300 << E->getStmtClassName() << E->getSourceRange(); 4301 return; 4302 } 4303 break; 4304 } 4305 4306 case Expr::CXXUuidofExprClass: { 4307 NotPrimaryExpr(); 4308 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 4309 // As of clang 12, uuidof uses the vendor extended expression 4310 // mangling. Previously, it used a special-cased nonstandard extension. 4311 if (Context.getASTContext().getLangOpts().getClangABICompat() > 4312 LangOptions::ClangABI::Ver11) { 4313 Out << "u8__uuidof"; 4314 if (UE->isTypeOperand()) 4315 mangleType(UE->getTypeOperand(Context.getASTContext())); 4316 else 4317 mangleTemplateArgExpr(UE->getExprOperand()); 4318 Out << 'E'; 4319 } else { 4320 if (UE->isTypeOperand()) { 4321 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 4322 Out << "u8__uuidoft"; 4323 mangleType(UuidT); 4324 } else { 4325 Expr *UuidExp = UE->getExprOperand(); 4326 Out << "u8__uuidofz"; 4327 mangleExpression(UuidExp); 4328 } 4329 } 4330 break; 4331 } 4332 4333 // Even gcc-4.5 doesn't mangle this. 4334 case Expr::BinaryConditionalOperatorClass: { 4335 NotPrimaryExpr(); 4336 DiagnosticsEngine &Diags = Context.getDiags(); 4337 unsigned DiagID = 4338 Diags.getCustomDiagID(DiagnosticsEngine::Error, 4339 "?: operator with omitted middle operand cannot be mangled"); 4340 Diags.Report(E->getExprLoc(), DiagID) 4341 << E->getStmtClassName() << E->getSourceRange(); 4342 return; 4343 } 4344 4345 // These are used for internal purposes and cannot be meaningfully mangled. 4346 case Expr::OpaqueValueExprClass: 4347 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 4348 4349 case Expr::InitListExprClass: { 4350 NotPrimaryExpr(); 4351 Out << "il"; 4352 mangleInitListElements(cast<InitListExpr>(E)); 4353 Out << "E"; 4354 break; 4355 } 4356 4357 case Expr::DesignatedInitExprClass: { 4358 NotPrimaryExpr(); 4359 auto *DIE = cast<DesignatedInitExpr>(E); 4360 for (const auto &Designator : DIE->designators()) { 4361 if (Designator.isFieldDesignator()) { 4362 Out << "di"; 4363 mangleSourceName(Designator.getFieldName()); 4364 } else if (Designator.isArrayDesignator()) { 4365 Out << "dx"; 4366 mangleExpression(DIE->getArrayIndex(Designator)); 4367 } else { 4368 assert(Designator.isArrayRangeDesignator() && 4369 "unknown designator kind"); 4370 Out << "dX"; 4371 mangleExpression(DIE->getArrayRangeStart(Designator)); 4372 mangleExpression(DIE->getArrayRangeEnd(Designator)); 4373 } 4374 } 4375 mangleExpression(DIE->getInit()); 4376 break; 4377 } 4378 4379 case Expr::CXXDefaultArgExprClass: 4380 E = cast<CXXDefaultArgExpr>(E)->getExpr(); 4381 goto recurse; 4382 4383 case Expr::CXXDefaultInitExprClass: 4384 E = cast<CXXDefaultInitExpr>(E)->getExpr(); 4385 goto recurse; 4386 4387 case Expr::CXXStdInitializerListExprClass: 4388 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr(); 4389 goto recurse; 4390 4391 case Expr::SubstNonTypeTemplateParmExprClass: 4392 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(); 4393 goto recurse; 4394 4395 case Expr::UserDefinedLiteralClass: 4396 // We follow g++'s approach of mangling a UDL as a call to the literal 4397 // operator. 4398 case Expr::CXXMemberCallExprClass: // fallthrough 4399 case Expr::CallExprClass: { 4400 NotPrimaryExpr(); 4401 const CallExpr *CE = cast<CallExpr>(E); 4402 4403 // <expression> ::= cp <simple-id> <expression>* E 4404 // We use this mangling only when the call would use ADL except 4405 // for being parenthesized. Per discussion with David 4406 // Vandervoorde, 2011.04.25. 4407 if (isParenthesizedADLCallee(CE)) { 4408 Out << "cp"; 4409 // The callee here is a parenthesized UnresolvedLookupExpr with 4410 // no qualifier and should always get mangled as a <simple-id> 4411 // anyway. 4412 4413 // <expression> ::= cl <expression>* E 4414 } else { 4415 Out << "cl"; 4416 } 4417 4418 unsigned CallArity = CE->getNumArgs(); 4419 for (const Expr *Arg : CE->arguments()) 4420 if (isa<PackExpansionExpr>(Arg)) 4421 CallArity = UnknownArity; 4422 4423 mangleExpression(CE->getCallee(), CallArity); 4424 for (const Expr *Arg : CE->arguments()) 4425 mangleExpression(Arg); 4426 Out << 'E'; 4427 break; 4428 } 4429 4430 case Expr::CXXNewExprClass: { 4431 NotPrimaryExpr(); 4432 const CXXNewExpr *New = cast<CXXNewExpr>(E); 4433 if (New->isGlobalNew()) Out << "gs"; 4434 Out << (New->isArray() ? "na" : "nw"); 4435 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 4436 E = New->placement_arg_end(); I != E; ++I) 4437 mangleExpression(*I); 4438 Out << '_'; 4439 mangleType(New->getAllocatedType()); 4440 if (New->hasInitializer()) { 4441 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 4442 Out << "il"; 4443 else 4444 Out << "pi"; 4445 const Expr *Init = New->getInitializer(); 4446 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 4447 // Directly inline the initializers. 4448 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 4449 E = CCE->arg_end(); 4450 I != E; ++I) 4451 mangleExpression(*I); 4452 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 4453 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 4454 mangleExpression(PLE->getExpr(i)); 4455 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 4456 isa<InitListExpr>(Init)) { 4457 // Only take InitListExprs apart for list-initialization. 4458 mangleInitListElements(cast<InitListExpr>(Init)); 4459 } else 4460 mangleExpression(Init); 4461 } 4462 Out << 'E'; 4463 break; 4464 } 4465 4466 case Expr::CXXPseudoDestructorExprClass: { 4467 NotPrimaryExpr(); 4468 const auto *PDE = cast<CXXPseudoDestructorExpr>(E); 4469 if (const Expr *Base = PDE->getBase()) 4470 mangleMemberExprBase(Base, PDE->isArrow()); 4471 NestedNameSpecifier *Qualifier = PDE->getQualifier(); 4472 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) { 4473 if (Qualifier) { 4474 mangleUnresolvedPrefix(Qualifier, 4475 /*recursive=*/true); 4476 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()); 4477 Out << 'E'; 4478 } else { 4479 Out << "sr"; 4480 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType())) 4481 Out << 'E'; 4482 } 4483 } else if (Qualifier) { 4484 mangleUnresolvedPrefix(Qualifier); 4485 } 4486 // <base-unresolved-name> ::= dn <destructor-name> 4487 Out << "dn"; 4488 QualType DestroyedType = PDE->getDestroyedType(); 4489 mangleUnresolvedTypeOrSimpleId(DestroyedType); 4490 break; 4491 } 4492 4493 case Expr::MemberExprClass: { 4494 NotPrimaryExpr(); 4495 const MemberExpr *ME = cast<MemberExpr>(E); 4496 mangleMemberExpr(ME->getBase(), ME->isArrow(), 4497 ME->getQualifier(), nullptr, 4498 ME->getMemberDecl()->getDeclName(), 4499 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4500 Arity); 4501 break; 4502 } 4503 4504 case Expr::UnresolvedMemberExprClass: { 4505 NotPrimaryExpr(); 4506 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 4507 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4508 ME->isArrow(), ME->getQualifier(), nullptr, 4509 ME->getMemberName(), 4510 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4511 Arity); 4512 break; 4513 } 4514 4515 case Expr::CXXDependentScopeMemberExprClass: { 4516 NotPrimaryExpr(); 4517 const CXXDependentScopeMemberExpr *ME 4518 = cast<CXXDependentScopeMemberExpr>(E); 4519 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4520 ME->isArrow(), ME->getQualifier(), 4521 ME->getFirstQualifierFoundInScope(), 4522 ME->getMember(), 4523 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4524 Arity); 4525 break; 4526 } 4527 4528 case Expr::UnresolvedLookupExprClass: { 4529 NotPrimaryExpr(); 4530 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 4531 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), 4532 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(), 4533 Arity); 4534 break; 4535 } 4536 4537 case Expr::CXXUnresolvedConstructExprClass: { 4538 NotPrimaryExpr(); 4539 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 4540 unsigned N = CE->getNumArgs(); 4541 4542 if (CE->isListInitialization()) { 4543 assert(N == 1 && "unexpected form for list initialization"); 4544 auto *IL = cast<InitListExpr>(CE->getArg(0)); 4545 Out << "tl"; 4546 mangleType(CE->getType()); 4547 mangleInitListElements(IL); 4548 Out << "E"; 4549 break; 4550 } 4551 4552 Out << "cv"; 4553 mangleType(CE->getType()); 4554 if (N != 1) Out << '_'; 4555 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 4556 if (N != 1) Out << 'E'; 4557 break; 4558 } 4559 4560 case Expr::CXXConstructExprClass: { 4561 // An implicit cast is silent, thus may contain <expr-primary>. 4562 const auto *CE = cast<CXXConstructExpr>(E); 4563 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) { 4564 assert( 4565 CE->getNumArgs() >= 1 && 4566 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && 4567 "implicit CXXConstructExpr must have one argument"); 4568 E = cast<CXXConstructExpr>(E)->getArg(0); 4569 goto recurse; 4570 } 4571 NotPrimaryExpr(); 4572 Out << "il"; 4573 for (auto *E : CE->arguments()) 4574 mangleExpression(E); 4575 Out << "E"; 4576 break; 4577 } 4578 4579 case Expr::CXXTemporaryObjectExprClass: { 4580 NotPrimaryExpr(); 4581 const auto *CE = cast<CXXTemporaryObjectExpr>(E); 4582 unsigned N = CE->getNumArgs(); 4583 bool List = CE->isListInitialization(); 4584 4585 if (List) 4586 Out << "tl"; 4587 else 4588 Out << "cv"; 4589 mangleType(CE->getType()); 4590 if (!List && N != 1) 4591 Out << '_'; 4592 if (CE->isStdInitListInitialization()) { 4593 // We implicitly created a std::initializer_list<T> for the first argument 4594 // of a constructor of type U in an expression of the form U{a, b, c}. 4595 // Strip all the semantic gunk off the initializer list. 4596 auto *SILE = 4597 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit()); 4598 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit()); 4599 mangleInitListElements(ILE); 4600 } else { 4601 for (auto *E : CE->arguments()) 4602 mangleExpression(E); 4603 } 4604 if (List || N != 1) 4605 Out << 'E'; 4606 break; 4607 } 4608 4609 case Expr::CXXScalarValueInitExprClass: 4610 NotPrimaryExpr(); 4611 Out << "cv"; 4612 mangleType(E->getType()); 4613 Out << "_E"; 4614 break; 4615 4616 case Expr::CXXNoexceptExprClass: 4617 NotPrimaryExpr(); 4618 Out << "nx"; 4619 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 4620 break; 4621 4622 case Expr::UnaryExprOrTypeTraitExprClass: { 4623 // Non-instantiation-dependent traits are an <expr-primary> integer literal. 4624 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 4625 4626 if (!SAE->isInstantiationDependent()) { 4627 // Itanium C++ ABI: 4628 // If the operand of a sizeof or alignof operator is not 4629 // instantiation-dependent it is encoded as an integer literal 4630 // reflecting the result of the operator. 4631 // 4632 // If the result of the operator is implicitly converted to a known 4633 // integer type, that type is used for the literal; otherwise, the type 4634 // of std::size_t or std::ptrdiff_t is used. 4635 QualType T = (ImplicitlyConvertedToType.isNull() || 4636 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 4637 : ImplicitlyConvertedToType; 4638 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 4639 mangleIntegerLiteral(T, V); 4640 break; 4641 } 4642 4643 NotPrimaryExpr(); // But otherwise, they are not. 4644 4645 auto MangleAlignofSizeofArg = [&] { 4646 if (SAE->isArgumentType()) { 4647 Out << 't'; 4648 mangleType(SAE->getArgumentType()); 4649 } else { 4650 Out << 'z'; 4651 mangleExpression(SAE->getArgumentExpr()); 4652 } 4653 }; 4654 4655 switch(SAE->getKind()) { 4656 case UETT_SizeOf: 4657 Out << 's'; 4658 MangleAlignofSizeofArg(); 4659 break; 4660 case UETT_PreferredAlignOf: 4661 // As of clang 12, we mangle __alignof__ differently than alignof. (They 4662 // have acted differently since Clang 8, but were previously mangled the 4663 // same.) 4664 if (Context.getASTContext().getLangOpts().getClangABICompat() > 4665 LangOptions::ClangABI::Ver11) { 4666 Out << "u11__alignof__"; 4667 if (SAE->isArgumentType()) 4668 mangleType(SAE->getArgumentType()); 4669 else 4670 mangleTemplateArgExpr(SAE->getArgumentExpr()); 4671 Out << 'E'; 4672 break; 4673 } 4674 LLVM_FALLTHROUGH; 4675 case UETT_AlignOf: 4676 Out << 'a'; 4677 MangleAlignofSizeofArg(); 4678 break; 4679 case UETT_VecStep: { 4680 DiagnosticsEngine &Diags = Context.getDiags(); 4681 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4682 "cannot yet mangle vec_step expression"); 4683 Diags.Report(DiagID); 4684 return; 4685 } 4686 case UETT_OpenMPRequiredSimdAlign: { 4687 DiagnosticsEngine &Diags = Context.getDiags(); 4688 unsigned DiagID = Diags.getCustomDiagID( 4689 DiagnosticsEngine::Error, 4690 "cannot yet mangle __builtin_omp_required_simd_align expression"); 4691 Diags.Report(DiagID); 4692 return; 4693 } 4694 } 4695 break; 4696 } 4697 4698 case Expr::CXXThrowExprClass: { 4699 NotPrimaryExpr(); 4700 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 4701 // <expression> ::= tw <expression> # throw expression 4702 // ::= tr # rethrow 4703 if (TE->getSubExpr()) { 4704 Out << "tw"; 4705 mangleExpression(TE->getSubExpr()); 4706 } else { 4707 Out << "tr"; 4708 } 4709 break; 4710 } 4711 4712 case Expr::CXXTypeidExprClass: { 4713 NotPrimaryExpr(); 4714 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 4715 // <expression> ::= ti <type> # typeid (type) 4716 // ::= te <expression> # typeid (expression) 4717 if (TIE->isTypeOperand()) { 4718 Out << "ti"; 4719 mangleType(TIE->getTypeOperand(Context.getASTContext())); 4720 } else { 4721 Out << "te"; 4722 mangleExpression(TIE->getExprOperand()); 4723 } 4724 break; 4725 } 4726 4727 case Expr::CXXDeleteExprClass: { 4728 NotPrimaryExpr(); 4729 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 4730 // <expression> ::= [gs] dl <expression> # [::] delete expr 4731 // ::= [gs] da <expression> # [::] delete [] expr 4732 if (DE->isGlobalDelete()) Out << "gs"; 4733 Out << (DE->isArrayForm() ? "da" : "dl"); 4734 mangleExpression(DE->getArgument()); 4735 break; 4736 } 4737 4738 case Expr::UnaryOperatorClass: { 4739 NotPrimaryExpr(); 4740 const UnaryOperator *UO = cast<UnaryOperator>(E); 4741 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 4742 /*Arity=*/1); 4743 mangleExpression(UO->getSubExpr()); 4744 break; 4745 } 4746 4747 case Expr::ArraySubscriptExprClass: { 4748 NotPrimaryExpr(); 4749 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 4750 4751 // Array subscript is treated as a syntactically weird form of 4752 // binary operator. 4753 Out << "ix"; 4754 mangleExpression(AE->getLHS()); 4755 mangleExpression(AE->getRHS()); 4756 break; 4757 } 4758 4759 case Expr::MatrixSubscriptExprClass: { 4760 NotPrimaryExpr(); 4761 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E); 4762 Out << "ixix"; 4763 mangleExpression(ME->getBase()); 4764 mangleExpression(ME->getRowIdx()); 4765 mangleExpression(ME->getColumnIdx()); 4766 break; 4767 } 4768 4769 case Expr::CompoundAssignOperatorClass: // fallthrough 4770 case Expr::BinaryOperatorClass: { 4771 NotPrimaryExpr(); 4772 const BinaryOperator *BO = cast<BinaryOperator>(E); 4773 if (BO->getOpcode() == BO_PtrMemD) 4774 Out << "ds"; 4775 else 4776 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 4777 /*Arity=*/2); 4778 mangleExpression(BO->getLHS()); 4779 mangleExpression(BO->getRHS()); 4780 break; 4781 } 4782 4783 case Expr::CXXRewrittenBinaryOperatorClass: { 4784 NotPrimaryExpr(); 4785 // The mangled form represents the original syntax. 4786 CXXRewrittenBinaryOperator::DecomposedForm Decomposed = 4787 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm(); 4788 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode), 4789 /*Arity=*/2); 4790 mangleExpression(Decomposed.LHS); 4791 mangleExpression(Decomposed.RHS); 4792 break; 4793 } 4794 4795 case Expr::ConditionalOperatorClass: { 4796 NotPrimaryExpr(); 4797 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 4798 mangleOperatorName(OO_Conditional, /*Arity=*/3); 4799 mangleExpression(CO->getCond()); 4800 mangleExpression(CO->getLHS(), Arity); 4801 mangleExpression(CO->getRHS(), Arity); 4802 break; 4803 } 4804 4805 case Expr::ImplicitCastExprClass: { 4806 ImplicitlyConvertedToType = E->getType(); 4807 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4808 goto recurse; 4809 } 4810 4811 case Expr::ObjCBridgedCastExprClass: { 4812 NotPrimaryExpr(); 4813 // Mangle ownership casts as a vendor extended operator __bridge, 4814 // __bridge_transfer, or __bridge_retain. 4815 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 4816 Out << "v1U" << Kind.size() << Kind; 4817 mangleCastExpression(E, "cv"); 4818 break; 4819 } 4820 4821 case Expr::CStyleCastExprClass: 4822 NotPrimaryExpr(); 4823 mangleCastExpression(E, "cv"); 4824 break; 4825 4826 case Expr::CXXFunctionalCastExprClass: { 4827 NotPrimaryExpr(); 4828 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit(); 4829 // FIXME: Add isImplicit to CXXConstructExpr. 4830 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub)) 4831 if (CCE->getParenOrBraceRange().isInvalid()) 4832 Sub = CCE->getArg(0)->IgnoreImplicit(); 4833 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub)) 4834 Sub = StdInitList->getSubExpr()->IgnoreImplicit(); 4835 if (auto *IL = dyn_cast<InitListExpr>(Sub)) { 4836 Out << "tl"; 4837 mangleType(E->getType()); 4838 mangleInitListElements(IL); 4839 Out << "E"; 4840 } else { 4841 mangleCastExpression(E, "cv"); 4842 } 4843 break; 4844 } 4845 4846 case Expr::CXXStaticCastExprClass: 4847 NotPrimaryExpr(); 4848 mangleCastExpression(E, "sc"); 4849 break; 4850 case Expr::CXXDynamicCastExprClass: 4851 NotPrimaryExpr(); 4852 mangleCastExpression(E, "dc"); 4853 break; 4854 case Expr::CXXReinterpretCastExprClass: 4855 NotPrimaryExpr(); 4856 mangleCastExpression(E, "rc"); 4857 break; 4858 case Expr::CXXConstCastExprClass: 4859 NotPrimaryExpr(); 4860 mangleCastExpression(E, "cc"); 4861 break; 4862 case Expr::CXXAddrspaceCastExprClass: 4863 NotPrimaryExpr(); 4864 mangleCastExpression(E, "ac"); 4865 break; 4866 4867 case Expr::CXXOperatorCallExprClass: { 4868 NotPrimaryExpr(); 4869 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 4870 unsigned NumArgs = CE->getNumArgs(); 4871 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax 4872 // (the enclosing MemberExpr covers the syntactic portion). 4873 if (CE->getOperator() != OO_Arrow) 4874 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 4875 // Mangle the arguments. 4876 for (unsigned i = 0; i != NumArgs; ++i) 4877 mangleExpression(CE->getArg(i)); 4878 break; 4879 } 4880 4881 case Expr::ParenExprClass: 4882 E = cast<ParenExpr>(E)->getSubExpr(); 4883 goto recurse; 4884 4885 case Expr::ConceptSpecializationExprClass: { 4886 // <expr-primary> ::= L <mangled-name> E # external name 4887 Out << "L_Z"; 4888 auto *CSE = cast<ConceptSpecializationExpr>(E); 4889 mangleTemplateName(CSE->getNamedConcept(), 4890 CSE->getTemplateArguments().data(), 4891 CSE->getTemplateArguments().size()); 4892 Out << 'E'; 4893 break; 4894 } 4895 4896 case Expr::DeclRefExprClass: 4897 // MangleDeclRefExpr helper handles primary-vs-nonprimary 4898 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl()); 4899 break; 4900 4901 case Expr::SubstNonTypeTemplateParmPackExprClass: 4902 NotPrimaryExpr(); 4903 // FIXME: not clear how to mangle this! 4904 // template <unsigned N...> class A { 4905 // template <class U...> void foo(U (&x)[N]...); 4906 // }; 4907 Out << "_SUBSTPACK_"; 4908 break; 4909 4910 case Expr::FunctionParmPackExprClass: { 4911 NotPrimaryExpr(); 4912 // FIXME: not clear how to mangle this! 4913 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 4914 Out << "v110_SUBSTPACK"; 4915 MangleDeclRefExpr(FPPE->getParameterPack()); 4916 break; 4917 } 4918 4919 case Expr::DependentScopeDeclRefExprClass: { 4920 NotPrimaryExpr(); 4921 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 4922 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), 4923 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(), 4924 Arity); 4925 break; 4926 } 4927 4928 case Expr::CXXBindTemporaryExprClass: 4929 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr(); 4930 goto recurse; 4931 4932 case Expr::ExprWithCleanupsClass: 4933 E = cast<ExprWithCleanups>(E)->getSubExpr(); 4934 goto recurse; 4935 4936 case Expr::FloatingLiteralClass: { 4937 // <expr-primary> 4938 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 4939 mangleFloatLiteral(FL->getType(), FL->getValue()); 4940 break; 4941 } 4942 4943 case Expr::FixedPointLiteralClass: 4944 // Currently unimplemented -- might be <expr-primary> in future? 4945 mangleFixedPointLiteral(); 4946 break; 4947 4948 case Expr::CharacterLiteralClass: 4949 // <expr-primary> 4950 Out << 'L'; 4951 mangleType(E->getType()); 4952 Out << cast<CharacterLiteral>(E)->getValue(); 4953 Out << 'E'; 4954 break; 4955 4956 // FIXME. __objc_yes/__objc_no are mangled same as true/false 4957 case Expr::ObjCBoolLiteralExprClass: 4958 // <expr-primary> 4959 Out << "Lb"; 4960 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4961 Out << 'E'; 4962 break; 4963 4964 case Expr::CXXBoolLiteralExprClass: 4965 // <expr-primary> 4966 Out << "Lb"; 4967 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4968 Out << 'E'; 4969 break; 4970 4971 case Expr::IntegerLiteralClass: { 4972 // <expr-primary> 4973 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 4974 if (E->getType()->isSignedIntegerType()) 4975 Value.setIsSigned(true); 4976 mangleIntegerLiteral(E->getType(), Value); 4977 break; 4978 } 4979 4980 case Expr::ImaginaryLiteralClass: { 4981 // <expr-primary> 4982 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 4983 // Mangle as if a complex literal. 4984 // Proposal from David Vandevoorde, 2010.06.30. 4985 Out << 'L'; 4986 mangleType(E->getType()); 4987 if (const FloatingLiteral *Imag = 4988 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 4989 // Mangle a floating-point zero of the appropriate type. 4990 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 4991 Out << '_'; 4992 mangleFloat(Imag->getValue()); 4993 } else { 4994 Out << "0_"; 4995 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 4996 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 4997 Value.setIsSigned(true); 4998 mangleNumber(Value); 4999 } 5000 Out << 'E'; 5001 break; 5002 } 5003 5004 case Expr::StringLiteralClass: { 5005 // <expr-primary> 5006 // Revised proposal from David Vandervoorde, 2010.07.15. 5007 Out << 'L'; 5008 assert(isa<ConstantArrayType>(E->getType())); 5009 mangleType(E->getType()); 5010 Out << 'E'; 5011 break; 5012 } 5013 5014 case Expr::GNUNullExprClass: 5015 // <expr-primary> 5016 // Mangle as if an integer literal 0. 5017 mangleIntegerLiteral(E->getType(), llvm::APSInt(32)); 5018 break; 5019 5020 case Expr::CXXNullPtrLiteralExprClass: { 5021 // <expr-primary> 5022 Out << "LDnE"; 5023 break; 5024 } 5025 5026 case Expr::LambdaExprClass: { 5027 // A lambda-expression can't appear in the signature of an 5028 // externally-visible declaration, so there's no standard mangling for 5029 // this, but mangling as a literal of the closure type seems reasonable. 5030 Out << "L"; 5031 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass())); 5032 Out << "E"; 5033 break; 5034 } 5035 5036 case Expr::PackExpansionExprClass: 5037 NotPrimaryExpr(); 5038 Out << "sp"; 5039 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 5040 break; 5041 5042 case Expr::SizeOfPackExprClass: { 5043 NotPrimaryExpr(); 5044 auto *SPE = cast<SizeOfPackExpr>(E); 5045 if (SPE->isPartiallySubstituted()) { 5046 Out << "sP"; 5047 for (const auto &A : SPE->getPartialArguments()) 5048 mangleTemplateArg(A, false); 5049 Out << "E"; 5050 break; 5051 } 5052 5053 Out << "sZ"; 5054 const NamedDecl *Pack = SPE->getPack(); 5055 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 5056 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 5057 else if (const NonTypeTemplateParmDecl *NTTP 5058 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 5059 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex()); 5060 else if (const TemplateTemplateParmDecl *TempTP 5061 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 5062 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex()); 5063 else 5064 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 5065 break; 5066 } 5067 5068 case Expr::MaterializeTemporaryExprClass: 5069 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr(); 5070 goto recurse; 5071 5072 case Expr::CXXFoldExprClass: { 5073 NotPrimaryExpr(); 5074 auto *FE = cast<CXXFoldExpr>(E); 5075 if (FE->isLeftFold()) 5076 Out << (FE->getInit() ? "fL" : "fl"); 5077 else 5078 Out << (FE->getInit() ? "fR" : "fr"); 5079 5080 if (FE->getOperator() == BO_PtrMemD) 5081 Out << "ds"; 5082 else 5083 mangleOperatorName( 5084 BinaryOperator::getOverloadedOperator(FE->getOperator()), 5085 /*Arity=*/2); 5086 5087 if (FE->getLHS()) 5088 mangleExpression(FE->getLHS()); 5089 if (FE->getRHS()) 5090 mangleExpression(FE->getRHS()); 5091 break; 5092 } 5093 5094 case Expr::CXXThisExprClass: 5095 NotPrimaryExpr(); 5096 Out << "fpT"; 5097 break; 5098 5099 case Expr::CoawaitExprClass: 5100 // FIXME: Propose a non-vendor mangling. 5101 NotPrimaryExpr(); 5102 Out << "v18co_await"; 5103 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 5104 break; 5105 5106 case Expr::DependentCoawaitExprClass: 5107 // FIXME: Propose a non-vendor mangling. 5108 NotPrimaryExpr(); 5109 Out << "v18co_await"; 5110 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand()); 5111 break; 5112 5113 case Expr::CoyieldExprClass: 5114 // FIXME: Propose a non-vendor mangling. 5115 NotPrimaryExpr(); 5116 Out << "v18co_yield"; 5117 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 5118 break; 5119 case Expr::SYCLUniqueStableNameExprClass: { 5120 const auto *USN = cast<SYCLUniqueStableNameExpr>(E); 5121 NotPrimaryExpr(); 5122 5123 Out << "u33__builtin_sycl_unique_stable_name"; 5124 mangleType(USN->getTypeSourceInfo()->getType()); 5125 5126 Out << "E"; 5127 break; 5128 } 5129 } 5130 5131 if (AsTemplateArg && !IsPrimaryExpr) 5132 Out << 'E'; 5133 } 5134 5135 /// Mangle an expression which refers to a parameter variable. 5136 /// 5137 /// <expression> ::= <function-param> 5138 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 5139 /// <function-param> ::= fp <top-level CV-qualifiers> 5140 /// <parameter-2 non-negative number> _ # L == 0, I > 0 5141 /// <function-param> ::= fL <L-1 non-negative number> 5142 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 5143 /// <function-param> ::= fL <L-1 non-negative number> 5144 /// p <top-level CV-qualifiers> 5145 /// <I-1 non-negative number> _ # L > 0, I > 0 5146 /// 5147 /// L is the nesting depth of the parameter, defined as 1 if the 5148 /// parameter comes from the innermost function prototype scope 5149 /// enclosing the current context, 2 if from the next enclosing 5150 /// function prototype scope, and so on, with one special case: if 5151 /// we've processed the full parameter clause for the innermost 5152 /// function type, then L is one less. This definition conveniently 5153 /// makes it irrelevant whether a function's result type was written 5154 /// trailing or leading, but is otherwise overly complicated; the 5155 /// numbering was first designed without considering references to 5156 /// parameter in locations other than return types, and then the 5157 /// mangling had to be generalized without changing the existing 5158 /// manglings. 5159 /// 5160 /// I is the zero-based index of the parameter within its parameter 5161 /// declaration clause. Note that the original ABI document describes 5162 /// this using 1-based ordinals. 5163 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 5164 unsigned parmDepth = parm->getFunctionScopeDepth(); 5165 unsigned parmIndex = parm->getFunctionScopeIndex(); 5166 5167 // Compute 'L'. 5168 // parmDepth does not include the declaring function prototype. 5169 // FunctionTypeDepth does account for that. 5170 assert(parmDepth < FunctionTypeDepth.getDepth()); 5171 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 5172 if (FunctionTypeDepth.isInResultType()) 5173 nestingDepth--; 5174 5175 if (nestingDepth == 0) { 5176 Out << "fp"; 5177 } else { 5178 Out << "fL" << (nestingDepth - 1) << 'p'; 5179 } 5180 5181 // Top-level qualifiers. We don't have to worry about arrays here, 5182 // because parameters declared as arrays should already have been 5183 // transformed to have pointer type. FIXME: apparently these don't 5184 // get mangled if used as an rvalue of a known non-class type? 5185 assert(!parm->getType()->isArrayType() 5186 && "parameter's type is still an array type?"); 5187 5188 if (const DependentAddressSpaceType *DAST = 5189 dyn_cast<DependentAddressSpaceType>(parm->getType())) { 5190 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST); 5191 } else { 5192 mangleQualifiers(parm->getType().getQualifiers()); 5193 } 5194 5195 // Parameter index. 5196 if (parmIndex != 0) { 5197 Out << (parmIndex - 1); 5198 } 5199 Out << '_'; 5200 } 5201 5202 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T, 5203 const CXXRecordDecl *InheritedFrom) { 5204 // <ctor-dtor-name> ::= C1 # complete object constructor 5205 // ::= C2 # base object constructor 5206 // ::= CI1 <type> # complete inheriting constructor 5207 // ::= CI2 <type> # base inheriting constructor 5208 // 5209 // In addition, C5 is a comdat name with C1 and C2 in it. 5210 Out << 'C'; 5211 if (InheritedFrom) 5212 Out << 'I'; 5213 switch (T) { 5214 case Ctor_Complete: 5215 Out << '1'; 5216 break; 5217 case Ctor_Base: 5218 Out << '2'; 5219 break; 5220 case Ctor_Comdat: 5221 Out << '5'; 5222 break; 5223 case Ctor_DefaultClosure: 5224 case Ctor_CopyingClosure: 5225 llvm_unreachable("closure constructors don't exist for the Itanium ABI!"); 5226 } 5227 if (InheritedFrom) 5228 mangleName(InheritedFrom); 5229 } 5230 5231 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 5232 // <ctor-dtor-name> ::= D0 # deleting destructor 5233 // ::= D1 # complete object destructor 5234 // ::= D2 # base object destructor 5235 // 5236 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 5237 switch (T) { 5238 case Dtor_Deleting: 5239 Out << "D0"; 5240 break; 5241 case Dtor_Complete: 5242 Out << "D1"; 5243 break; 5244 case Dtor_Base: 5245 Out << "D2"; 5246 break; 5247 case Dtor_Comdat: 5248 Out << "D5"; 5249 break; 5250 } 5251 } 5252 5253 namespace { 5254 // Helper to provide ancillary information on a template used to mangle its 5255 // arguments. 5256 struct TemplateArgManglingInfo { 5257 TemplateDecl *ResolvedTemplate = nullptr; 5258 bool SeenPackExpansionIntoNonPack = false; 5259 const NamedDecl *UnresolvedExpandedPack = nullptr; 5260 5261 TemplateArgManglingInfo(TemplateName TN) { 5262 if (TemplateDecl *TD = TN.getAsTemplateDecl()) 5263 ResolvedTemplate = TD; 5264 } 5265 5266 /// Do we need to mangle template arguments with exactly correct types? 5267 /// 5268 /// This should be called exactly once for each parameter / argument pair, in 5269 /// order. 5270 bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) { 5271 // We need correct types when the template-name is unresolved or when it 5272 // names a template that is able to be overloaded. 5273 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack) 5274 return true; 5275 5276 // Move to the next parameter. 5277 const NamedDecl *Param = UnresolvedExpandedPack; 5278 if (!Param) { 5279 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && 5280 "no parameter for argument"); 5281 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx); 5282 5283 // If we reach an expanded parameter pack whose argument isn't in pack 5284 // form, that means Sema couldn't figure out which arguments belonged to 5285 // it, because it contains a pack expansion. Track the expanded pack for 5286 // all further template arguments until we hit that pack expansion. 5287 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) { 5288 assert(getExpandedPackSize(Param) && 5289 "failed to form pack argument for parameter pack"); 5290 UnresolvedExpandedPack = Param; 5291 } 5292 } 5293 5294 // If we encounter a pack argument that is expanded into a non-pack 5295 // parameter, we can no longer track parameter / argument correspondence, 5296 // and need to use exact types from this point onwards. 5297 if (Arg.isPackExpansion() && 5298 (!Param->isParameterPack() || UnresolvedExpandedPack)) { 5299 SeenPackExpansionIntoNonPack = true; 5300 return true; 5301 } 5302 5303 // We need exact types for function template arguments because they might be 5304 // overloaded on template parameter type. As a special case, a member 5305 // function template of a generic lambda is not overloadable. 5306 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) { 5307 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext()); 5308 if (!RD || !RD->isGenericLambda()) 5309 return true; 5310 } 5311 5312 // Otherwise, we only need a correct type if the parameter has a deduced 5313 // type. 5314 // 5315 // Note: for an expanded parameter pack, getType() returns the type prior 5316 // to expansion. We could ask for the expanded type with getExpansionType(), 5317 // but it doesn't matter because substitution and expansion don't affect 5318 // whether a deduced type appears in the type. 5319 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param); 5320 return NTTP && NTTP->getType()->getContainedDeducedType(); 5321 } 5322 }; 5323 } 5324 5325 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5326 const TemplateArgumentLoc *TemplateArgs, 5327 unsigned NumTemplateArgs) { 5328 // <template-args> ::= I <template-arg>+ E 5329 Out << 'I'; 5330 TemplateArgManglingInfo Info(TN); 5331 for (unsigned i = 0; i != NumTemplateArgs; ++i) 5332 mangleTemplateArg(TemplateArgs[i].getArgument(), 5333 Info.needExactType(i, TemplateArgs[i].getArgument())); 5334 Out << 'E'; 5335 } 5336 5337 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5338 const TemplateArgumentList &AL) { 5339 // <template-args> ::= I <template-arg>+ E 5340 Out << 'I'; 5341 TemplateArgManglingInfo Info(TN); 5342 for (unsigned i = 0, e = AL.size(); i != e; ++i) 5343 mangleTemplateArg(AL[i], Info.needExactType(i, AL[i])); 5344 Out << 'E'; 5345 } 5346 5347 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5348 const TemplateArgument *TemplateArgs, 5349 unsigned NumTemplateArgs) { 5350 // <template-args> ::= I <template-arg>+ E 5351 Out << 'I'; 5352 TemplateArgManglingInfo Info(TN); 5353 for (unsigned i = 0; i != NumTemplateArgs; ++i) 5354 mangleTemplateArg(TemplateArgs[i], Info.needExactType(i, TemplateArgs[i])); 5355 Out << 'E'; 5356 } 5357 5358 void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) { 5359 // <template-arg> ::= <type> # type or template 5360 // ::= X <expression> E # expression 5361 // ::= <expr-primary> # simple expressions 5362 // ::= J <template-arg>* E # argument pack 5363 if (!A.isInstantiationDependent() || A.isDependent()) 5364 A = Context.getASTContext().getCanonicalTemplateArgument(A); 5365 5366 switch (A.getKind()) { 5367 case TemplateArgument::Null: 5368 llvm_unreachable("Cannot mangle NULL template argument"); 5369 5370 case TemplateArgument::Type: 5371 mangleType(A.getAsType()); 5372 break; 5373 case TemplateArgument::Template: 5374 // This is mangled as <type>. 5375 mangleType(A.getAsTemplate()); 5376 break; 5377 case TemplateArgument::TemplateExpansion: 5378 // <type> ::= Dp <type> # pack expansion (C++0x) 5379 Out << "Dp"; 5380 mangleType(A.getAsTemplateOrTemplatePattern()); 5381 break; 5382 case TemplateArgument::Expression: 5383 mangleTemplateArgExpr(A.getAsExpr()); 5384 break; 5385 case TemplateArgument::Integral: 5386 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 5387 break; 5388 case TemplateArgument::Declaration: { 5389 // <expr-primary> ::= L <mangled-name> E # external name 5390 ValueDecl *D = A.getAsDecl(); 5391 5392 // Template parameter objects are modeled by reproducing a source form 5393 // produced as if by aggregate initialization. 5394 if (A.getParamTypeForDecl()->isRecordType()) { 5395 auto *TPO = cast<TemplateParamObjectDecl>(D); 5396 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(), 5397 TPO->getValue(), /*TopLevel=*/true, 5398 NeedExactType); 5399 break; 5400 } 5401 5402 ASTContext &Ctx = Context.getASTContext(); 5403 APValue Value; 5404 if (D->isCXXInstanceMember()) 5405 // Simple pointer-to-member with no conversion. 5406 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{}); 5407 else if (D->getType()->isArrayType() && 5408 Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()), 5409 A.getParamTypeForDecl()) && 5410 Ctx.getLangOpts().getClangABICompat() > 5411 LangOptions::ClangABI::Ver11) 5412 // Build a value corresponding to this implicit array-to-pointer decay. 5413 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 5414 {APValue::LValuePathEntry::ArrayIndex(0)}, 5415 /*OnePastTheEnd=*/false); 5416 else 5417 // Regular pointer or reference to a declaration. 5418 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 5419 ArrayRef<APValue::LValuePathEntry>(), 5420 /*OnePastTheEnd=*/false); 5421 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true, 5422 NeedExactType); 5423 break; 5424 } 5425 case TemplateArgument::NullPtr: { 5426 mangleNullPointer(A.getNullPtrType()); 5427 break; 5428 } 5429 case TemplateArgument::Pack: { 5430 // <template-arg> ::= J <template-arg>* E 5431 Out << 'J'; 5432 for (const auto &P : A.pack_elements()) 5433 mangleTemplateArg(P, NeedExactType); 5434 Out << 'E'; 5435 } 5436 } 5437 } 5438 5439 void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) { 5440 ASTContext &Ctx = Context.getASTContext(); 5441 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) { 5442 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true); 5443 return; 5444 } 5445 5446 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary> 5447 // correctly in cases where the template argument was 5448 // constructed from an expression rather than an already-evaluated 5449 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of 5450 // 'Li0E'. 5451 // 5452 // We did special-case DeclRefExpr to attempt to DTRT for that one 5453 // expression-kind, but while doing so, unfortunately handled ParmVarDecl 5454 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of 5455 // the proper 'Xfp_E'. 5456 E = E->IgnoreParenImpCasts(); 5457 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 5458 const ValueDecl *D = DRE->getDecl(); 5459 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 5460 Out << 'L'; 5461 mangle(D); 5462 Out << 'E'; 5463 return; 5464 } 5465 } 5466 Out << 'X'; 5467 mangleExpression(E); 5468 Out << 'E'; 5469 } 5470 5471 /// Determine whether a given value is equivalent to zero-initialization for 5472 /// the purpose of discarding a trailing portion of a 'tl' mangling. 5473 /// 5474 /// Note that this is not in general equivalent to determining whether the 5475 /// value has an all-zeroes bit pattern. 5476 static bool isZeroInitialized(QualType T, const APValue &V) { 5477 // FIXME: mangleValueInTemplateArg has quadratic time complexity in 5478 // pathological cases due to using this, but it's a little awkward 5479 // to do this in linear time in general. 5480 switch (V.getKind()) { 5481 case APValue::None: 5482 case APValue::Indeterminate: 5483 case APValue::AddrLabelDiff: 5484 return false; 5485 5486 case APValue::Struct: { 5487 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5488 assert(RD && "unexpected type for record value"); 5489 unsigned I = 0; 5490 for (const CXXBaseSpecifier &BS : RD->bases()) { 5491 if (!isZeroInitialized(BS.getType(), V.getStructBase(I))) 5492 return false; 5493 ++I; 5494 } 5495 I = 0; 5496 for (const FieldDecl *FD : RD->fields()) { 5497 if (!FD->isUnnamedBitfield() && 5498 !isZeroInitialized(FD->getType(), V.getStructField(I))) 5499 return false; 5500 ++I; 5501 } 5502 return true; 5503 } 5504 5505 case APValue::Union: { 5506 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5507 assert(RD && "unexpected type for union value"); 5508 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any. 5509 for (const FieldDecl *FD : RD->fields()) { 5510 if (!FD->isUnnamedBitfield()) 5511 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) && 5512 isZeroInitialized(FD->getType(), V.getUnionValue()); 5513 } 5514 // If there are no fields (other than unnamed bitfields), the value is 5515 // necessarily zero-initialized. 5516 return true; 5517 } 5518 5519 case APValue::Array: { 5520 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 5521 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I) 5522 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I))) 5523 return false; 5524 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller()); 5525 } 5526 5527 case APValue::Vector: { 5528 const VectorType *VT = T->castAs<VectorType>(); 5529 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) 5530 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I))) 5531 return false; 5532 return true; 5533 } 5534 5535 case APValue::Int: 5536 return !V.getInt(); 5537 5538 case APValue::Float: 5539 return V.getFloat().isPosZero(); 5540 5541 case APValue::FixedPoint: 5542 return !V.getFixedPoint().getValue(); 5543 5544 case APValue::ComplexFloat: 5545 return V.getComplexFloatReal().isPosZero() && 5546 V.getComplexFloatImag().isPosZero(); 5547 5548 case APValue::ComplexInt: 5549 return !V.getComplexIntReal() && !V.getComplexIntImag(); 5550 5551 case APValue::LValue: 5552 return V.isNullPointer(); 5553 5554 case APValue::MemberPointer: 5555 return !V.getMemberPointerDecl(); 5556 } 5557 5558 llvm_unreachable("Unhandled APValue::ValueKind enum"); 5559 } 5560 5561 static QualType getLValueType(ASTContext &Ctx, const APValue &LV) { 5562 QualType T = LV.getLValueBase().getType(); 5563 for (APValue::LValuePathEntry E : LV.getLValuePath()) { 5564 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 5565 T = AT->getElementType(); 5566 else if (const FieldDecl *FD = 5567 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer())) 5568 T = FD->getType(); 5569 else 5570 T = Ctx.getRecordType( 5571 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer())); 5572 } 5573 return T; 5574 } 5575 5576 static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc, 5577 DiagnosticsEngine &Diags, 5578 const FieldDecl *FD) { 5579 // According to: 5580 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous 5581 // For the purposes of mangling, the name of an anonymous union is considered 5582 // to be the name of the first named data member found by a pre-order, 5583 // depth-first, declaration-order walk of the data members of the anonymous 5584 // union. 5585 5586 if (FD->getIdentifier()) 5587 return FD->getIdentifier(); 5588 5589 // The only cases where the identifer of a FieldDecl would be blank is if the 5590 // field represents an anonymous record type or if it is an unnamed bitfield. 5591 // There is no type to descend into in the case of a bitfield, so we can just 5592 // return nullptr in that case. 5593 if (FD->isBitField()) 5594 return nullptr; 5595 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 5596 5597 // Consider only the fields in declaration order, searched depth-first. We 5598 // don't care about the active member of the union, as all we are doing is 5599 // looking for a valid name. We also don't check bases, due to guidance from 5600 // the Itanium ABI folks. 5601 for (const FieldDecl *RDField : RD->fields()) { 5602 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField)) 5603 return II; 5604 } 5605 5606 // According to the Itanium ABI: If there is no such data member (i.e., if all 5607 // of the data members in the union are unnamed), then there is no way for a 5608 // program to refer to the anonymous union, and there is therefore no need to 5609 // mangle its name. However, we should diagnose this anyway. 5610 unsigned DiagID = Diags.getCustomDiagID( 5611 DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet"); 5612 Diags.Report(UnionLoc, DiagID); 5613 5614 return nullptr; 5615 } 5616 5617 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V, 5618 bool TopLevel, 5619 bool NeedExactType) { 5620 // Ignore all top-level cv-qualifiers, to match GCC. 5621 Qualifiers Quals; 5622 T = getASTContext().getUnqualifiedArrayType(T, Quals); 5623 5624 // A top-level expression that's not a primary expression is wrapped in X...E. 5625 bool IsPrimaryExpr = true; 5626 auto NotPrimaryExpr = [&] { 5627 if (TopLevel && IsPrimaryExpr) 5628 Out << 'X'; 5629 IsPrimaryExpr = false; 5630 }; 5631 5632 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63. 5633 switch (V.getKind()) { 5634 case APValue::None: 5635 case APValue::Indeterminate: 5636 Out << 'L'; 5637 mangleType(T); 5638 Out << 'E'; 5639 break; 5640 5641 case APValue::AddrLabelDiff: 5642 llvm_unreachable("unexpected value kind in template argument"); 5643 5644 case APValue::Struct: { 5645 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5646 assert(RD && "unexpected type for record value"); 5647 5648 // Drop trailing zero-initialized elements. 5649 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields()); 5650 while ( 5651 !Fields.empty() && 5652 (Fields.back()->isUnnamedBitfield() || 5653 isZeroInitialized(Fields.back()->getType(), 5654 V.getStructField(Fields.back()->getFieldIndex())))) { 5655 Fields.pop_back(); 5656 } 5657 llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end()); 5658 if (Fields.empty()) { 5659 while (!Bases.empty() && 5660 isZeroInitialized(Bases.back().getType(), 5661 V.getStructBase(Bases.size() - 1))) 5662 Bases = Bases.drop_back(); 5663 } 5664 5665 // <expression> ::= tl <type> <braced-expression>* E 5666 NotPrimaryExpr(); 5667 Out << "tl"; 5668 mangleType(T); 5669 for (unsigned I = 0, N = Bases.size(); I != N; ++I) 5670 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false); 5671 for (unsigned I = 0, N = Fields.size(); I != N; ++I) { 5672 if (Fields[I]->isUnnamedBitfield()) 5673 continue; 5674 mangleValueInTemplateArg(Fields[I]->getType(), 5675 V.getStructField(Fields[I]->getFieldIndex()), 5676 false); 5677 } 5678 Out << 'E'; 5679 break; 5680 } 5681 5682 case APValue::Union: { 5683 assert(T->getAsCXXRecordDecl() && "unexpected type for union value"); 5684 const FieldDecl *FD = V.getUnionField(); 5685 5686 if (!FD) { 5687 Out << 'L'; 5688 mangleType(T); 5689 Out << 'E'; 5690 break; 5691 } 5692 5693 // <braced-expression> ::= di <field source-name> <braced-expression> 5694 NotPrimaryExpr(); 5695 Out << "tl"; 5696 mangleType(T); 5697 if (!isZeroInitialized(T, V)) { 5698 Out << "di"; 5699 IdentifierInfo *II = (getUnionInitName( 5700 T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD)); 5701 if (II) 5702 mangleSourceName(II); 5703 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false); 5704 } 5705 Out << 'E'; 5706 break; 5707 } 5708 5709 case APValue::Array: { 5710 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 5711 5712 NotPrimaryExpr(); 5713 Out << "tl"; 5714 mangleType(T); 5715 5716 // Drop trailing zero-initialized elements. 5717 unsigned N = V.getArraySize(); 5718 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) { 5719 N = V.getArrayInitializedElts(); 5720 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1))) 5721 --N; 5722 } 5723 5724 for (unsigned I = 0; I != N; ++I) { 5725 const APValue &Elem = I < V.getArrayInitializedElts() 5726 ? V.getArrayInitializedElt(I) 5727 : V.getArrayFiller(); 5728 mangleValueInTemplateArg(ElemT, Elem, false); 5729 } 5730 Out << 'E'; 5731 break; 5732 } 5733 5734 case APValue::Vector: { 5735 const VectorType *VT = T->castAs<VectorType>(); 5736 5737 NotPrimaryExpr(); 5738 Out << "tl"; 5739 mangleType(T); 5740 unsigned N = V.getVectorLength(); 5741 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1))) 5742 --N; 5743 for (unsigned I = 0; I != N; ++I) 5744 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false); 5745 Out << 'E'; 5746 break; 5747 } 5748 5749 case APValue::Int: 5750 mangleIntegerLiteral(T, V.getInt()); 5751 break; 5752 5753 case APValue::Float: 5754 mangleFloatLiteral(T, V.getFloat()); 5755 break; 5756 5757 case APValue::FixedPoint: 5758 mangleFixedPointLiteral(); 5759 break; 5760 5761 case APValue::ComplexFloat: { 5762 const ComplexType *CT = T->castAs<ComplexType>(); 5763 NotPrimaryExpr(); 5764 Out << "tl"; 5765 mangleType(T); 5766 if (!V.getComplexFloatReal().isPosZero() || 5767 !V.getComplexFloatImag().isPosZero()) 5768 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal()); 5769 if (!V.getComplexFloatImag().isPosZero()) 5770 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag()); 5771 Out << 'E'; 5772 break; 5773 } 5774 5775 case APValue::ComplexInt: { 5776 const ComplexType *CT = T->castAs<ComplexType>(); 5777 NotPrimaryExpr(); 5778 Out << "tl"; 5779 mangleType(T); 5780 if (V.getComplexIntReal().getBoolValue() || 5781 V.getComplexIntImag().getBoolValue()) 5782 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal()); 5783 if (V.getComplexIntImag().getBoolValue()) 5784 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag()); 5785 Out << 'E'; 5786 break; 5787 } 5788 5789 case APValue::LValue: { 5790 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 5791 assert((T->isPointerType() || T->isReferenceType()) && 5792 "unexpected type for LValue template arg"); 5793 5794 if (V.isNullPointer()) { 5795 mangleNullPointer(T); 5796 break; 5797 } 5798 5799 APValue::LValueBase B = V.getLValueBase(); 5800 if (!B) { 5801 // Non-standard mangling for integer cast to a pointer; this can only 5802 // occur as an extension. 5803 CharUnits Offset = V.getLValueOffset(); 5804 if (Offset.isZero()) { 5805 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as 5806 // a cast, because L <type> 0 E means something else. 5807 NotPrimaryExpr(); 5808 Out << "rc"; 5809 mangleType(T); 5810 Out << "Li0E"; 5811 if (TopLevel) 5812 Out << 'E'; 5813 } else { 5814 Out << "L"; 5815 mangleType(T); 5816 Out << Offset.getQuantity() << 'E'; 5817 } 5818 break; 5819 } 5820 5821 ASTContext &Ctx = Context.getASTContext(); 5822 5823 enum { Base, Offset, Path } Kind; 5824 if (!V.hasLValuePath()) { 5825 // Mangle as (T*)((char*)&base + N). 5826 if (T->isReferenceType()) { 5827 NotPrimaryExpr(); 5828 Out << "decvP"; 5829 mangleType(T->getPointeeType()); 5830 } else { 5831 NotPrimaryExpr(); 5832 Out << "cv"; 5833 mangleType(T); 5834 } 5835 Out << "plcvPcad"; 5836 Kind = Offset; 5837 } else { 5838 if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) { 5839 NotPrimaryExpr(); 5840 // A final conversion to the template parameter's type is usually 5841 // folded into the 'so' mangling, but we can't do that for 'void*' 5842 // parameters without introducing collisions. 5843 if (NeedExactType && T->isVoidPointerType()) { 5844 Out << "cv"; 5845 mangleType(T); 5846 } 5847 if (T->isPointerType()) 5848 Out << "ad"; 5849 Out << "so"; 5850 mangleType(T->isVoidPointerType() 5851 ? getLValueType(Ctx, V).getUnqualifiedType() 5852 : T->getPointeeType()); 5853 Kind = Path; 5854 } else { 5855 if (NeedExactType && 5856 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) && 5857 Ctx.getLangOpts().getClangABICompat() > 5858 LangOptions::ClangABI::Ver11) { 5859 NotPrimaryExpr(); 5860 Out << "cv"; 5861 mangleType(T); 5862 } 5863 if (T->isPointerType()) { 5864 NotPrimaryExpr(); 5865 Out << "ad"; 5866 } 5867 Kind = Base; 5868 } 5869 } 5870 5871 QualType TypeSoFar = B.getType(); 5872 if (auto *VD = B.dyn_cast<const ValueDecl*>()) { 5873 Out << 'L'; 5874 mangle(VD); 5875 Out << 'E'; 5876 } else if (auto *E = B.dyn_cast<const Expr*>()) { 5877 NotPrimaryExpr(); 5878 mangleExpression(E); 5879 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) { 5880 NotPrimaryExpr(); 5881 Out << "ti"; 5882 mangleType(QualType(TI.getType(), 0)); 5883 } else { 5884 // We should never see dynamic allocations here. 5885 llvm_unreachable("unexpected lvalue base kind in template argument"); 5886 } 5887 5888 switch (Kind) { 5889 case Base: 5890 break; 5891 5892 case Offset: 5893 Out << 'L'; 5894 mangleType(Ctx.getPointerDiffType()); 5895 mangleNumber(V.getLValueOffset().getQuantity()); 5896 Out << 'E'; 5897 break; 5898 5899 case Path: 5900 // <expression> ::= so <referent type> <expr> [<offset number>] 5901 // <union-selector>* [p] E 5902 if (!V.getLValueOffset().isZero()) 5903 mangleNumber(V.getLValueOffset().getQuantity()); 5904 5905 // We model a past-the-end array pointer as array indexing with index N, 5906 // not with the "past the end" flag. Compensate for that. 5907 bool OnePastTheEnd = V.isLValueOnePastTheEnd(); 5908 5909 for (APValue::LValuePathEntry E : V.getLValuePath()) { 5910 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) { 5911 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5912 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex(); 5913 TypeSoFar = AT->getElementType(); 5914 } else { 5915 const Decl *D = E.getAsBaseOrMember().getPointer(); 5916 if (auto *FD = dyn_cast<FieldDecl>(D)) { 5917 // <union-selector> ::= _ <number> 5918 if (FD->getParent()->isUnion()) { 5919 Out << '_'; 5920 if (FD->getFieldIndex()) 5921 Out << (FD->getFieldIndex() - 1); 5922 } 5923 TypeSoFar = FD->getType(); 5924 } else { 5925 TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D)); 5926 } 5927 } 5928 } 5929 5930 if (OnePastTheEnd) 5931 Out << 'p'; 5932 Out << 'E'; 5933 break; 5934 } 5935 5936 break; 5937 } 5938 5939 case APValue::MemberPointer: 5940 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 5941 if (!V.getMemberPointerDecl()) { 5942 mangleNullPointer(T); 5943 break; 5944 } 5945 5946 ASTContext &Ctx = Context.getASTContext(); 5947 5948 NotPrimaryExpr(); 5949 if (!V.getMemberPointerPath().empty()) { 5950 Out << "mc"; 5951 mangleType(T); 5952 } else if (NeedExactType && 5953 !Ctx.hasSameType( 5954 T->castAs<MemberPointerType>()->getPointeeType(), 5955 V.getMemberPointerDecl()->getType()) && 5956 Ctx.getLangOpts().getClangABICompat() > 5957 LangOptions::ClangABI::Ver11) { 5958 Out << "cv"; 5959 mangleType(T); 5960 } 5961 Out << "adL"; 5962 mangle(V.getMemberPointerDecl()); 5963 Out << 'E'; 5964 if (!V.getMemberPointerPath().empty()) { 5965 CharUnits Offset = 5966 Context.getASTContext().getMemberPointerPathAdjustment(V); 5967 if (!Offset.isZero()) 5968 mangleNumber(Offset.getQuantity()); 5969 Out << 'E'; 5970 } 5971 break; 5972 } 5973 5974 if (TopLevel && !IsPrimaryExpr) 5975 Out << 'E'; 5976 } 5977 5978 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) { 5979 // <template-param> ::= T_ # first template parameter 5980 // ::= T <parameter-2 non-negative number> _ 5981 // ::= TL <L-1 non-negative number> __ 5982 // ::= TL <L-1 non-negative number> _ 5983 // <parameter-2 non-negative number> _ 5984 // 5985 // The latter two manglings are from a proposal here: 5986 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117 5987 Out << 'T'; 5988 if (Depth != 0) 5989 Out << 'L' << (Depth - 1) << '_'; 5990 if (Index != 0) 5991 Out << (Index - 1); 5992 Out << '_'; 5993 } 5994 5995 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 5996 if (SeqID == 0) { 5997 // Nothing. 5998 } else if (SeqID == 1) { 5999 Out << '0'; 6000 } else { 6001 SeqID--; 6002 6003 // <seq-id> is encoded in base-36, using digits and upper case letters. 6004 char Buffer[7]; // log(2**32) / log(36) ~= 7 6005 MutableArrayRef<char> BufferRef(Buffer); 6006 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 6007 6008 for (; SeqID != 0; SeqID /= 36) { 6009 unsigned C = SeqID % 36; 6010 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 6011 } 6012 6013 Out.write(I.base(), I - BufferRef.rbegin()); 6014 } 6015 Out << '_'; 6016 } 6017 6018 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 6019 bool result = mangleSubstitution(tname); 6020 assert(result && "no existing substitution for template name"); 6021 (void) result; 6022 } 6023 6024 // <substitution> ::= S <seq-id> _ 6025 // ::= S_ 6026 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 6027 // Try one of the standard substitutions first. 6028 if (mangleStandardSubstitution(ND)) 6029 return true; 6030 6031 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 6032 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 6033 } 6034 6035 bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) { 6036 assert(NNS->getKind() == NestedNameSpecifier::Identifier && 6037 "mangleSubstitution(NestedNameSpecifier *) is only used for " 6038 "identifier nested name specifiers."); 6039 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS); 6040 return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS)); 6041 } 6042 6043 /// Determine whether the given type has any qualifiers that are relevant for 6044 /// substitutions. 6045 static bool hasMangledSubstitutionQualifiers(QualType T) { 6046 Qualifiers Qs = T.getQualifiers(); 6047 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned(); 6048 } 6049 6050 bool CXXNameMangler::mangleSubstitution(QualType T) { 6051 if (!hasMangledSubstitutionQualifiers(T)) { 6052 if (const RecordType *RT = T->getAs<RecordType>()) 6053 return mangleSubstitution(RT->getDecl()); 6054 } 6055 6056 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 6057 6058 return mangleSubstitution(TypePtr); 6059 } 6060 6061 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 6062 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 6063 return mangleSubstitution(TD); 6064 6065 Template = Context.getASTContext().getCanonicalTemplateName(Template); 6066 return mangleSubstitution( 6067 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 6068 } 6069 6070 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 6071 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 6072 if (I == Substitutions.end()) 6073 return false; 6074 6075 unsigned SeqID = I->second; 6076 Out << 'S'; 6077 mangleSeqID(SeqID); 6078 6079 return true; 6080 } 6081 6082 /// Returns whether S is a template specialization of std::Name with a single 6083 /// argument of type A. 6084 bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name, 6085 QualType A) { 6086 if (S.isNull()) 6087 return false; 6088 6089 const RecordType *RT = S->getAs<RecordType>(); 6090 if (!RT) 6091 return false; 6092 6093 const ClassTemplateSpecializationDecl *SD = 6094 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6095 if (!SD || !SD->getIdentifier()->isStr(Name)) 6096 return false; 6097 6098 if (!isStdNamespace(Context.getEffectiveDeclContext(SD))) 6099 return false; 6100 6101 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 6102 if (TemplateArgs.size() != 1) 6103 return false; 6104 6105 if (TemplateArgs[0].getAsType() != A) 6106 return false; 6107 6108 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6109 return false; 6110 6111 return true; 6112 } 6113 6114 /// Returns whether SD is a template specialization std::Name<char, 6115 /// std::char_traits<char> [, std::allocator<char>]> 6116 /// HasAllocator controls whether the 3rd template argument is needed. 6117 bool CXXNameMangler::isStdCharSpecialization( 6118 const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name, 6119 bool HasAllocator) { 6120 if (!SD->getIdentifier()->isStr(Name)) 6121 return false; 6122 6123 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 6124 if (TemplateArgs.size() != (HasAllocator ? 3 : 2)) 6125 return false; 6126 6127 QualType A = TemplateArgs[0].getAsType(); 6128 if (A.isNull()) 6129 return false; 6130 // Plain 'char' is named Char_S or Char_U depending on the target ABI. 6131 if (!A->isSpecificBuiltinType(BuiltinType::Char_S) && 6132 !A->isSpecificBuiltinType(BuiltinType::Char_U)) 6133 return false; 6134 6135 if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A)) 6136 return false; 6137 6138 if (HasAllocator && 6139 !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A)) 6140 return false; 6141 6142 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6143 return false; 6144 6145 return true; 6146 } 6147 6148 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 6149 // <substitution> ::= St # ::std:: 6150 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 6151 if (isStd(NS)) { 6152 Out << "St"; 6153 return true; 6154 } 6155 return false; 6156 } 6157 6158 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 6159 if (!isStdNamespace(Context.getEffectiveDeclContext(TD))) 6160 return false; 6161 6162 if (TD->getOwningModuleForLinkage()) 6163 return false; 6164 6165 // <substitution> ::= Sa # ::std::allocator 6166 if (TD->getIdentifier()->isStr("allocator")) { 6167 Out << "Sa"; 6168 return true; 6169 } 6170 6171 // <<substitution> ::= Sb # ::std::basic_string 6172 if (TD->getIdentifier()->isStr("basic_string")) { 6173 Out << "Sb"; 6174 return true; 6175 } 6176 return false; 6177 } 6178 6179 if (const ClassTemplateSpecializationDecl *SD = 6180 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 6181 if (!isStdNamespace(Context.getEffectiveDeclContext(SD))) 6182 return false; 6183 6184 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6185 return false; 6186 6187 // <substitution> ::= Ss # ::std::basic_string<char, 6188 // ::std::char_traits<char>, 6189 // ::std::allocator<char> > 6190 if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) { 6191 Out << "Ss"; 6192 return true; 6193 } 6194 6195 // <substitution> ::= Si # ::std::basic_istream<char, 6196 // ::std::char_traits<char> > 6197 if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) { 6198 Out << "Si"; 6199 return true; 6200 } 6201 6202 // <substitution> ::= So # ::std::basic_ostream<char, 6203 // ::std::char_traits<char> > 6204 if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) { 6205 Out << "So"; 6206 return true; 6207 } 6208 6209 // <substitution> ::= Sd # ::std::basic_iostream<char, 6210 // ::std::char_traits<char> > 6211 if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) { 6212 Out << "Sd"; 6213 return true; 6214 } 6215 return false; 6216 } 6217 6218 return false; 6219 } 6220 6221 void CXXNameMangler::addSubstitution(QualType T) { 6222 if (!hasMangledSubstitutionQualifiers(T)) { 6223 if (const RecordType *RT = T->getAs<RecordType>()) { 6224 addSubstitution(RT->getDecl()); 6225 return; 6226 } 6227 } 6228 6229 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 6230 addSubstitution(TypePtr); 6231 } 6232 6233 void CXXNameMangler::addSubstitution(TemplateName Template) { 6234 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 6235 return addSubstitution(TD); 6236 6237 Template = Context.getASTContext().getCanonicalTemplateName(Template); 6238 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 6239 } 6240 6241 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 6242 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 6243 Substitutions[Ptr] = SeqID++; 6244 } 6245 6246 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) { 6247 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!"); 6248 if (Other->SeqID > SeqID) { 6249 Substitutions.swap(Other->Substitutions); 6250 SeqID = Other->SeqID; 6251 } 6252 } 6253 6254 CXXNameMangler::AbiTagList 6255 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) { 6256 // When derived abi tags are disabled there is no need to make any list. 6257 if (DisableDerivedAbiTags) 6258 return AbiTagList(); 6259 6260 llvm::raw_null_ostream NullOutStream; 6261 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream); 6262 TrackReturnTypeTags.disableDerivedAbiTags(); 6263 6264 const FunctionProtoType *Proto = 6265 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 6266 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push(); 6267 TrackReturnTypeTags.FunctionTypeDepth.enterResultType(); 6268 TrackReturnTypeTags.mangleType(Proto->getReturnType()); 6269 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType(); 6270 TrackReturnTypeTags.FunctionTypeDepth.pop(saved); 6271 6272 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 6273 } 6274 6275 CXXNameMangler::AbiTagList 6276 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) { 6277 // When derived abi tags are disabled there is no need to make any list. 6278 if (DisableDerivedAbiTags) 6279 return AbiTagList(); 6280 6281 llvm::raw_null_ostream NullOutStream; 6282 CXXNameMangler TrackVariableType(*this, NullOutStream); 6283 TrackVariableType.disableDerivedAbiTags(); 6284 6285 TrackVariableType.mangleType(VD->getType()); 6286 6287 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 6288 } 6289 6290 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C, 6291 const VarDecl *VD) { 6292 llvm::raw_null_ostream NullOutStream; 6293 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true); 6294 TrackAbiTags.mangle(VD); 6295 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size(); 6296 } 6297 6298 // 6299 6300 /// Mangles the name of the declaration D and emits that name to the given 6301 /// output stream. 6302 /// 6303 /// If the declaration D requires a mangled name, this routine will emit that 6304 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 6305 /// and this routine will return false. In this case, the caller should just 6306 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 6307 /// name. 6308 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD, 6309 raw_ostream &Out) { 6310 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 6311 assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) && 6312 "Invalid mangleName() call, argument is not a variable or function!"); 6313 6314 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 6315 getASTContext().getSourceManager(), 6316 "Mangling declaration"); 6317 6318 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) { 6319 auto Type = GD.getCtorType(); 6320 CXXNameMangler Mangler(*this, Out, CD, Type); 6321 return Mangler.mangle(GlobalDecl(CD, Type)); 6322 } 6323 6324 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) { 6325 auto Type = GD.getDtorType(); 6326 CXXNameMangler Mangler(*this, Out, DD, Type); 6327 return Mangler.mangle(GlobalDecl(DD, Type)); 6328 } 6329 6330 CXXNameMangler Mangler(*this, Out, D); 6331 Mangler.mangle(GD); 6332 } 6333 6334 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 6335 raw_ostream &Out) { 6336 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 6337 Mangler.mangle(GlobalDecl(D, Ctor_Comdat)); 6338 } 6339 6340 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 6341 raw_ostream &Out) { 6342 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 6343 Mangler.mangle(GlobalDecl(D, Dtor_Comdat)); 6344 } 6345 6346 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 6347 const ThunkInfo &Thunk, 6348 raw_ostream &Out) { 6349 // <special-name> ::= T <call-offset> <base encoding> 6350 // # base is the nominal target function of thunk 6351 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 6352 // # base is the nominal target function of thunk 6353 // # first call-offset is 'this' adjustment 6354 // # second call-offset is result adjustment 6355 6356 assert(!isa<CXXDestructorDecl>(MD) && 6357 "Use mangleCXXDtor for destructor decls!"); 6358 CXXNameMangler Mangler(*this, Out); 6359 Mangler.getStream() << "_ZT"; 6360 if (!Thunk.Return.isEmpty()) 6361 Mangler.getStream() << 'c'; 6362 6363 // Mangle the 'this' pointer adjustment. 6364 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 6365 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 6366 6367 // Mangle the return pointer adjustment if there is one. 6368 if (!Thunk.Return.isEmpty()) 6369 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 6370 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 6371 6372 Mangler.mangleFunctionEncoding(MD); 6373 } 6374 6375 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 6376 const CXXDestructorDecl *DD, CXXDtorType Type, 6377 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 6378 // <special-name> ::= T <call-offset> <base encoding> 6379 // # base is the nominal target function of thunk 6380 CXXNameMangler Mangler(*this, Out, DD, Type); 6381 Mangler.getStream() << "_ZT"; 6382 6383 // Mangle the 'this' pointer adjustment. 6384 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 6385 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 6386 6387 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type)); 6388 } 6389 6390 /// Returns the mangled name for a guard variable for the passed in VarDecl. 6391 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 6392 raw_ostream &Out) { 6393 // <special-name> ::= GV <object name> # Guard variable for one-time 6394 // # initialization 6395 CXXNameMangler Mangler(*this, Out); 6396 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 6397 // be a bug that is fixed in trunk. 6398 Mangler.getStream() << "_ZGV"; 6399 Mangler.mangleName(D); 6400 } 6401 6402 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 6403 raw_ostream &Out) { 6404 // These symbols are internal in the Itanium ABI, so the names don't matter. 6405 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 6406 // avoid duplicate symbols. 6407 Out << "__cxx_global_var_init"; 6408 } 6409 6410 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 6411 raw_ostream &Out) { 6412 // Prefix the mangling of D with __dtor_. 6413 CXXNameMangler Mangler(*this, Out); 6414 Mangler.getStream() << "__dtor_"; 6415 if (shouldMangleDeclName(D)) 6416 Mangler.mangle(D); 6417 else 6418 Mangler.getStream() << D->getName(); 6419 } 6420 6421 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D, 6422 raw_ostream &Out) { 6423 // Clang generates these internal-linkage functions as part of its 6424 // implementation of the XL ABI. 6425 CXXNameMangler Mangler(*this, Out); 6426 Mangler.getStream() << "__finalize_"; 6427 if (shouldMangleDeclName(D)) 6428 Mangler.mangle(D); 6429 else 6430 Mangler.getStream() << D->getName(); 6431 } 6432 6433 void ItaniumMangleContextImpl::mangleSEHFilterExpression( 6434 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 6435 CXXNameMangler Mangler(*this, Out); 6436 Mangler.getStream() << "__filt_"; 6437 if (shouldMangleDeclName(EnclosingDecl)) 6438 Mangler.mangle(EnclosingDecl); 6439 else 6440 Mangler.getStream() << EnclosingDecl->getName(); 6441 } 6442 6443 void ItaniumMangleContextImpl::mangleSEHFinallyBlock( 6444 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 6445 CXXNameMangler Mangler(*this, Out); 6446 Mangler.getStream() << "__fin_"; 6447 if (shouldMangleDeclName(EnclosingDecl)) 6448 Mangler.mangle(EnclosingDecl); 6449 else 6450 Mangler.getStream() << EnclosingDecl->getName(); 6451 } 6452 6453 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 6454 raw_ostream &Out) { 6455 // <special-name> ::= TH <object name> 6456 CXXNameMangler Mangler(*this, Out); 6457 Mangler.getStream() << "_ZTH"; 6458 Mangler.mangleName(D); 6459 } 6460 6461 void 6462 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 6463 raw_ostream &Out) { 6464 // <special-name> ::= TW <object name> 6465 CXXNameMangler Mangler(*this, Out); 6466 Mangler.getStream() << "_ZTW"; 6467 Mangler.mangleName(D); 6468 } 6469 6470 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 6471 unsigned ManglingNumber, 6472 raw_ostream &Out) { 6473 // We match the GCC mangling here. 6474 // <special-name> ::= GR <object name> 6475 CXXNameMangler Mangler(*this, Out); 6476 Mangler.getStream() << "_ZGR"; 6477 Mangler.mangleName(D); 6478 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 6479 Mangler.mangleSeqID(ManglingNumber - 1); 6480 } 6481 6482 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 6483 raw_ostream &Out) { 6484 // <special-name> ::= TV <type> # virtual table 6485 CXXNameMangler Mangler(*this, Out); 6486 Mangler.getStream() << "_ZTV"; 6487 Mangler.mangleNameOrStandardSubstitution(RD); 6488 } 6489 6490 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 6491 raw_ostream &Out) { 6492 // <special-name> ::= TT <type> # VTT structure 6493 CXXNameMangler Mangler(*this, Out); 6494 Mangler.getStream() << "_ZTT"; 6495 Mangler.mangleNameOrStandardSubstitution(RD); 6496 } 6497 6498 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 6499 int64_t Offset, 6500 const CXXRecordDecl *Type, 6501 raw_ostream &Out) { 6502 // <special-name> ::= TC <type> <offset number> _ <base type> 6503 CXXNameMangler Mangler(*this, Out); 6504 Mangler.getStream() << "_ZTC"; 6505 Mangler.mangleNameOrStandardSubstitution(RD); 6506 Mangler.getStream() << Offset; 6507 Mangler.getStream() << '_'; 6508 Mangler.mangleNameOrStandardSubstitution(Type); 6509 } 6510 6511 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 6512 // <special-name> ::= TI <type> # typeinfo structure 6513 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 6514 CXXNameMangler Mangler(*this, Out); 6515 Mangler.getStream() << "_ZTI"; 6516 Mangler.mangleType(Ty); 6517 } 6518 6519 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 6520 raw_ostream &Out) { 6521 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 6522 CXXNameMangler Mangler(*this, Out); 6523 Mangler.getStream() << "_ZTS"; 6524 Mangler.mangleType(Ty); 6525 } 6526 6527 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 6528 mangleCXXRTTIName(Ty, Out); 6529 } 6530 6531 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 6532 llvm_unreachable("Can't mangle string literals"); 6533 } 6534 6535 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda, 6536 raw_ostream &Out) { 6537 CXXNameMangler Mangler(*this, Out); 6538 Mangler.mangleLambdaSig(Lambda); 6539 } 6540 6541 void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M, 6542 raw_ostream &Out) { 6543 // <special-name> ::= GI <module-name> # module initializer function 6544 CXXNameMangler Mangler(*this, Out); 6545 Mangler.getStream() << "_ZGI"; 6546 Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName()); 6547 if (M->isModulePartition()) { 6548 // The partition needs including, as partitions can have them too. 6549 auto Partition = M->Name.find(':'); 6550 Mangler.mangleModuleNamePrefix( 6551 StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1), 6552 /*IsPartition*/ true); 6553 } 6554 } 6555 6556 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context, 6557 DiagnosticsEngine &Diags, 6558 bool IsAux) { 6559 return new ItaniumMangleContextImpl( 6560 Context, Diags, 6561 [](ASTContext &, const NamedDecl *) -> llvm::Optional<unsigned> { 6562 return llvm::None; 6563 }, 6564 IsAux); 6565 } 6566 6567 ItaniumMangleContext * 6568 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags, 6569 DiscriminatorOverrideTy DiscriminatorOverride, 6570 bool IsAux) { 6571 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride, 6572 IsAux); 6573 } 6574