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