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_IntelOclBicc: 3153 case CC_SpirFunction: 3154 case CC_OpenCLKernel: 3155 case CC_PreserveMost: 3156 case CC_PreserveAll: 3157 // FIXME: we should be mangling all of the above. 3158 return ""; 3159 3160 case CC_X86ThisCall: 3161 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is 3162 // used explicitly. At this point, we don't have that much information in 3163 // the AST, since clang tends to bake the convention into the canonical 3164 // function type. thiscall only rarely used explicitly, so don't mangle it 3165 // for now. 3166 return ""; 3167 3168 case CC_X86StdCall: 3169 return "stdcall"; 3170 case CC_X86FastCall: 3171 return "fastcall"; 3172 case CC_X86_64SysV: 3173 return "sysv_abi"; 3174 case CC_Win64: 3175 return "ms_abi"; 3176 case CC_Swift: 3177 return "swiftcall"; 3178 case CC_SwiftAsync: 3179 return "swiftasynccall"; 3180 } 3181 llvm_unreachable("bad calling convention"); 3182 } 3183 3184 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) { 3185 // Fast path. 3186 if (T->getExtInfo() == FunctionType::ExtInfo()) 3187 return; 3188 3189 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 3190 // This will get more complicated in the future if we mangle other 3191 // things here; but for now, since we mangle ns_returns_retained as 3192 // a qualifier on the result type, we can get away with this: 3193 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC()); 3194 if (!CCQualifier.empty()) 3195 mangleVendorQualifier(CCQualifier); 3196 3197 // FIXME: regparm 3198 // FIXME: noreturn 3199 } 3200 3201 void 3202 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { 3203 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 3204 3205 // Note that these are *not* substitution candidates. Demanglers might 3206 // have trouble with this if the parameter type is fully substituted. 3207 3208 switch (PI.getABI()) { 3209 case ParameterABI::Ordinary: 3210 break; 3211 3212 // All of these start with "swift", so they come before "ns_consumed". 3213 case ParameterABI::SwiftContext: 3214 case ParameterABI::SwiftAsyncContext: 3215 case ParameterABI::SwiftErrorResult: 3216 case ParameterABI::SwiftIndirectResult: 3217 mangleVendorQualifier(getParameterABISpelling(PI.getABI())); 3218 break; 3219 } 3220 3221 if (PI.isConsumed()) 3222 mangleVendorQualifier("ns_consumed"); 3223 3224 if (PI.isNoEscape()) 3225 mangleVendorQualifier("noescape"); 3226 } 3227 3228 // <type> ::= <function-type> 3229 // <function-type> ::= [<CV-qualifiers>] F [Y] 3230 // <bare-function-type> [<ref-qualifier>] E 3231 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 3232 mangleExtFunctionInfo(T); 3233 3234 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 3235 // e.g. "const" in "int (A::*)() const". 3236 mangleQualifiers(T->getMethodQuals()); 3237 3238 // Mangle instantiation-dependent exception-specification, if present, 3239 // per cxx-abi-dev proposal on 2016-10-11. 3240 if (T->hasInstantiationDependentExceptionSpec()) { 3241 if (isComputedNoexcept(T->getExceptionSpecType())) { 3242 Out << "DO"; 3243 mangleExpression(T->getNoexceptExpr()); 3244 Out << "E"; 3245 } else { 3246 assert(T->getExceptionSpecType() == EST_Dynamic); 3247 Out << "Dw"; 3248 for (auto ExceptTy : T->exceptions()) 3249 mangleType(ExceptTy); 3250 Out << "E"; 3251 } 3252 } else if (T->isNothrow()) { 3253 Out << "Do"; 3254 } 3255 3256 Out << 'F'; 3257 3258 // FIXME: We don't have enough information in the AST to produce the 'Y' 3259 // encoding for extern "C" function types. 3260 mangleBareFunctionType(T, /*MangleReturnType=*/true); 3261 3262 // Mangle the ref-qualifier, if present. 3263 mangleRefQualifier(T->getRefQualifier()); 3264 3265 Out << 'E'; 3266 } 3267 3268 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 3269 // Function types without prototypes can arise when mangling a function type 3270 // within an overloadable function in C. We mangle these as the absence of any 3271 // parameter types (not even an empty parameter list). 3272 Out << 'F'; 3273 3274 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3275 3276 FunctionTypeDepth.enterResultType(); 3277 mangleType(T->getReturnType()); 3278 FunctionTypeDepth.leaveResultType(); 3279 3280 FunctionTypeDepth.pop(saved); 3281 Out << 'E'; 3282 } 3283 3284 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto, 3285 bool MangleReturnType, 3286 const FunctionDecl *FD) { 3287 // Record that we're in a function type. See mangleFunctionParam 3288 // for details on what we're trying to achieve here. 3289 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3290 3291 // <bare-function-type> ::= <signature type>+ 3292 if (MangleReturnType) { 3293 FunctionTypeDepth.enterResultType(); 3294 3295 // Mangle ns_returns_retained as an order-sensitive qualifier here. 3296 if (Proto->getExtInfo().getProducesResult() && FD == nullptr) 3297 mangleVendorQualifier("ns_returns_retained"); 3298 3299 // Mangle the return type without any direct ARC ownership qualifiers. 3300 QualType ReturnTy = Proto->getReturnType(); 3301 if (ReturnTy.getObjCLifetime()) { 3302 auto SplitReturnTy = ReturnTy.split(); 3303 SplitReturnTy.Quals.removeObjCLifetime(); 3304 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy); 3305 } 3306 mangleType(ReturnTy); 3307 3308 FunctionTypeDepth.leaveResultType(); 3309 } 3310 3311 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 3312 // <builtin-type> ::= v # void 3313 Out << 'v'; 3314 3315 FunctionTypeDepth.pop(saved); 3316 return; 3317 } 3318 3319 assert(!FD || FD->getNumParams() == Proto->getNumParams()); 3320 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 3321 // Mangle extended parameter info as order-sensitive qualifiers here. 3322 if (Proto->hasExtParameterInfos() && FD == nullptr) { 3323 mangleExtParameterInfo(Proto->getExtParameterInfo(I)); 3324 } 3325 3326 // Mangle the type. 3327 QualType ParamTy = Proto->getParamType(I); 3328 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy)); 3329 3330 if (FD) { 3331 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) { 3332 // Attr can only take 1 character, so we can hardcode the length below. 3333 assert(Attr->getType() <= 9 && Attr->getType() >= 0); 3334 if (Attr->isDynamic()) 3335 Out << "U25pass_dynamic_object_size" << Attr->getType(); 3336 else 3337 Out << "U17pass_object_size" << Attr->getType(); 3338 } 3339 } 3340 } 3341 3342 FunctionTypeDepth.pop(saved); 3343 3344 // <builtin-type> ::= z # ellipsis 3345 if (Proto->isVariadic()) 3346 Out << 'z'; 3347 } 3348 3349 // <type> ::= <class-enum-type> 3350 // <class-enum-type> ::= <name> 3351 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 3352 mangleName(T->getDecl()); 3353 } 3354 3355 // <type> ::= <class-enum-type> 3356 // <class-enum-type> ::= <name> 3357 void CXXNameMangler::mangleType(const EnumType *T) { 3358 mangleType(static_cast<const TagType*>(T)); 3359 } 3360 void CXXNameMangler::mangleType(const RecordType *T) { 3361 mangleType(static_cast<const TagType*>(T)); 3362 } 3363 void CXXNameMangler::mangleType(const TagType *T) { 3364 mangleName(T->getDecl()); 3365 } 3366 3367 // <type> ::= <array-type> 3368 // <array-type> ::= A <positive dimension number> _ <element type> 3369 // ::= A [<dimension expression>] _ <element type> 3370 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 3371 Out << 'A' << T->getSize() << '_'; 3372 mangleType(T->getElementType()); 3373 } 3374 void CXXNameMangler::mangleType(const VariableArrayType *T) { 3375 Out << 'A'; 3376 // decayed vla types (size 0) will just be skipped. 3377 if (T->getSizeExpr()) 3378 mangleExpression(T->getSizeExpr()); 3379 Out << '_'; 3380 mangleType(T->getElementType()); 3381 } 3382 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 3383 Out << 'A'; 3384 // A DependentSizedArrayType might not have size expression as below 3385 // 3386 // template<int ...N> int arr[] = {N...}; 3387 if (T->getSizeExpr()) 3388 mangleExpression(T->getSizeExpr()); 3389 Out << '_'; 3390 mangleType(T->getElementType()); 3391 } 3392 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 3393 Out << "A_"; 3394 mangleType(T->getElementType()); 3395 } 3396 3397 // <type> ::= <pointer-to-member-type> 3398 // <pointer-to-member-type> ::= M <class type> <member type> 3399 void CXXNameMangler::mangleType(const MemberPointerType *T) { 3400 Out << 'M'; 3401 mangleType(QualType(T->getClass(), 0)); 3402 QualType PointeeType = T->getPointeeType(); 3403 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 3404 mangleType(FPT); 3405 3406 // Itanium C++ ABI 5.1.8: 3407 // 3408 // The type of a non-static member function is considered to be different, 3409 // for the purposes of substitution, from the type of a namespace-scope or 3410 // static member function whose type appears similar. The types of two 3411 // non-static member functions are considered to be different, for the 3412 // purposes of substitution, if the functions are members of different 3413 // classes. In other words, for the purposes of substitution, the class of 3414 // which the function is a member is considered part of the type of 3415 // function. 3416 3417 // Given that we already substitute member function pointers as a 3418 // whole, the net effect of this rule is just to unconditionally 3419 // suppress substitution on the function type in a member pointer. 3420 // We increment the SeqID here to emulate adding an entry to the 3421 // substitution table. 3422 ++SeqID; 3423 } else 3424 mangleType(PointeeType); 3425 } 3426 3427 // <type> ::= <template-param> 3428 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 3429 mangleTemplateParameter(T->getDepth(), T->getIndex()); 3430 } 3431 3432 // <type> ::= <template-param> 3433 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 3434 // FIXME: not clear how to mangle this! 3435 // template <class T...> class A { 3436 // template <class U...> void foo(T(*)(U) x...); 3437 // }; 3438 Out << "_SUBSTPACK_"; 3439 } 3440 3441 // <type> ::= P <type> # pointer-to 3442 void CXXNameMangler::mangleType(const PointerType *T) { 3443 Out << 'P'; 3444 mangleType(T->getPointeeType()); 3445 } 3446 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 3447 Out << 'P'; 3448 mangleType(T->getPointeeType()); 3449 } 3450 3451 // <type> ::= R <type> # reference-to 3452 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 3453 Out << 'R'; 3454 mangleType(T->getPointeeType()); 3455 } 3456 3457 // <type> ::= O <type> # rvalue reference-to (C++0x) 3458 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 3459 Out << 'O'; 3460 mangleType(T->getPointeeType()); 3461 } 3462 3463 // <type> ::= C <type> # complex pair (C 2000) 3464 void CXXNameMangler::mangleType(const ComplexType *T) { 3465 Out << 'C'; 3466 mangleType(T->getElementType()); 3467 } 3468 3469 // ARM's ABI for Neon vector types specifies that they should be mangled as 3470 // if they are structs (to match ARM's initial implementation). The 3471 // vector type must be one of the special types predefined by ARM. 3472 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 3473 QualType EltType = T->getElementType(); 3474 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3475 const char *EltName = nullptr; 3476 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3477 switch (cast<BuiltinType>(EltType)->getKind()) { 3478 case BuiltinType::SChar: 3479 case BuiltinType::UChar: 3480 EltName = "poly8_t"; 3481 break; 3482 case BuiltinType::Short: 3483 case BuiltinType::UShort: 3484 EltName = "poly16_t"; 3485 break; 3486 case BuiltinType::LongLong: 3487 case BuiltinType::ULongLong: 3488 EltName = "poly64_t"; 3489 break; 3490 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 3491 } 3492 } else { 3493 switch (cast<BuiltinType>(EltType)->getKind()) { 3494 case BuiltinType::SChar: EltName = "int8_t"; break; 3495 case BuiltinType::UChar: EltName = "uint8_t"; break; 3496 case BuiltinType::Short: EltName = "int16_t"; break; 3497 case BuiltinType::UShort: EltName = "uint16_t"; break; 3498 case BuiltinType::Int: EltName = "int32_t"; break; 3499 case BuiltinType::UInt: EltName = "uint32_t"; break; 3500 case BuiltinType::LongLong: EltName = "int64_t"; break; 3501 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 3502 case BuiltinType::Double: EltName = "float64_t"; break; 3503 case BuiltinType::Float: EltName = "float32_t"; break; 3504 case BuiltinType::Half: EltName = "float16_t"; break; 3505 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break; 3506 default: 3507 llvm_unreachable("unexpected Neon vector element type"); 3508 } 3509 } 3510 const char *BaseName = nullptr; 3511 unsigned BitSize = (T->getNumElements() * 3512 getASTContext().getTypeSize(EltType)); 3513 if (BitSize == 64) 3514 BaseName = "__simd64_"; 3515 else { 3516 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 3517 BaseName = "__simd128_"; 3518 } 3519 Out << strlen(BaseName) + strlen(EltName); 3520 Out << BaseName << EltName; 3521 } 3522 3523 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) { 3524 DiagnosticsEngine &Diags = Context.getDiags(); 3525 unsigned DiagID = Diags.getCustomDiagID( 3526 DiagnosticsEngine::Error, 3527 "cannot mangle this dependent neon vector type yet"); 3528 Diags.Report(T->getAttributeLoc(), DiagID); 3529 } 3530 3531 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 3532 switch (EltType->getKind()) { 3533 case BuiltinType::SChar: 3534 return "Int8"; 3535 case BuiltinType::Short: 3536 return "Int16"; 3537 case BuiltinType::Int: 3538 return "Int32"; 3539 case BuiltinType::Long: 3540 case BuiltinType::LongLong: 3541 return "Int64"; 3542 case BuiltinType::UChar: 3543 return "Uint8"; 3544 case BuiltinType::UShort: 3545 return "Uint16"; 3546 case BuiltinType::UInt: 3547 return "Uint32"; 3548 case BuiltinType::ULong: 3549 case BuiltinType::ULongLong: 3550 return "Uint64"; 3551 case BuiltinType::Half: 3552 return "Float16"; 3553 case BuiltinType::Float: 3554 return "Float32"; 3555 case BuiltinType::Double: 3556 return "Float64"; 3557 case BuiltinType::BFloat16: 3558 return "Bfloat16"; 3559 default: 3560 llvm_unreachable("Unexpected vector element base type"); 3561 } 3562 } 3563 3564 // AArch64's ABI for Neon vector types specifies that they should be mangled as 3565 // the equivalent internal name. The vector type must be one of the special 3566 // types predefined by ARM. 3567 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 3568 QualType EltType = T->getElementType(); 3569 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3570 unsigned BitSize = 3571 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 3572 (void)BitSize; // Silence warning. 3573 3574 assert((BitSize == 64 || BitSize == 128) && 3575 "Neon vector type not 64 or 128 bits"); 3576 3577 StringRef EltName; 3578 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3579 switch (cast<BuiltinType>(EltType)->getKind()) { 3580 case BuiltinType::UChar: 3581 EltName = "Poly8"; 3582 break; 3583 case BuiltinType::UShort: 3584 EltName = "Poly16"; 3585 break; 3586 case BuiltinType::ULong: 3587 case BuiltinType::ULongLong: 3588 EltName = "Poly64"; 3589 break; 3590 default: 3591 llvm_unreachable("unexpected Neon polynomial vector element type"); 3592 } 3593 } else 3594 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 3595 3596 std::string TypeName = 3597 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str(); 3598 Out << TypeName.length() << TypeName; 3599 } 3600 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) { 3601 DiagnosticsEngine &Diags = Context.getDiags(); 3602 unsigned DiagID = Diags.getCustomDiagID( 3603 DiagnosticsEngine::Error, 3604 "cannot mangle this dependent neon vector type yet"); 3605 Diags.Report(T->getAttributeLoc(), DiagID); 3606 } 3607 3608 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types 3609 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64 3610 // type as the sizeless variants. 3611 // 3612 // The mangling scheme for VLS types is implemented as a "pseudo" template: 3613 // 3614 // '__SVE_VLS<<type>, <vector length>>' 3615 // 3616 // Combining the existing SVE type and a specific vector length (in bits). 3617 // For example: 3618 // 3619 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512))); 3620 // 3621 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as: 3622 // 3623 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE" 3624 // 3625 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE 3626 // 3627 // The latest ACLE specification (00bet5) does not contain details of this 3628 // mangling scheme, it will be specified in the next revision. The mangling 3629 // scheme is otherwise defined in the appendices to the Procedure Call Standard 3630 // for the Arm Architecture, see 3631 // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling 3632 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) { 3633 assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3634 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && 3635 "expected fixed-length SVE vector!"); 3636 3637 QualType EltType = T->getElementType(); 3638 assert(EltType->isBuiltinType() && 3639 "expected builtin type for fixed-length SVE vector!"); 3640 3641 StringRef TypeName; 3642 switch (cast<BuiltinType>(EltType)->getKind()) { 3643 case BuiltinType::SChar: 3644 TypeName = "__SVInt8_t"; 3645 break; 3646 case BuiltinType::UChar: { 3647 if (T->getVectorKind() == VectorType::SveFixedLengthDataVector) 3648 TypeName = "__SVUint8_t"; 3649 else 3650 TypeName = "__SVBool_t"; 3651 break; 3652 } 3653 case BuiltinType::Short: 3654 TypeName = "__SVInt16_t"; 3655 break; 3656 case BuiltinType::UShort: 3657 TypeName = "__SVUint16_t"; 3658 break; 3659 case BuiltinType::Int: 3660 TypeName = "__SVInt32_t"; 3661 break; 3662 case BuiltinType::UInt: 3663 TypeName = "__SVUint32_t"; 3664 break; 3665 case BuiltinType::Long: 3666 TypeName = "__SVInt64_t"; 3667 break; 3668 case BuiltinType::ULong: 3669 TypeName = "__SVUint64_t"; 3670 break; 3671 case BuiltinType::Half: 3672 TypeName = "__SVFloat16_t"; 3673 break; 3674 case BuiltinType::Float: 3675 TypeName = "__SVFloat32_t"; 3676 break; 3677 case BuiltinType::Double: 3678 TypeName = "__SVFloat64_t"; 3679 break; 3680 case BuiltinType::BFloat16: 3681 TypeName = "__SVBfloat16_t"; 3682 break; 3683 default: 3684 llvm_unreachable("unexpected element type for fixed-length SVE vector!"); 3685 } 3686 3687 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width; 3688 3689 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 3690 VecSizeInBits *= 8; 3691 3692 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj" 3693 << VecSizeInBits << "EE"; 3694 } 3695 3696 void CXXNameMangler::mangleAArch64FixedSveVectorType( 3697 const DependentVectorType *T) { 3698 DiagnosticsEngine &Diags = Context.getDiags(); 3699 unsigned DiagID = Diags.getCustomDiagID( 3700 DiagnosticsEngine::Error, 3701 "cannot mangle this dependent fixed-length SVE vector type yet"); 3702 Diags.Report(T->getAttributeLoc(), DiagID); 3703 } 3704 3705 // GNU extension: vector types 3706 // <type> ::= <vector-type> 3707 // <vector-type> ::= Dv <positive dimension number> _ 3708 // <extended element type> 3709 // ::= Dv [<dimension expression>] _ <element type> 3710 // <extended element type> ::= <element type> 3711 // ::= p # AltiVec vector pixel 3712 // ::= b # Altivec vector bool 3713 void CXXNameMangler::mangleType(const VectorType *T) { 3714 if ((T->getVectorKind() == VectorType::NeonVector || 3715 T->getVectorKind() == VectorType::NeonPolyVector)) { 3716 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3717 llvm::Triple::ArchType Arch = 3718 getASTContext().getTargetInfo().getTriple().getArch(); 3719 if ((Arch == llvm::Triple::aarch64 || 3720 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 3721 mangleAArch64NeonVectorType(T); 3722 else 3723 mangleNeonVectorType(T); 3724 return; 3725 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3726 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 3727 mangleAArch64FixedSveVectorType(T); 3728 return; 3729 } 3730 Out << "Dv" << T->getNumElements() << '_'; 3731 if (T->getVectorKind() == VectorType::AltiVecPixel) 3732 Out << 'p'; 3733 else if (T->getVectorKind() == VectorType::AltiVecBool) 3734 Out << 'b'; 3735 else 3736 mangleType(T->getElementType()); 3737 } 3738 3739 void CXXNameMangler::mangleType(const DependentVectorType *T) { 3740 if ((T->getVectorKind() == VectorType::NeonVector || 3741 T->getVectorKind() == VectorType::NeonPolyVector)) { 3742 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3743 llvm::Triple::ArchType Arch = 3744 getASTContext().getTargetInfo().getTriple().getArch(); 3745 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) && 3746 !Target.isOSDarwin()) 3747 mangleAArch64NeonVectorType(T); 3748 else 3749 mangleNeonVectorType(T); 3750 return; 3751 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3752 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 3753 mangleAArch64FixedSveVectorType(T); 3754 return; 3755 } 3756 3757 Out << "Dv"; 3758 mangleExpression(T->getSizeExpr()); 3759 Out << '_'; 3760 if (T->getVectorKind() == VectorType::AltiVecPixel) 3761 Out << 'p'; 3762 else if (T->getVectorKind() == VectorType::AltiVecBool) 3763 Out << 'b'; 3764 else 3765 mangleType(T->getElementType()); 3766 } 3767 3768 void CXXNameMangler::mangleType(const ExtVectorType *T) { 3769 mangleType(static_cast<const VectorType*>(T)); 3770 } 3771 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 3772 Out << "Dv"; 3773 mangleExpression(T->getSizeExpr()); 3774 Out << '_'; 3775 mangleType(T->getElementType()); 3776 } 3777 3778 void CXXNameMangler::mangleType(const ConstantMatrixType *T) { 3779 // Mangle matrix types as a vendor extended type: 3780 // u<Len>matrix_typeI<Rows><Columns><element type>E 3781 3782 StringRef VendorQualifier = "matrix_type"; 3783 Out << "u" << VendorQualifier.size() << VendorQualifier; 3784 3785 Out << "I"; 3786 auto &ASTCtx = getASTContext(); 3787 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType()); 3788 llvm::APSInt Rows(BitWidth); 3789 Rows = T->getNumRows(); 3790 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows); 3791 llvm::APSInt Columns(BitWidth); 3792 Columns = T->getNumColumns(); 3793 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns); 3794 mangleType(T->getElementType()); 3795 Out << "E"; 3796 } 3797 3798 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) { 3799 // Mangle matrix types as a vendor extended type: 3800 // u<Len>matrix_typeI<row expr><column expr><element type>E 3801 StringRef VendorQualifier = "matrix_type"; 3802 Out << "u" << VendorQualifier.size() << VendorQualifier; 3803 3804 Out << "I"; 3805 mangleTemplateArgExpr(T->getRowExpr()); 3806 mangleTemplateArgExpr(T->getColumnExpr()); 3807 mangleType(T->getElementType()); 3808 Out << "E"; 3809 } 3810 3811 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) { 3812 SplitQualType split = T->getPointeeType().split(); 3813 mangleQualifiers(split.Quals, T); 3814 mangleType(QualType(split.Ty, 0)); 3815 } 3816 3817 void CXXNameMangler::mangleType(const PackExpansionType *T) { 3818 // <type> ::= Dp <type> # pack expansion (C++0x) 3819 Out << "Dp"; 3820 mangleType(T->getPattern()); 3821 } 3822 3823 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 3824 mangleSourceName(T->getDecl()->getIdentifier()); 3825 } 3826 3827 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 3828 // Treat __kindof as a vendor extended type qualifier. 3829 if (T->isKindOfType()) 3830 Out << "U8__kindof"; 3831 3832 if (!T->qual_empty()) { 3833 // Mangle protocol qualifiers. 3834 SmallString<64> QualStr; 3835 llvm::raw_svector_ostream QualOS(QualStr); 3836 QualOS << "objcproto"; 3837 for (const auto *I : T->quals()) { 3838 StringRef name = I->getName(); 3839 QualOS << name.size() << name; 3840 } 3841 Out << 'U' << QualStr.size() << QualStr; 3842 } 3843 3844 mangleType(T->getBaseType()); 3845 3846 if (T->isSpecialized()) { 3847 // Mangle type arguments as I <type>+ E 3848 Out << 'I'; 3849 for (auto typeArg : T->getTypeArgs()) 3850 mangleType(typeArg); 3851 Out << 'E'; 3852 } 3853 } 3854 3855 void CXXNameMangler::mangleType(const BlockPointerType *T) { 3856 Out << "U13block_pointer"; 3857 mangleType(T->getPointeeType()); 3858 } 3859 3860 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 3861 // Mangle injected class name types as if the user had written the 3862 // specialization out fully. It may not actually be possible to see 3863 // this mangling, though. 3864 mangleType(T->getInjectedSpecializationType()); 3865 } 3866 3867 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 3868 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 3869 mangleTemplateName(TD, T->getArgs(), T->getNumArgs()); 3870 } else { 3871 if (mangleSubstitution(QualType(T, 0))) 3872 return; 3873 3874 mangleTemplatePrefix(T->getTemplateName()); 3875 3876 // FIXME: GCC does not appear to mangle the template arguments when 3877 // the template in question is a dependent template name. Should we 3878 // emulate that badness? 3879 mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs()); 3880 addSubstitution(QualType(T, 0)); 3881 } 3882 } 3883 3884 void CXXNameMangler::mangleType(const DependentNameType *T) { 3885 // Proposal by cxx-abi-dev, 2014-03-26 3886 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 3887 // # dependent elaborated type specifier using 3888 // # 'typename' 3889 // ::= Ts <name> # dependent elaborated type specifier using 3890 // # 'struct' or 'class' 3891 // ::= Tu <name> # dependent elaborated type specifier using 3892 // # 'union' 3893 // ::= Te <name> # dependent elaborated type specifier using 3894 // # 'enum' 3895 switch (T->getKeyword()) { 3896 case ETK_None: 3897 case ETK_Typename: 3898 break; 3899 case ETK_Struct: 3900 case ETK_Class: 3901 case ETK_Interface: 3902 Out << "Ts"; 3903 break; 3904 case ETK_Union: 3905 Out << "Tu"; 3906 break; 3907 case ETK_Enum: 3908 Out << "Te"; 3909 break; 3910 } 3911 // Typename types are always nested 3912 Out << 'N'; 3913 manglePrefix(T->getQualifier()); 3914 mangleSourceName(T->getIdentifier()); 3915 Out << 'E'; 3916 } 3917 3918 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 3919 // Dependently-scoped template types are nested if they have a prefix. 3920 Out << 'N'; 3921 3922 // TODO: avoid making this TemplateName. 3923 TemplateName Prefix = 3924 getASTContext().getDependentTemplateName(T->getQualifier(), 3925 T->getIdentifier()); 3926 mangleTemplatePrefix(Prefix); 3927 3928 // FIXME: GCC does not appear to mangle the template arguments when 3929 // the template in question is a dependent template name. Should we 3930 // emulate that badness? 3931 mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs()); 3932 Out << 'E'; 3933 } 3934 3935 void CXXNameMangler::mangleType(const TypeOfType *T) { 3936 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3937 // "extension with parameters" mangling. 3938 Out << "u6typeof"; 3939 } 3940 3941 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 3942 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3943 // "extension with parameters" mangling. 3944 Out << "u6typeof"; 3945 } 3946 3947 void CXXNameMangler::mangleType(const DecltypeType *T) { 3948 Expr *E = T->getUnderlyingExpr(); 3949 3950 // type ::= Dt <expression> E # decltype of an id-expression 3951 // # or class member access 3952 // ::= DT <expression> E # decltype of an expression 3953 3954 // This purports to be an exhaustive list of id-expressions and 3955 // class member accesses. Note that we do not ignore parentheses; 3956 // parentheses change the semantics of decltype for these 3957 // expressions (and cause the mangler to use the other form). 3958 if (isa<DeclRefExpr>(E) || 3959 isa<MemberExpr>(E) || 3960 isa<UnresolvedLookupExpr>(E) || 3961 isa<DependentScopeDeclRefExpr>(E) || 3962 isa<CXXDependentScopeMemberExpr>(E) || 3963 isa<UnresolvedMemberExpr>(E)) 3964 Out << "Dt"; 3965 else 3966 Out << "DT"; 3967 mangleExpression(E); 3968 Out << 'E'; 3969 } 3970 3971 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 3972 // If this is dependent, we need to record that. If not, we simply 3973 // mangle it as the underlying type since they are equivalent. 3974 if (T->isDependentType()) { 3975 Out << 'U'; 3976 3977 switch (T->getUTTKind()) { 3978 case UnaryTransformType::EnumUnderlyingType: 3979 Out << "3eut"; 3980 break; 3981 } 3982 } 3983 3984 mangleType(T->getBaseType()); 3985 } 3986 3987 void CXXNameMangler::mangleType(const AutoType *T) { 3988 assert(T->getDeducedType().isNull() && 3989 "Deduced AutoType shouldn't be handled here!"); 3990 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType && 3991 "shouldn't need to mangle __auto_type!"); 3992 // <builtin-type> ::= Da # auto 3993 // ::= Dc # decltype(auto) 3994 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 3995 } 3996 3997 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) { 3998 QualType Deduced = T->getDeducedType(); 3999 if (!Deduced.isNull()) 4000 return mangleType(Deduced); 4001 4002 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl(); 4003 assert(TD && "shouldn't form deduced TST unless we know we have a template"); 4004 4005 if (mangleSubstitution(TD)) 4006 return; 4007 4008 mangleName(GlobalDecl(TD)); 4009 addSubstitution(TD); 4010 } 4011 4012 void CXXNameMangler::mangleType(const AtomicType *T) { 4013 // <type> ::= U <source-name> <type> # vendor extended type qualifier 4014 // (Until there's a standardized mangling...) 4015 Out << "U7_Atomic"; 4016 mangleType(T->getValueType()); 4017 } 4018 4019 void CXXNameMangler::mangleType(const PipeType *T) { 4020 // Pipe type mangling rules are described in SPIR 2.0 specification 4021 // A.1 Data types and A.3 Summary of changes 4022 // <type> ::= 8ocl_pipe 4023 Out << "8ocl_pipe"; 4024 } 4025 4026 void CXXNameMangler::mangleType(const BitIntType *T) { 4027 // 5.1.5.2 Builtin types 4028 // <type> ::= DB <number | instantiation-dependent expression> _ 4029 // ::= DU <number | instantiation-dependent expression> _ 4030 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_"; 4031 } 4032 4033 void CXXNameMangler::mangleType(const DependentBitIntType *T) { 4034 // 5.1.5.2 Builtin types 4035 // <type> ::= DB <number | instantiation-dependent expression> _ 4036 // ::= DU <number | instantiation-dependent expression> _ 4037 Out << "D" << (T->isUnsigned() ? "U" : "B"); 4038 mangleExpression(T->getNumBitsExpr()); 4039 Out << "_"; 4040 } 4041 4042 void CXXNameMangler::mangleIntegerLiteral(QualType T, 4043 const llvm::APSInt &Value) { 4044 // <expr-primary> ::= L <type> <value number> E # integer literal 4045 Out << 'L'; 4046 4047 mangleType(T); 4048 if (T->isBooleanType()) { 4049 // Boolean values are encoded as 0/1. 4050 Out << (Value.getBoolValue() ? '1' : '0'); 4051 } else { 4052 mangleNumber(Value); 4053 } 4054 Out << 'E'; 4055 4056 } 4057 4058 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) { 4059 // Ignore member expressions involving anonymous unions. 4060 while (const auto *RT = Base->getType()->getAs<RecordType>()) { 4061 if (!RT->getDecl()->isAnonymousStructOrUnion()) 4062 break; 4063 const auto *ME = dyn_cast<MemberExpr>(Base); 4064 if (!ME) 4065 break; 4066 Base = ME->getBase(); 4067 IsArrow = ME->isArrow(); 4068 } 4069 4070 if (Base->isImplicitCXXThis()) { 4071 // Note: GCC mangles member expressions to the implicit 'this' as 4072 // *this., whereas we represent them as this->. The Itanium C++ ABI 4073 // does not specify anything here, so we follow GCC. 4074 Out << "dtdefpT"; 4075 } else { 4076 Out << (IsArrow ? "pt" : "dt"); 4077 mangleExpression(Base); 4078 } 4079 } 4080 4081 /// Mangles a member expression. 4082 void CXXNameMangler::mangleMemberExpr(const Expr *base, 4083 bool isArrow, 4084 NestedNameSpecifier *qualifier, 4085 NamedDecl *firstQualifierLookup, 4086 DeclarationName member, 4087 const TemplateArgumentLoc *TemplateArgs, 4088 unsigned NumTemplateArgs, 4089 unsigned arity) { 4090 // <expression> ::= dt <expression> <unresolved-name> 4091 // ::= pt <expression> <unresolved-name> 4092 if (base) 4093 mangleMemberExprBase(base, isArrow); 4094 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity); 4095 } 4096 4097 /// Look at the callee of the given call expression and determine if 4098 /// it's a parenthesized id-expression which would have triggered ADL 4099 /// otherwise. 4100 static bool isParenthesizedADLCallee(const CallExpr *call) { 4101 const Expr *callee = call->getCallee(); 4102 const Expr *fn = callee->IgnoreParens(); 4103 4104 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 4105 // too, but for those to appear in the callee, it would have to be 4106 // parenthesized. 4107 if (callee == fn) return false; 4108 4109 // Must be an unresolved lookup. 4110 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 4111 if (!lookup) return false; 4112 4113 assert(!lookup->requiresADL()); 4114 4115 // Must be an unqualified lookup. 4116 if (lookup->getQualifier()) return false; 4117 4118 // Must not have found a class member. Note that if one is a class 4119 // member, they're all class members. 4120 if (lookup->getNumDecls() > 0 && 4121 (*lookup->decls_begin())->isCXXClassMember()) 4122 return false; 4123 4124 // Otherwise, ADL would have been triggered. 4125 return true; 4126 } 4127 4128 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 4129 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 4130 Out << CastEncoding; 4131 mangleType(ECE->getType()); 4132 mangleExpression(ECE->getSubExpr()); 4133 } 4134 4135 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) { 4136 if (auto *Syntactic = InitList->getSyntacticForm()) 4137 InitList = Syntactic; 4138 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 4139 mangleExpression(InitList->getInit(i)); 4140 } 4141 4142 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity, 4143 bool AsTemplateArg) { 4144 // <expression> ::= <unary operator-name> <expression> 4145 // ::= <binary operator-name> <expression> <expression> 4146 // ::= <trinary operator-name> <expression> <expression> <expression> 4147 // ::= cv <type> expression # conversion with one argument 4148 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 4149 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 4150 // ::= sc <type> <expression> # static_cast<type> (expression) 4151 // ::= cc <type> <expression> # const_cast<type> (expression) 4152 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 4153 // ::= st <type> # sizeof (a type) 4154 // ::= at <type> # alignof (a type) 4155 // ::= <template-param> 4156 // ::= <function-param> 4157 // ::= fpT # 'this' expression (part of <function-param>) 4158 // ::= sr <type> <unqualified-name> # dependent name 4159 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 4160 // ::= ds <expression> <expression> # expr.*expr 4161 // ::= sZ <template-param> # size of a parameter pack 4162 // ::= sZ <function-param> # size of a function parameter pack 4163 // ::= u <source-name> <template-arg>* E # vendor extended expression 4164 // ::= <expr-primary> 4165 // <expr-primary> ::= L <type> <value number> E # integer literal 4166 // ::= L <type> <value float> E # floating literal 4167 // ::= L <type> <string type> E # string literal 4168 // ::= L <nullptr type> E # nullptr literal "LDnE" 4169 // ::= L <pointer type> 0 E # null pointer template argument 4170 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang 4171 // ::= L <mangled-name> E # external name 4172 QualType ImplicitlyConvertedToType; 4173 4174 // A top-level expression that's not <expr-primary> needs to be wrapped in 4175 // X...E in a template arg. 4176 bool IsPrimaryExpr = true; 4177 auto NotPrimaryExpr = [&] { 4178 if (AsTemplateArg && IsPrimaryExpr) 4179 Out << 'X'; 4180 IsPrimaryExpr = false; 4181 }; 4182 4183 auto MangleDeclRefExpr = [&](const NamedDecl *D) { 4184 switch (D->getKind()) { 4185 default: 4186 // <expr-primary> ::= L <mangled-name> E # external name 4187 Out << 'L'; 4188 mangle(D); 4189 Out << 'E'; 4190 break; 4191 4192 case Decl::ParmVar: 4193 NotPrimaryExpr(); 4194 mangleFunctionParam(cast<ParmVarDecl>(D)); 4195 break; 4196 4197 case Decl::EnumConstant: { 4198 // <expr-primary> 4199 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 4200 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 4201 break; 4202 } 4203 4204 case Decl::NonTypeTemplateParm: 4205 NotPrimaryExpr(); 4206 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 4207 mangleTemplateParameter(PD->getDepth(), PD->getIndex()); 4208 break; 4209 } 4210 }; 4211 4212 // 'goto recurse' is used when handling a simple "unwrapping" node which 4213 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need 4214 // to be preserved. 4215 recurse: 4216 switch (E->getStmtClass()) { 4217 case Expr::NoStmtClass: 4218 #define ABSTRACT_STMT(Type) 4219 #define EXPR(Type, Base) 4220 #define STMT(Type, Base) \ 4221 case Expr::Type##Class: 4222 #include "clang/AST/StmtNodes.inc" 4223 // fallthrough 4224 4225 // These all can only appear in local or variable-initialization 4226 // contexts and so should never appear in a mangling. 4227 case Expr::AddrLabelExprClass: 4228 case Expr::DesignatedInitUpdateExprClass: 4229 case Expr::ImplicitValueInitExprClass: 4230 case Expr::ArrayInitLoopExprClass: 4231 case Expr::ArrayInitIndexExprClass: 4232 case Expr::NoInitExprClass: 4233 case Expr::ParenListExprClass: 4234 case Expr::MSPropertyRefExprClass: 4235 case Expr::MSPropertySubscriptExprClass: 4236 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 4237 case Expr::RecoveryExprClass: 4238 case Expr::OMPArraySectionExprClass: 4239 case Expr::OMPArrayShapingExprClass: 4240 case Expr::OMPIteratorExprClass: 4241 case Expr::CXXInheritedCtorInitExprClass: 4242 llvm_unreachable("unexpected statement kind"); 4243 4244 case Expr::ConstantExprClass: 4245 E = cast<ConstantExpr>(E)->getSubExpr(); 4246 goto recurse; 4247 4248 // FIXME: invent manglings for all these. 4249 case Expr::BlockExprClass: 4250 case Expr::ChooseExprClass: 4251 case Expr::CompoundLiteralExprClass: 4252 case Expr::ExtVectorElementExprClass: 4253 case Expr::GenericSelectionExprClass: 4254 case Expr::ObjCEncodeExprClass: 4255 case Expr::ObjCIsaExprClass: 4256 case Expr::ObjCIvarRefExprClass: 4257 case Expr::ObjCMessageExprClass: 4258 case Expr::ObjCPropertyRefExprClass: 4259 case Expr::ObjCProtocolExprClass: 4260 case Expr::ObjCSelectorExprClass: 4261 case Expr::ObjCStringLiteralClass: 4262 case Expr::ObjCBoxedExprClass: 4263 case Expr::ObjCArrayLiteralClass: 4264 case Expr::ObjCDictionaryLiteralClass: 4265 case Expr::ObjCSubscriptRefExprClass: 4266 case Expr::ObjCIndirectCopyRestoreExprClass: 4267 case Expr::ObjCAvailabilityCheckExprClass: 4268 case Expr::OffsetOfExprClass: 4269 case Expr::PredefinedExprClass: 4270 case Expr::ShuffleVectorExprClass: 4271 case Expr::ConvertVectorExprClass: 4272 case Expr::StmtExprClass: 4273 case Expr::TypeTraitExprClass: 4274 case Expr::RequiresExprClass: 4275 case Expr::ArrayTypeTraitExprClass: 4276 case Expr::ExpressionTraitExprClass: 4277 case Expr::VAArgExprClass: 4278 case Expr::CUDAKernelCallExprClass: 4279 case Expr::AsTypeExprClass: 4280 case Expr::PseudoObjectExprClass: 4281 case Expr::AtomicExprClass: 4282 case Expr::SourceLocExprClass: 4283 case Expr::BuiltinBitCastExprClass: 4284 { 4285 NotPrimaryExpr(); 4286 if (!NullOut) { 4287 // As bad as this diagnostic is, it's better than crashing. 4288 DiagnosticsEngine &Diags = Context.getDiags(); 4289 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4290 "cannot yet mangle expression type %0"); 4291 Diags.Report(E->getExprLoc(), DiagID) 4292 << E->getStmtClassName() << E->getSourceRange(); 4293 return; 4294 } 4295 break; 4296 } 4297 4298 case Expr::CXXUuidofExprClass: { 4299 NotPrimaryExpr(); 4300 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 4301 // As of clang 12, uuidof uses the vendor extended expression 4302 // mangling. Previously, it used a special-cased nonstandard extension. 4303 if (Context.getASTContext().getLangOpts().getClangABICompat() > 4304 LangOptions::ClangABI::Ver11) { 4305 Out << "u8__uuidof"; 4306 if (UE->isTypeOperand()) 4307 mangleType(UE->getTypeOperand(Context.getASTContext())); 4308 else 4309 mangleTemplateArgExpr(UE->getExprOperand()); 4310 Out << 'E'; 4311 } else { 4312 if (UE->isTypeOperand()) { 4313 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 4314 Out << "u8__uuidoft"; 4315 mangleType(UuidT); 4316 } else { 4317 Expr *UuidExp = UE->getExprOperand(); 4318 Out << "u8__uuidofz"; 4319 mangleExpression(UuidExp); 4320 } 4321 } 4322 break; 4323 } 4324 4325 // Even gcc-4.5 doesn't mangle this. 4326 case Expr::BinaryConditionalOperatorClass: { 4327 NotPrimaryExpr(); 4328 DiagnosticsEngine &Diags = Context.getDiags(); 4329 unsigned DiagID = 4330 Diags.getCustomDiagID(DiagnosticsEngine::Error, 4331 "?: operator with omitted middle operand cannot be mangled"); 4332 Diags.Report(E->getExprLoc(), DiagID) 4333 << E->getStmtClassName() << E->getSourceRange(); 4334 return; 4335 } 4336 4337 // These are used for internal purposes and cannot be meaningfully mangled. 4338 case Expr::OpaqueValueExprClass: 4339 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 4340 4341 case Expr::InitListExprClass: { 4342 NotPrimaryExpr(); 4343 Out << "il"; 4344 mangleInitListElements(cast<InitListExpr>(E)); 4345 Out << "E"; 4346 break; 4347 } 4348 4349 case Expr::DesignatedInitExprClass: { 4350 NotPrimaryExpr(); 4351 auto *DIE = cast<DesignatedInitExpr>(E); 4352 for (const auto &Designator : DIE->designators()) { 4353 if (Designator.isFieldDesignator()) { 4354 Out << "di"; 4355 mangleSourceName(Designator.getFieldName()); 4356 } else if (Designator.isArrayDesignator()) { 4357 Out << "dx"; 4358 mangleExpression(DIE->getArrayIndex(Designator)); 4359 } else { 4360 assert(Designator.isArrayRangeDesignator() && 4361 "unknown designator kind"); 4362 Out << "dX"; 4363 mangleExpression(DIE->getArrayRangeStart(Designator)); 4364 mangleExpression(DIE->getArrayRangeEnd(Designator)); 4365 } 4366 } 4367 mangleExpression(DIE->getInit()); 4368 break; 4369 } 4370 4371 case Expr::CXXDefaultArgExprClass: 4372 E = cast<CXXDefaultArgExpr>(E)->getExpr(); 4373 goto recurse; 4374 4375 case Expr::CXXDefaultInitExprClass: 4376 E = cast<CXXDefaultInitExpr>(E)->getExpr(); 4377 goto recurse; 4378 4379 case Expr::CXXStdInitializerListExprClass: 4380 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr(); 4381 goto recurse; 4382 4383 case Expr::SubstNonTypeTemplateParmExprClass: 4384 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(); 4385 goto recurse; 4386 4387 case Expr::UserDefinedLiteralClass: 4388 // We follow g++'s approach of mangling a UDL as a call to the literal 4389 // operator. 4390 case Expr::CXXMemberCallExprClass: // fallthrough 4391 case Expr::CallExprClass: { 4392 NotPrimaryExpr(); 4393 const CallExpr *CE = cast<CallExpr>(E); 4394 4395 // <expression> ::= cp <simple-id> <expression>* E 4396 // We use this mangling only when the call would use ADL except 4397 // for being parenthesized. Per discussion with David 4398 // Vandervoorde, 2011.04.25. 4399 if (isParenthesizedADLCallee(CE)) { 4400 Out << "cp"; 4401 // The callee here is a parenthesized UnresolvedLookupExpr with 4402 // no qualifier and should always get mangled as a <simple-id> 4403 // anyway. 4404 4405 // <expression> ::= cl <expression>* E 4406 } else { 4407 Out << "cl"; 4408 } 4409 4410 unsigned CallArity = CE->getNumArgs(); 4411 for (const Expr *Arg : CE->arguments()) 4412 if (isa<PackExpansionExpr>(Arg)) 4413 CallArity = UnknownArity; 4414 4415 mangleExpression(CE->getCallee(), CallArity); 4416 for (const Expr *Arg : CE->arguments()) 4417 mangleExpression(Arg); 4418 Out << 'E'; 4419 break; 4420 } 4421 4422 case Expr::CXXNewExprClass: { 4423 NotPrimaryExpr(); 4424 const CXXNewExpr *New = cast<CXXNewExpr>(E); 4425 if (New->isGlobalNew()) Out << "gs"; 4426 Out << (New->isArray() ? "na" : "nw"); 4427 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 4428 E = New->placement_arg_end(); I != E; ++I) 4429 mangleExpression(*I); 4430 Out << '_'; 4431 mangleType(New->getAllocatedType()); 4432 if (New->hasInitializer()) { 4433 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 4434 Out << "il"; 4435 else 4436 Out << "pi"; 4437 const Expr *Init = New->getInitializer(); 4438 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 4439 // Directly inline the initializers. 4440 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 4441 E = CCE->arg_end(); 4442 I != E; ++I) 4443 mangleExpression(*I); 4444 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 4445 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 4446 mangleExpression(PLE->getExpr(i)); 4447 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 4448 isa<InitListExpr>(Init)) { 4449 // Only take InitListExprs apart for list-initialization. 4450 mangleInitListElements(cast<InitListExpr>(Init)); 4451 } else 4452 mangleExpression(Init); 4453 } 4454 Out << 'E'; 4455 break; 4456 } 4457 4458 case Expr::CXXPseudoDestructorExprClass: { 4459 NotPrimaryExpr(); 4460 const auto *PDE = cast<CXXPseudoDestructorExpr>(E); 4461 if (const Expr *Base = PDE->getBase()) 4462 mangleMemberExprBase(Base, PDE->isArrow()); 4463 NestedNameSpecifier *Qualifier = PDE->getQualifier(); 4464 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) { 4465 if (Qualifier) { 4466 mangleUnresolvedPrefix(Qualifier, 4467 /*recursive=*/true); 4468 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()); 4469 Out << 'E'; 4470 } else { 4471 Out << "sr"; 4472 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType())) 4473 Out << 'E'; 4474 } 4475 } else if (Qualifier) { 4476 mangleUnresolvedPrefix(Qualifier); 4477 } 4478 // <base-unresolved-name> ::= dn <destructor-name> 4479 Out << "dn"; 4480 QualType DestroyedType = PDE->getDestroyedType(); 4481 mangleUnresolvedTypeOrSimpleId(DestroyedType); 4482 break; 4483 } 4484 4485 case Expr::MemberExprClass: { 4486 NotPrimaryExpr(); 4487 const MemberExpr *ME = cast<MemberExpr>(E); 4488 mangleMemberExpr(ME->getBase(), ME->isArrow(), 4489 ME->getQualifier(), nullptr, 4490 ME->getMemberDecl()->getDeclName(), 4491 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4492 Arity); 4493 break; 4494 } 4495 4496 case Expr::UnresolvedMemberExprClass: { 4497 NotPrimaryExpr(); 4498 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 4499 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4500 ME->isArrow(), ME->getQualifier(), nullptr, 4501 ME->getMemberName(), 4502 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4503 Arity); 4504 break; 4505 } 4506 4507 case Expr::CXXDependentScopeMemberExprClass: { 4508 NotPrimaryExpr(); 4509 const CXXDependentScopeMemberExpr *ME 4510 = cast<CXXDependentScopeMemberExpr>(E); 4511 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4512 ME->isArrow(), ME->getQualifier(), 4513 ME->getFirstQualifierFoundInScope(), 4514 ME->getMember(), 4515 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4516 Arity); 4517 break; 4518 } 4519 4520 case Expr::UnresolvedLookupExprClass: { 4521 NotPrimaryExpr(); 4522 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 4523 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), 4524 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(), 4525 Arity); 4526 break; 4527 } 4528 4529 case Expr::CXXUnresolvedConstructExprClass: { 4530 NotPrimaryExpr(); 4531 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 4532 unsigned N = CE->getNumArgs(); 4533 4534 if (CE->isListInitialization()) { 4535 assert(N == 1 && "unexpected form for list initialization"); 4536 auto *IL = cast<InitListExpr>(CE->getArg(0)); 4537 Out << "tl"; 4538 mangleType(CE->getType()); 4539 mangleInitListElements(IL); 4540 Out << "E"; 4541 break; 4542 } 4543 4544 Out << "cv"; 4545 mangleType(CE->getType()); 4546 if (N != 1) Out << '_'; 4547 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 4548 if (N != 1) Out << 'E'; 4549 break; 4550 } 4551 4552 case Expr::CXXConstructExprClass: { 4553 // An implicit cast is silent, thus may contain <expr-primary>. 4554 const auto *CE = cast<CXXConstructExpr>(E); 4555 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) { 4556 assert( 4557 CE->getNumArgs() >= 1 && 4558 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && 4559 "implicit CXXConstructExpr must have one argument"); 4560 E = cast<CXXConstructExpr>(E)->getArg(0); 4561 goto recurse; 4562 } 4563 NotPrimaryExpr(); 4564 Out << "il"; 4565 for (auto *E : CE->arguments()) 4566 mangleExpression(E); 4567 Out << "E"; 4568 break; 4569 } 4570 4571 case Expr::CXXTemporaryObjectExprClass: { 4572 NotPrimaryExpr(); 4573 const auto *CE = cast<CXXTemporaryObjectExpr>(E); 4574 unsigned N = CE->getNumArgs(); 4575 bool List = CE->isListInitialization(); 4576 4577 if (List) 4578 Out << "tl"; 4579 else 4580 Out << "cv"; 4581 mangleType(CE->getType()); 4582 if (!List && N != 1) 4583 Out << '_'; 4584 if (CE->isStdInitListInitialization()) { 4585 // We implicitly created a std::initializer_list<T> for the first argument 4586 // of a constructor of type U in an expression of the form U{a, b, c}. 4587 // Strip all the semantic gunk off the initializer list. 4588 auto *SILE = 4589 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit()); 4590 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit()); 4591 mangleInitListElements(ILE); 4592 } else { 4593 for (auto *E : CE->arguments()) 4594 mangleExpression(E); 4595 } 4596 if (List || N != 1) 4597 Out << 'E'; 4598 break; 4599 } 4600 4601 case Expr::CXXScalarValueInitExprClass: 4602 NotPrimaryExpr(); 4603 Out << "cv"; 4604 mangleType(E->getType()); 4605 Out << "_E"; 4606 break; 4607 4608 case Expr::CXXNoexceptExprClass: 4609 NotPrimaryExpr(); 4610 Out << "nx"; 4611 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 4612 break; 4613 4614 case Expr::UnaryExprOrTypeTraitExprClass: { 4615 // Non-instantiation-dependent traits are an <expr-primary> integer literal. 4616 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 4617 4618 if (!SAE->isInstantiationDependent()) { 4619 // Itanium C++ ABI: 4620 // If the operand of a sizeof or alignof operator is not 4621 // instantiation-dependent it is encoded as an integer literal 4622 // reflecting the result of the operator. 4623 // 4624 // If the result of the operator is implicitly converted to a known 4625 // integer type, that type is used for the literal; otherwise, the type 4626 // of std::size_t or std::ptrdiff_t is used. 4627 QualType T = (ImplicitlyConvertedToType.isNull() || 4628 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 4629 : ImplicitlyConvertedToType; 4630 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 4631 mangleIntegerLiteral(T, V); 4632 break; 4633 } 4634 4635 NotPrimaryExpr(); // But otherwise, they are not. 4636 4637 auto MangleAlignofSizeofArg = [&] { 4638 if (SAE->isArgumentType()) { 4639 Out << 't'; 4640 mangleType(SAE->getArgumentType()); 4641 } else { 4642 Out << 'z'; 4643 mangleExpression(SAE->getArgumentExpr()); 4644 } 4645 }; 4646 4647 switch(SAE->getKind()) { 4648 case UETT_SizeOf: 4649 Out << 's'; 4650 MangleAlignofSizeofArg(); 4651 break; 4652 case UETT_PreferredAlignOf: 4653 // As of clang 12, we mangle __alignof__ differently than alignof. (They 4654 // have acted differently since Clang 8, but were previously mangled the 4655 // same.) 4656 if (Context.getASTContext().getLangOpts().getClangABICompat() > 4657 LangOptions::ClangABI::Ver11) { 4658 Out << "u11__alignof__"; 4659 if (SAE->isArgumentType()) 4660 mangleType(SAE->getArgumentType()); 4661 else 4662 mangleTemplateArgExpr(SAE->getArgumentExpr()); 4663 Out << 'E'; 4664 break; 4665 } 4666 LLVM_FALLTHROUGH; 4667 case UETT_AlignOf: 4668 Out << 'a'; 4669 MangleAlignofSizeofArg(); 4670 break; 4671 case UETT_VecStep: { 4672 DiagnosticsEngine &Diags = Context.getDiags(); 4673 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4674 "cannot yet mangle vec_step expression"); 4675 Diags.Report(DiagID); 4676 return; 4677 } 4678 case UETT_OpenMPRequiredSimdAlign: { 4679 DiagnosticsEngine &Diags = Context.getDiags(); 4680 unsigned DiagID = Diags.getCustomDiagID( 4681 DiagnosticsEngine::Error, 4682 "cannot yet mangle __builtin_omp_required_simd_align expression"); 4683 Diags.Report(DiagID); 4684 return; 4685 } 4686 } 4687 break; 4688 } 4689 4690 case Expr::CXXThrowExprClass: { 4691 NotPrimaryExpr(); 4692 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 4693 // <expression> ::= tw <expression> # throw expression 4694 // ::= tr # rethrow 4695 if (TE->getSubExpr()) { 4696 Out << "tw"; 4697 mangleExpression(TE->getSubExpr()); 4698 } else { 4699 Out << "tr"; 4700 } 4701 break; 4702 } 4703 4704 case Expr::CXXTypeidExprClass: { 4705 NotPrimaryExpr(); 4706 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 4707 // <expression> ::= ti <type> # typeid (type) 4708 // ::= te <expression> # typeid (expression) 4709 if (TIE->isTypeOperand()) { 4710 Out << "ti"; 4711 mangleType(TIE->getTypeOperand(Context.getASTContext())); 4712 } else { 4713 Out << "te"; 4714 mangleExpression(TIE->getExprOperand()); 4715 } 4716 break; 4717 } 4718 4719 case Expr::CXXDeleteExprClass: { 4720 NotPrimaryExpr(); 4721 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 4722 // <expression> ::= [gs] dl <expression> # [::] delete expr 4723 // ::= [gs] da <expression> # [::] delete [] expr 4724 if (DE->isGlobalDelete()) Out << "gs"; 4725 Out << (DE->isArrayForm() ? "da" : "dl"); 4726 mangleExpression(DE->getArgument()); 4727 break; 4728 } 4729 4730 case Expr::UnaryOperatorClass: { 4731 NotPrimaryExpr(); 4732 const UnaryOperator *UO = cast<UnaryOperator>(E); 4733 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 4734 /*Arity=*/1); 4735 mangleExpression(UO->getSubExpr()); 4736 break; 4737 } 4738 4739 case Expr::ArraySubscriptExprClass: { 4740 NotPrimaryExpr(); 4741 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 4742 4743 // Array subscript is treated as a syntactically weird form of 4744 // binary operator. 4745 Out << "ix"; 4746 mangleExpression(AE->getLHS()); 4747 mangleExpression(AE->getRHS()); 4748 break; 4749 } 4750 4751 case Expr::MatrixSubscriptExprClass: { 4752 NotPrimaryExpr(); 4753 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E); 4754 Out << "ixix"; 4755 mangleExpression(ME->getBase()); 4756 mangleExpression(ME->getRowIdx()); 4757 mangleExpression(ME->getColumnIdx()); 4758 break; 4759 } 4760 4761 case Expr::CompoundAssignOperatorClass: // fallthrough 4762 case Expr::BinaryOperatorClass: { 4763 NotPrimaryExpr(); 4764 const BinaryOperator *BO = cast<BinaryOperator>(E); 4765 if (BO->getOpcode() == BO_PtrMemD) 4766 Out << "ds"; 4767 else 4768 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 4769 /*Arity=*/2); 4770 mangleExpression(BO->getLHS()); 4771 mangleExpression(BO->getRHS()); 4772 break; 4773 } 4774 4775 case Expr::CXXRewrittenBinaryOperatorClass: { 4776 NotPrimaryExpr(); 4777 // The mangled form represents the original syntax. 4778 CXXRewrittenBinaryOperator::DecomposedForm Decomposed = 4779 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm(); 4780 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode), 4781 /*Arity=*/2); 4782 mangleExpression(Decomposed.LHS); 4783 mangleExpression(Decomposed.RHS); 4784 break; 4785 } 4786 4787 case Expr::ConditionalOperatorClass: { 4788 NotPrimaryExpr(); 4789 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 4790 mangleOperatorName(OO_Conditional, /*Arity=*/3); 4791 mangleExpression(CO->getCond()); 4792 mangleExpression(CO->getLHS(), Arity); 4793 mangleExpression(CO->getRHS(), Arity); 4794 break; 4795 } 4796 4797 case Expr::ImplicitCastExprClass: { 4798 ImplicitlyConvertedToType = E->getType(); 4799 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4800 goto recurse; 4801 } 4802 4803 case Expr::ObjCBridgedCastExprClass: { 4804 NotPrimaryExpr(); 4805 // Mangle ownership casts as a vendor extended operator __bridge, 4806 // __bridge_transfer, or __bridge_retain. 4807 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 4808 Out << "v1U" << Kind.size() << Kind; 4809 mangleCastExpression(E, "cv"); 4810 break; 4811 } 4812 4813 case Expr::CStyleCastExprClass: 4814 NotPrimaryExpr(); 4815 mangleCastExpression(E, "cv"); 4816 break; 4817 4818 case Expr::CXXFunctionalCastExprClass: { 4819 NotPrimaryExpr(); 4820 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit(); 4821 // FIXME: Add isImplicit to CXXConstructExpr. 4822 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub)) 4823 if (CCE->getParenOrBraceRange().isInvalid()) 4824 Sub = CCE->getArg(0)->IgnoreImplicit(); 4825 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub)) 4826 Sub = StdInitList->getSubExpr()->IgnoreImplicit(); 4827 if (auto *IL = dyn_cast<InitListExpr>(Sub)) { 4828 Out << "tl"; 4829 mangleType(E->getType()); 4830 mangleInitListElements(IL); 4831 Out << "E"; 4832 } else { 4833 mangleCastExpression(E, "cv"); 4834 } 4835 break; 4836 } 4837 4838 case Expr::CXXStaticCastExprClass: 4839 NotPrimaryExpr(); 4840 mangleCastExpression(E, "sc"); 4841 break; 4842 case Expr::CXXDynamicCastExprClass: 4843 NotPrimaryExpr(); 4844 mangleCastExpression(E, "dc"); 4845 break; 4846 case Expr::CXXReinterpretCastExprClass: 4847 NotPrimaryExpr(); 4848 mangleCastExpression(E, "rc"); 4849 break; 4850 case Expr::CXXConstCastExprClass: 4851 NotPrimaryExpr(); 4852 mangleCastExpression(E, "cc"); 4853 break; 4854 case Expr::CXXAddrspaceCastExprClass: 4855 NotPrimaryExpr(); 4856 mangleCastExpression(E, "ac"); 4857 break; 4858 4859 case Expr::CXXOperatorCallExprClass: { 4860 NotPrimaryExpr(); 4861 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 4862 unsigned NumArgs = CE->getNumArgs(); 4863 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax 4864 // (the enclosing MemberExpr covers the syntactic portion). 4865 if (CE->getOperator() != OO_Arrow) 4866 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 4867 // Mangle the arguments. 4868 for (unsigned i = 0; i != NumArgs; ++i) 4869 mangleExpression(CE->getArg(i)); 4870 break; 4871 } 4872 4873 case Expr::ParenExprClass: 4874 E = cast<ParenExpr>(E)->getSubExpr(); 4875 goto recurse; 4876 4877 case Expr::ConceptSpecializationExprClass: { 4878 // <expr-primary> ::= L <mangled-name> E # external name 4879 Out << "L_Z"; 4880 auto *CSE = cast<ConceptSpecializationExpr>(E); 4881 mangleTemplateName(CSE->getNamedConcept(), 4882 CSE->getTemplateArguments().data(), 4883 CSE->getTemplateArguments().size()); 4884 Out << 'E'; 4885 break; 4886 } 4887 4888 case Expr::DeclRefExprClass: 4889 // MangleDeclRefExpr helper handles primary-vs-nonprimary 4890 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl()); 4891 break; 4892 4893 case Expr::SubstNonTypeTemplateParmPackExprClass: 4894 NotPrimaryExpr(); 4895 // FIXME: not clear how to mangle this! 4896 // template <unsigned N...> class A { 4897 // template <class U...> void foo(U (&x)[N]...); 4898 // }; 4899 Out << "_SUBSTPACK_"; 4900 break; 4901 4902 case Expr::FunctionParmPackExprClass: { 4903 NotPrimaryExpr(); 4904 // FIXME: not clear how to mangle this! 4905 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 4906 Out << "v110_SUBSTPACK"; 4907 MangleDeclRefExpr(FPPE->getParameterPack()); 4908 break; 4909 } 4910 4911 case Expr::DependentScopeDeclRefExprClass: { 4912 NotPrimaryExpr(); 4913 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 4914 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), 4915 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(), 4916 Arity); 4917 break; 4918 } 4919 4920 case Expr::CXXBindTemporaryExprClass: 4921 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr(); 4922 goto recurse; 4923 4924 case Expr::ExprWithCleanupsClass: 4925 E = cast<ExprWithCleanups>(E)->getSubExpr(); 4926 goto recurse; 4927 4928 case Expr::FloatingLiteralClass: { 4929 // <expr-primary> 4930 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 4931 mangleFloatLiteral(FL->getType(), FL->getValue()); 4932 break; 4933 } 4934 4935 case Expr::FixedPointLiteralClass: 4936 // Currently unimplemented -- might be <expr-primary> in future? 4937 mangleFixedPointLiteral(); 4938 break; 4939 4940 case Expr::CharacterLiteralClass: 4941 // <expr-primary> 4942 Out << 'L'; 4943 mangleType(E->getType()); 4944 Out << cast<CharacterLiteral>(E)->getValue(); 4945 Out << 'E'; 4946 break; 4947 4948 // FIXME. __objc_yes/__objc_no are mangled same as true/false 4949 case Expr::ObjCBoolLiteralExprClass: 4950 // <expr-primary> 4951 Out << "Lb"; 4952 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4953 Out << 'E'; 4954 break; 4955 4956 case Expr::CXXBoolLiteralExprClass: 4957 // <expr-primary> 4958 Out << "Lb"; 4959 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4960 Out << 'E'; 4961 break; 4962 4963 case Expr::IntegerLiteralClass: { 4964 // <expr-primary> 4965 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 4966 if (E->getType()->isSignedIntegerType()) 4967 Value.setIsSigned(true); 4968 mangleIntegerLiteral(E->getType(), Value); 4969 break; 4970 } 4971 4972 case Expr::ImaginaryLiteralClass: { 4973 // <expr-primary> 4974 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 4975 // Mangle as if a complex literal. 4976 // Proposal from David Vandevoorde, 2010.06.30. 4977 Out << 'L'; 4978 mangleType(E->getType()); 4979 if (const FloatingLiteral *Imag = 4980 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 4981 // Mangle a floating-point zero of the appropriate type. 4982 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 4983 Out << '_'; 4984 mangleFloat(Imag->getValue()); 4985 } else { 4986 Out << "0_"; 4987 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 4988 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 4989 Value.setIsSigned(true); 4990 mangleNumber(Value); 4991 } 4992 Out << 'E'; 4993 break; 4994 } 4995 4996 case Expr::StringLiteralClass: { 4997 // <expr-primary> 4998 // Revised proposal from David Vandervoorde, 2010.07.15. 4999 Out << 'L'; 5000 assert(isa<ConstantArrayType>(E->getType())); 5001 mangleType(E->getType()); 5002 Out << 'E'; 5003 break; 5004 } 5005 5006 case Expr::GNUNullExprClass: 5007 // <expr-primary> 5008 // Mangle as if an integer literal 0. 5009 mangleIntegerLiteral(E->getType(), llvm::APSInt(32)); 5010 break; 5011 5012 case Expr::CXXNullPtrLiteralExprClass: { 5013 // <expr-primary> 5014 Out << "LDnE"; 5015 break; 5016 } 5017 5018 case Expr::LambdaExprClass: { 5019 // A lambda-expression can't appear in the signature of an 5020 // externally-visible declaration, so there's no standard mangling for 5021 // this, but mangling as a literal of the closure type seems reasonable. 5022 Out << "L"; 5023 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass())); 5024 Out << "E"; 5025 break; 5026 } 5027 5028 case Expr::PackExpansionExprClass: 5029 NotPrimaryExpr(); 5030 Out << "sp"; 5031 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 5032 break; 5033 5034 case Expr::SizeOfPackExprClass: { 5035 NotPrimaryExpr(); 5036 auto *SPE = cast<SizeOfPackExpr>(E); 5037 if (SPE->isPartiallySubstituted()) { 5038 Out << "sP"; 5039 for (const auto &A : SPE->getPartialArguments()) 5040 mangleTemplateArg(A, false); 5041 Out << "E"; 5042 break; 5043 } 5044 5045 Out << "sZ"; 5046 const NamedDecl *Pack = SPE->getPack(); 5047 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 5048 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 5049 else if (const NonTypeTemplateParmDecl *NTTP 5050 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 5051 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex()); 5052 else if (const TemplateTemplateParmDecl *TempTP 5053 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 5054 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex()); 5055 else 5056 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 5057 break; 5058 } 5059 5060 case Expr::MaterializeTemporaryExprClass: 5061 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr(); 5062 goto recurse; 5063 5064 case Expr::CXXFoldExprClass: { 5065 NotPrimaryExpr(); 5066 auto *FE = cast<CXXFoldExpr>(E); 5067 if (FE->isLeftFold()) 5068 Out << (FE->getInit() ? "fL" : "fl"); 5069 else 5070 Out << (FE->getInit() ? "fR" : "fr"); 5071 5072 if (FE->getOperator() == BO_PtrMemD) 5073 Out << "ds"; 5074 else 5075 mangleOperatorName( 5076 BinaryOperator::getOverloadedOperator(FE->getOperator()), 5077 /*Arity=*/2); 5078 5079 if (FE->getLHS()) 5080 mangleExpression(FE->getLHS()); 5081 if (FE->getRHS()) 5082 mangleExpression(FE->getRHS()); 5083 break; 5084 } 5085 5086 case Expr::CXXThisExprClass: 5087 NotPrimaryExpr(); 5088 Out << "fpT"; 5089 break; 5090 5091 case Expr::CoawaitExprClass: 5092 // FIXME: Propose a non-vendor mangling. 5093 NotPrimaryExpr(); 5094 Out << "v18co_await"; 5095 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 5096 break; 5097 5098 case Expr::DependentCoawaitExprClass: 5099 // FIXME: Propose a non-vendor mangling. 5100 NotPrimaryExpr(); 5101 Out << "v18co_await"; 5102 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand()); 5103 break; 5104 5105 case Expr::CoyieldExprClass: 5106 // FIXME: Propose a non-vendor mangling. 5107 NotPrimaryExpr(); 5108 Out << "v18co_yield"; 5109 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 5110 break; 5111 case Expr::SYCLUniqueStableNameExprClass: { 5112 const auto *USN = cast<SYCLUniqueStableNameExpr>(E); 5113 NotPrimaryExpr(); 5114 5115 Out << "u33__builtin_sycl_unique_stable_name"; 5116 mangleType(USN->getTypeSourceInfo()->getType()); 5117 5118 Out << "E"; 5119 break; 5120 } 5121 } 5122 5123 if (AsTemplateArg && !IsPrimaryExpr) 5124 Out << 'E'; 5125 } 5126 5127 /// Mangle an expression which refers to a parameter variable. 5128 /// 5129 /// <expression> ::= <function-param> 5130 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 5131 /// <function-param> ::= fp <top-level CV-qualifiers> 5132 /// <parameter-2 non-negative number> _ # L == 0, I > 0 5133 /// <function-param> ::= fL <L-1 non-negative number> 5134 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 5135 /// <function-param> ::= fL <L-1 non-negative number> 5136 /// p <top-level CV-qualifiers> 5137 /// <I-1 non-negative number> _ # L > 0, I > 0 5138 /// 5139 /// L is the nesting depth of the parameter, defined as 1 if the 5140 /// parameter comes from the innermost function prototype scope 5141 /// enclosing the current context, 2 if from the next enclosing 5142 /// function prototype scope, and so on, with one special case: if 5143 /// we've processed the full parameter clause for the innermost 5144 /// function type, then L is one less. This definition conveniently 5145 /// makes it irrelevant whether a function's result type was written 5146 /// trailing or leading, but is otherwise overly complicated; the 5147 /// numbering was first designed without considering references to 5148 /// parameter in locations other than return types, and then the 5149 /// mangling had to be generalized without changing the existing 5150 /// manglings. 5151 /// 5152 /// I is the zero-based index of the parameter within its parameter 5153 /// declaration clause. Note that the original ABI document describes 5154 /// this using 1-based ordinals. 5155 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 5156 unsigned parmDepth = parm->getFunctionScopeDepth(); 5157 unsigned parmIndex = parm->getFunctionScopeIndex(); 5158 5159 // Compute 'L'. 5160 // parmDepth does not include the declaring function prototype. 5161 // FunctionTypeDepth does account for that. 5162 assert(parmDepth < FunctionTypeDepth.getDepth()); 5163 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 5164 if (FunctionTypeDepth.isInResultType()) 5165 nestingDepth--; 5166 5167 if (nestingDepth == 0) { 5168 Out << "fp"; 5169 } else { 5170 Out << "fL" << (nestingDepth - 1) << 'p'; 5171 } 5172 5173 // Top-level qualifiers. We don't have to worry about arrays here, 5174 // because parameters declared as arrays should already have been 5175 // transformed to have pointer type. FIXME: apparently these don't 5176 // get mangled if used as an rvalue of a known non-class type? 5177 assert(!parm->getType()->isArrayType() 5178 && "parameter's type is still an array type?"); 5179 5180 if (const DependentAddressSpaceType *DAST = 5181 dyn_cast<DependentAddressSpaceType>(parm->getType())) { 5182 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST); 5183 } else { 5184 mangleQualifiers(parm->getType().getQualifiers()); 5185 } 5186 5187 // Parameter index. 5188 if (parmIndex != 0) { 5189 Out << (parmIndex - 1); 5190 } 5191 Out << '_'; 5192 } 5193 5194 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T, 5195 const CXXRecordDecl *InheritedFrom) { 5196 // <ctor-dtor-name> ::= C1 # complete object constructor 5197 // ::= C2 # base object constructor 5198 // ::= CI1 <type> # complete inheriting constructor 5199 // ::= CI2 <type> # base inheriting constructor 5200 // 5201 // In addition, C5 is a comdat name with C1 and C2 in it. 5202 Out << 'C'; 5203 if (InheritedFrom) 5204 Out << 'I'; 5205 switch (T) { 5206 case Ctor_Complete: 5207 Out << '1'; 5208 break; 5209 case Ctor_Base: 5210 Out << '2'; 5211 break; 5212 case Ctor_Comdat: 5213 Out << '5'; 5214 break; 5215 case Ctor_DefaultClosure: 5216 case Ctor_CopyingClosure: 5217 llvm_unreachable("closure constructors don't exist for the Itanium ABI!"); 5218 } 5219 if (InheritedFrom) 5220 mangleName(InheritedFrom); 5221 } 5222 5223 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 5224 // <ctor-dtor-name> ::= D0 # deleting destructor 5225 // ::= D1 # complete object destructor 5226 // ::= D2 # base object destructor 5227 // 5228 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 5229 switch (T) { 5230 case Dtor_Deleting: 5231 Out << "D0"; 5232 break; 5233 case Dtor_Complete: 5234 Out << "D1"; 5235 break; 5236 case Dtor_Base: 5237 Out << "D2"; 5238 break; 5239 case Dtor_Comdat: 5240 Out << "D5"; 5241 break; 5242 } 5243 } 5244 5245 namespace { 5246 // Helper to provide ancillary information on a template used to mangle its 5247 // arguments. 5248 struct TemplateArgManglingInfo { 5249 TemplateDecl *ResolvedTemplate = nullptr; 5250 bool SeenPackExpansionIntoNonPack = false; 5251 const NamedDecl *UnresolvedExpandedPack = nullptr; 5252 5253 TemplateArgManglingInfo(TemplateName TN) { 5254 if (TemplateDecl *TD = TN.getAsTemplateDecl()) 5255 ResolvedTemplate = TD; 5256 } 5257 5258 /// Do we need to mangle template arguments with exactly correct types? 5259 /// 5260 /// This should be called exactly once for each parameter / argument pair, in 5261 /// order. 5262 bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) { 5263 // We need correct types when the template-name is unresolved or when it 5264 // names a template that is able to be overloaded. 5265 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack) 5266 return true; 5267 5268 // Move to the next parameter. 5269 const NamedDecl *Param = UnresolvedExpandedPack; 5270 if (!Param) { 5271 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && 5272 "no parameter for argument"); 5273 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx); 5274 5275 // If we reach an expanded parameter pack whose argument isn't in pack 5276 // form, that means Sema couldn't figure out which arguments belonged to 5277 // it, because it contains a pack expansion. Track the expanded pack for 5278 // all further template arguments until we hit that pack expansion. 5279 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) { 5280 assert(getExpandedPackSize(Param) && 5281 "failed to form pack argument for parameter pack"); 5282 UnresolvedExpandedPack = Param; 5283 } 5284 } 5285 5286 // If we encounter a pack argument that is expanded into a non-pack 5287 // parameter, we can no longer track parameter / argument correspondence, 5288 // and need to use exact types from this point onwards. 5289 if (Arg.isPackExpansion() && 5290 (!Param->isParameterPack() || UnresolvedExpandedPack)) { 5291 SeenPackExpansionIntoNonPack = true; 5292 return true; 5293 } 5294 5295 // We need exact types for function template arguments because they might be 5296 // overloaded on template parameter type. As a special case, a member 5297 // function template of a generic lambda is not overloadable. 5298 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) { 5299 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext()); 5300 if (!RD || !RD->isGenericLambda()) 5301 return true; 5302 } 5303 5304 // Otherwise, we only need a correct type if the parameter has a deduced 5305 // type. 5306 // 5307 // Note: for an expanded parameter pack, getType() returns the type prior 5308 // to expansion. We could ask for the expanded type with getExpansionType(), 5309 // but it doesn't matter because substitution and expansion don't affect 5310 // whether a deduced type appears in the type. 5311 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param); 5312 return NTTP && NTTP->getType()->getContainedDeducedType(); 5313 } 5314 }; 5315 } 5316 5317 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5318 const TemplateArgumentLoc *TemplateArgs, 5319 unsigned NumTemplateArgs) { 5320 // <template-args> ::= I <template-arg>+ E 5321 Out << 'I'; 5322 TemplateArgManglingInfo Info(TN); 5323 for (unsigned i = 0; i != NumTemplateArgs; ++i) 5324 mangleTemplateArg(TemplateArgs[i].getArgument(), 5325 Info.needExactType(i, TemplateArgs[i].getArgument())); 5326 Out << 'E'; 5327 } 5328 5329 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5330 const TemplateArgumentList &AL) { 5331 // <template-args> ::= I <template-arg>+ E 5332 Out << 'I'; 5333 TemplateArgManglingInfo Info(TN); 5334 for (unsigned i = 0, e = AL.size(); i != e; ++i) 5335 mangleTemplateArg(AL[i], Info.needExactType(i, AL[i])); 5336 Out << 'E'; 5337 } 5338 5339 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5340 const TemplateArgument *TemplateArgs, 5341 unsigned NumTemplateArgs) { 5342 // <template-args> ::= I <template-arg>+ E 5343 Out << 'I'; 5344 TemplateArgManglingInfo Info(TN); 5345 for (unsigned i = 0; i != NumTemplateArgs; ++i) 5346 mangleTemplateArg(TemplateArgs[i], Info.needExactType(i, TemplateArgs[i])); 5347 Out << 'E'; 5348 } 5349 5350 void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) { 5351 // <template-arg> ::= <type> # type or template 5352 // ::= X <expression> E # expression 5353 // ::= <expr-primary> # simple expressions 5354 // ::= J <template-arg>* E # argument pack 5355 if (!A.isInstantiationDependent() || A.isDependent()) 5356 A = Context.getASTContext().getCanonicalTemplateArgument(A); 5357 5358 switch (A.getKind()) { 5359 case TemplateArgument::Null: 5360 llvm_unreachable("Cannot mangle NULL template argument"); 5361 5362 case TemplateArgument::Type: 5363 mangleType(A.getAsType()); 5364 break; 5365 case TemplateArgument::Template: 5366 // This is mangled as <type>. 5367 mangleType(A.getAsTemplate()); 5368 break; 5369 case TemplateArgument::TemplateExpansion: 5370 // <type> ::= Dp <type> # pack expansion (C++0x) 5371 Out << "Dp"; 5372 mangleType(A.getAsTemplateOrTemplatePattern()); 5373 break; 5374 case TemplateArgument::Expression: 5375 mangleTemplateArgExpr(A.getAsExpr()); 5376 break; 5377 case TemplateArgument::Integral: 5378 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 5379 break; 5380 case TemplateArgument::Declaration: { 5381 // <expr-primary> ::= L <mangled-name> E # external name 5382 ValueDecl *D = A.getAsDecl(); 5383 5384 // Template parameter objects are modeled by reproducing a source form 5385 // produced as if by aggregate initialization. 5386 if (A.getParamTypeForDecl()->isRecordType()) { 5387 auto *TPO = cast<TemplateParamObjectDecl>(D); 5388 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(), 5389 TPO->getValue(), /*TopLevel=*/true, 5390 NeedExactType); 5391 break; 5392 } 5393 5394 ASTContext &Ctx = Context.getASTContext(); 5395 APValue Value; 5396 if (D->isCXXInstanceMember()) 5397 // Simple pointer-to-member with no conversion. 5398 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{}); 5399 else if (D->getType()->isArrayType() && 5400 Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()), 5401 A.getParamTypeForDecl()) && 5402 Ctx.getLangOpts().getClangABICompat() > 5403 LangOptions::ClangABI::Ver11) 5404 // Build a value corresponding to this implicit array-to-pointer decay. 5405 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 5406 {APValue::LValuePathEntry::ArrayIndex(0)}, 5407 /*OnePastTheEnd=*/false); 5408 else 5409 // Regular pointer or reference to a declaration. 5410 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 5411 ArrayRef<APValue::LValuePathEntry>(), 5412 /*OnePastTheEnd=*/false); 5413 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true, 5414 NeedExactType); 5415 break; 5416 } 5417 case TemplateArgument::NullPtr: { 5418 mangleNullPointer(A.getNullPtrType()); 5419 break; 5420 } 5421 case TemplateArgument::Pack: { 5422 // <template-arg> ::= J <template-arg>* E 5423 Out << 'J'; 5424 for (const auto &P : A.pack_elements()) 5425 mangleTemplateArg(P, NeedExactType); 5426 Out << 'E'; 5427 } 5428 } 5429 } 5430 5431 void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) { 5432 ASTContext &Ctx = Context.getASTContext(); 5433 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) { 5434 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true); 5435 return; 5436 } 5437 5438 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary> 5439 // correctly in cases where the template argument was 5440 // constructed from an expression rather than an already-evaluated 5441 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of 5442 // 'Li0E'. 5443 // 5444 // We did special-case DeclRefExpr to attempt to DTRT for that one 5445 // expression-kind, but while doing so, unfortunately handled ParmVarDecl 5446 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of 5447 // the proper 'Xfp_E'. 5448 E = E->IgnoreParenImpCasts(); 5449 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 5450 const ValueDecl *D = DRE->getDecl(); 5451 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 5452 Out << 'L'; 5453 mangle(D); 5454 Out << 'E'; 5455 return; 5456 } 5457 } 5458 Out << 'X'; 5459 mangleExpression(E); 5460 Out << 'E'; 5461 } 5462 5463 /// Determine whether a given value is equivalent to zero-initialization for 5464 /// the purpose of discarding a trailing portion of a 'tl' mangling. 5465 /// 5466 /// Note that this is not in general equivalent to determining whether the 5467 /// value has an all-zeroes bit pattern. 5468 static bool isZeroInitialized(QualType T, const APValue &V) { 5469 // FIXME: mangleValueInTemplateArg has quadratic time complexity in 5470 // pathological cases due to using this, but it's a little awkward 5471 // to do this in linear time in general. 5472 switch (V.getKind()) { 5473 case APValue::None: 5474 case APValue::Indeterminate: 5475 case APValue::AddrLabelDiff: 5476 return false; 5477 5478 case APValue::Struct: { 5479 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5480 assert(RD && "unexpected type for record value"); 5481 unsigned I = 0; 5482 for (const CXXBaseSpecifier &BS : RD->bases()) { 5483 if (!isZeroInitialized(BS.getType(), V.getStructBase(I))) 5484 return false; 5485 ++I; 5486 } 5487 I = 0; 5488 for (const FieldDecl *FD : RD->fields()) { 5489 if (!FD->isUnnamedBitfield() && 5490 !isZeroInitialized(FD->getType(), V.getStructField(I))) 5491 return false; 5492 ++I; 5493 } 5494 return true; 5495 } 5496 5497 case APValue::Union: { 5498 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5499 assert(RD && "unexpected type for union value"); 5500 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any. 5501 for (const FieldDecl *FD : RD->fields()) { 5502 if (!FD->isUnnamedBitfield()) 5503 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) && 5504 isZeroInitialized(FD->getType(), V.getUnionValue()); 5505 } 5506 // If there are no fields (other than unnamed bitfields), the value is 5507 // necessarily zero-initialized. 5508 return true; 5509 } 5510 5511 case APValue::Array: { 5512 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 5513 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I) 5514 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I))) 5515 return false; 5516 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller()); 5517 } 5518 5519 case APValue::Vector: { 5520 const VectorType *VT = T->castAs<VectorType>(); 5521 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) 5522 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I))) 5523 return false; 5524 return true; 5525 } 5526 5527 case APValue::Int: 5528 return !V.getInt(); 5529 5530 case APValue::Float: 5531 return V.getFloat().isPosZero(); 5532 5533 case APValue::FixedPoint: 5534 return !V.getFixedPoint().getValue(); 5535 5536 case APValue::ComplexFloat: 5537 return V.getComplexFloatReal().isPosZero() && 5538 V.getComplexFloatImag().isPosZero(); 5539 5540 case APValue::ComplexInt: 5541 return !V.getComplexIntReal() && !V.getComplexIntImag(); 5542 5543 case APValue::LValue: 5544 return V.isNullPointer(); 5545 5546 case APValue::MemberPointer: 5547 return !V.getMemberPointerDecl(); 5548 } 5549 5550 llvm_unreachable("Unhandled APValue::ValueKind enum"); 5551 } 5552 5553 static QualType getLValueType(ASTContext &Ctx, const APValue &LV) { 5554 QualType T = LV.getLValueBase().getType(); 5555 for (APValue::LValuePathEntry E : LV.getLValuePath()) { 5556 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 5557 T = AT->getElementType(); 5558 else if (const FieldDecl *FD = 5559 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer())) 5560 T = FD->getType(); 5561 else 5562 T = Ctx.getRecordType( 5563 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer())); 5564 } 5565 return T; 5566 } 5567 5568 static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc, 5569 DiagnosticsEngine &Diags, 5570 const FieldDecl *FD) { 5571 // According to: 5572 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous 5573 // For the purposes of mangling, the name of an anonymous union is considered 5574 // to be the name of the first named data member found by a pre-order, 5575 // depth-first, declaration-order walk of the data members of the anonymous 5576 // union. 5577 5578 if (FD->getIdentifier()) 5579 return FD->getIdentifier(); 5580 5581 // The only cases where the identifer of a FieldDecl would be blank is if the 5582 // field represents an anonymous record type or if it is an unnamed bitfield. 5583 // There is no type to descend into in the case of a bitfield, so we can just 5584 // return nullptr in that case. 5585 if (FD->isBitField()) 5586 return nullptr; 5587 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 5588 5589 // Consider only the fields in declaration order, searched depth-first. We 5590 // don't care about the active member of the union, as all we are doing is 5591 // looking for a valid name. We also don't check bases, due to guidance from 5592 // the Itanium ABI folks. 5593 for (const FieldDecl *RDField : RD->fields()) { 5594 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField)) 5595 return II; 5596 } 5597 5598 // According to the Itanium ABI: If there is no such data member (i.e., if all 5599 // of the data members in the union are unnamed), then there is no way for a 5600 // program to refer to the anonymous union, and there is therefore no need to 5601 // mangle its name. However, we should diagnose this anyway. 5602 unsigned DiagID = Diags.getCustomDiagID( 5603 DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet"); 5604 Diags.Report(UnionLoc, DiagID); 5605 5606 return nullptr; 5607 } 5608 5609 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V, 5610 bool TopLevel, 5611 bool NeedExactType) { 5612 // Ignore all top-level cv-qualifiers, to match GCC. 5613 Qualifiers Quals; 5614 T = getASTContext().getUnqualifiedArrayType(T, Quals); 5615 5616 // A top-level expression that's not a primary expression is wrapped in X...E. 5617 bool IsPrimaryExpr = true; 5618 auto NotPrimaryExpr = [&] { 5619 if (TopLevel && IsPrimaryExpr) 5620 Out << 'X'; 5621 IsPrimaryExpr = false; 5622 }; 5623 5624 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63. 5625 switch (V.getKind()) { 5626 case APValue::None: 5627 case APValue::Indeterminate: 5628 Out << 'L'; 5629 mangleType(T); 5630 Out << 'E'; 5631 break; 5632 5633 case APValue::AddrLabelDiff: 5634 llvm_unreachable("unexpected value kind in template argument"); 5635 5636 case APValue::Struct: { 5637 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5638 assert(RD && "unexpected type for record value"); 5639 5640 // Drop trailing zero-initialized elements. 5641 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->field_begin(), 5642 RD->field_end()); 5643 while ( 5644 !Fields.empty() && 5645 (Fields.back()->isUnnamedBitfield() || 5646 isZeroInitialized(Fields.back()->getType(), 5647 V.getStructField(Fields.back()->getFieldIndex())))) { 5648 Fields.pop_back(); 5649 } 5650 llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end()); 5651 if (Fields.empty()) { 5652 while (!Bases.empty() && 5653 isZeroInitialized(Bases.back().getType(), 5654 V.getStructBase(Bases.size() - 1))) 5655 Bases = Bases.drop_back(); 5656 } 5657 5658 // <expression> ::= tl <type> <braced-expression>* E 5659 NotPrimaryExpr(); 5660 Out << "tl"; 5661 mangleType(T); 5662 for (unsigned I = 0, N = Bases.size(); I != N; ++I) 5663 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false); 5664 for (unsigned I = 0, N = Fields.size(); I != N; ++I) { 5665 if (Fields[I]->isUnnamedBitfield()) 5666 continue; 5667 mangleValueInTemplateArg(Fields[I]->getType(), 5668 V.getStructField(Fields[I]->getFieldIndex()), 5669 false); 5670 } 5671 Out << 'E'; 5672 break; 5673 } 5674 5675 case APValue::Union: { 5676 assert(T->getAsCXXRecordDecl() && "unexpected type for union value"); 5677 const FieldDecl *FD = V.getUnionField(); 5678 5679 if (!FD) { 5680 Out << 'L'; 5681 mangleType(T); 5682 Out << 'E'; 5683 break; 5684 } 5685 5686 // <braced-expression> ::= di <field source-name> <braced-expression> 5687 NotPrimaryExpr(); 5688 Out << "tl"; 5689 mangleType(T); 5690 if (!isZeroInitialized(T, V)) { 5691 Out << "di"; 5692 IdentifierInfo *II = (getUnionInitName( 5693 T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD)); 5694 if (II) 5695 mangleSourceName(II); 5696 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false); 5697 } 5698 Out << 'E'; 5699 break; 5700 } 5701 5702 case APValue::Array: { 5703 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 5704 5705 NotPrimaryExpr(); 5706 Out << "tl"; 5707 mangleType(T); 5708 5709 // Drop trailing zero-initialized elements. 5710 unsigned N = V.getArraySize(); 5711 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) { 5712 N = V.getArrayInitializedElts(); 5713 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1))) 5714 --N; 5715 } 5716 5717 for (unsigned I = 0; I != N; ++I) { 5718 const APValue &Elem = I < V.getArrayInitializedElts() 5719 ? V.getArrayInitializedElt(I) 5720 : V.getArrayFiller(); 5721 mangleValueInTemplateArg(ElemT, Elem, false); 5722 } 5723 Out << 'E'; 5724 break; 5725 } 5726 5727 case APValue::Vector: { 5728 const VectorType *VT = T->castAs<VectorType>(); 5729 5730 NotPrimaryExpr(); 5731 Out << "tl"; 5732 mangleType(T); 5733 unsigned N = V.getVectorLength(); 5734 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1))) 5735 --N; 5736 for (unsigned I = 0; I != N; ++I) 5737 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false); 5738 Out << 'E'; 5739 break; 5740 } 5741 5742 case APValue::Int: 5743 mangleIntegerLiteral(T, V.getInt()); 5744 break; 5745 5746 case APValue::Float: 5747 mangleFloatLiteral(T, V.getFloat()); 5748 break; 5749 5750 case APValue::FixedPoint: 5751 mangleFixedPointLiteral(); 5752 break; 5753 5754 case APValue::ComplexFloat: { 5755 const ComplexType *CT = T->castAs<ComplexType>(); 5756 NotPrimaryExpr(); 5757 Out << "tl"; 5758 mangleType(T); 5759 if (!V.getComplexFloatReal().isPosZero() || 5760 !V.getComplexFloatImag().isPosZero()) 5761 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal()); 5762 if (!V.getComplexFloatImag().isPosZero()) 5763 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag()); 5764 Out << 'E'; 5765 break; 5766 } 5767 5768 case APValue::ComplexInt: { 5769 const ComplexType *CT = T->castAs<ComplexType>(); 5770 NotPrimaryExpr(); 5771 Out << "tl"; 5772 mangleType(T); 5773 if (V.getComplexIntReal().getBoolValue() || 5774 V.getComplexIntImag().getBoolValue()) 5775 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal()); 5776 if (V.getComplexIntImag().getBoolValue()) 5777 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag()); 5778 Out << 'E'; 5779 break; 5780 } 5781 5782 case APValue::LValue: { 5783 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 5784 assert((T->isPointerType() || T->isReferenceType()) && 5785 "unexpected type for LValue template arg"); 5786 5787 if (V.isNullPointer()) { 5788 mangleNullPointer(T); 5789 break; 5790 } 5791 5792 APValue::LValueBase B = V.getLValueBase(); 5793 if (!B) { 5794 // Non-standard mangling for integer cast to a pointer; this can only 5795 // occur as an extension. 5796 CharUnits Offset = V.getLValueOffset(); 5797 if (Offset.isZero()) { 5798 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as 5799 // a cast, because L <type> 0 E means something else. 5800 NotPrimaryExpr(); 5801 Out << "rc"; 5802 mangleType(T); 5803 Out << "Li0E"; 5804 if (TopLevel) 5805 Out << 'E'; 5806 } else { 5807 Out << "L"; 5808 mangleType(T); 5809 Out << Offset.getQuantity() << 'E'; 5810 } 5811 break; 5812 } 5813 5814 ASTContext &Ctx = Context.getASTContext(); 5815 5816 enum { Base, Offset, Path } Kind; 5817 if (!V.hasLValuePath()) { 5818 // Mangle as (T*)((char*)&base + N). 5819 if (T->isReferenceType()) { 5820 NotPrimaryExpr(); 5821 Out << "decvP"; 5822 mangleType(T->getPointeeType()); 5823 } else { 5824 NotPrimaryExpr(); 5825 Out << "cv"; 5826 mangleType(T); 5827 } 5828 Out << "plcvPcad"; 5829 Kind = Offset; 5830 } else { 5831 if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) { 5832 NotPrimaryExpr(); 5833 // A final conversion to the template parameter's type is usually 5834 // folded into the 'so' mangling, but we can't do that for 'void*' 5835 // parameters without introducing collisions. 5836 if (NeedExactType && T->isVoidPointerType()) { 5837 Out << "cv"; 5838 mangleType(T); 5839 } 5840 if (T->isPointerType()) 5841 Out << "ad"; 5842 Out << "so"; 5843 mangleType(T->isVoidPointerType() 5844 ? getLValueType(Ctx, V).getUnqualifiedType() 5845 : T->getPointeeType()); 5846 Kind = Path; 5847 } else { 5848 if (NeedExactType && 5849 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) && 5850 Ctx.getLangOpts().getClangABICompat() > 5851 LangOptions::ClangABI::Ver11) { 5852 NotPrimaryExpr(); 5853 Out << "cv"; 5854 mangleType(T); 5855 } 5856 if (T->isPointerType()) { 5857 NotPrimaryExpr(); 5858 Out << "ad"; 5859 } 5860 Kind = Base; 5861 } 5862 } 5863 5864 QualType TypeSoFar = B.getType(); 5865 if (auto *VD = B.dyn_cast<const ValueDecl*>()) { 5866 Out << 'L'; 5867 mangle(VD); 5868 Out << 'E'; 5869 } else if (auto *E = B.dyn_cast<const Expr*>()) { 5870 NotPrimaryExpr(); 5871 mangleExpression(E); 5872 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) { 5873 NotPrimaryExpr(); 5874 Out << "ti"; 5875 mangleType(QualType(TI.getType(), 0)); 5876 } else { 5877 // We should never see dynamic allocations here. 5878 llvm_unreachable("unexpected lvalue base kind in template argument"); 5879 } 5880 5881 switch (Kind) { 5882 case Base: 5883 break; 5884 5885 case Offset: 5886 Out << 'L'; 5887 mangleType(Ctx.getPointerDiffType()); 5888 mangleNumber(V.getLValueOffset().getQuantity()); 5889 Out << 'E'; 5890 break; 5891 5892 case Path: 5893 // <expression> ::= so <referent type> <expr> [<offset number>] 5894 // <union-selector>* [p] E 5895 if (!V.getLValueOffset().isZero()) 5896 mangleNumber(V.getLValueOffset().getQuantity()); 5897 5898 // We model a past-the-end array pointer as array indexing with index N, 5899 // not with the "past the end" flag. Compensate for that. 5900 bool OnePastTheEnd = V.isLValueOnePastTheEnd(); 5901 5902 for (APValue::LValuePathEntry E : V.getLValuePath()) { 5903 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) { 5904 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5905 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex(); 5906 TypeSoFar = AT->getElementType(); 5907 } else { 5908 const Decl *D = E.getAsBaseOrMember().getPointer(); 5909 if (auto *FD = dyn_cast<FieldDecl>(D)) { 5910 // <union-selector> ::= _ <number> 5911 if (FD->getParent()->isUnion()) { 5912 Out << '_'; 5913 if (FD->getFieldIndex()) 5914 Out << (FD->getFieldIndex() - 1); 5915 } 5916 TypeSoFar = FD->getType(); 5917 } else { 5918 TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D)); 5919 } 5920 } 5921 } 5922 5923 if (OnePastTheEnd) 5924 Out << 'p'; 5925 Out << 'E'; 5926 break; 5927 } 5928 5929 break; 5930 } 5931 5932 case APValue::MemberPointer: 5933 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 5934 if (!V.getMemberPointerDecl()) { 5935 mangleNullPointer(T); 5936 break; 5937 } 5938 5939 ASTContext &Ctx = Context.getASTContext(); 5940 5941 NotPrimaryExpr(); 5942 if (!V.getMemberPointerPath().empty()) { 5943 Out << "mc"; 5944 mangleType(T); 5945 } else if (NeedExactType && 5946 !Ctx.hasSameType( 5947 T->castAs<MemberPointerType>()->getPointeeType(), 5948 V.getMemberPointerDecl()->getType()) && 5949 Ctx.getLangOpts().getClangABICompat() > 5950 LangOptions::ClangABI::Ver11) { 5951 Out << "cv"; 5952 mangleType(T); 5953 } 5954 Out << "adL"; 5955 mangle(V.getMemberPointerDecl()); 5956 Out << 'E'; 5957 if (!V.getMemberPointerPath().empty()) { 5958 CharUnits Offset = 5959 Context.getASTContext().getMemberPointerPathAdjustment(V); 5960 if (!Offset.isZero()) 5961 mangleNumber(Offset.getQuantity()); 5962 Out << 'E'; 5963 } 5964 break; 5965 } 5966 5967 if (TopLevel && !IsPrimaryExpr) 5968 Out << 'E'; 5969 } 5970 5971 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) { 5972 // <template-param> ::= T_ # first template parameter 5973 // ::= T <parameter-2 non-negative number> _ 5974 // ::= TL <L-1 non-negative number> __ 5975 // ::= TL <L-1 non-negative number> _ 5976 // <parameter-2 non-negative number> _ 5977 // 5978 // The latter two manglings are from a proposal here: 5979 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117 5980 Out << 'T'; 5981 if (Depth != 0) 5982 Out << 'L' << (Depth - 1) << '_'; 5983 if (Index != 0) 5984 Out << (Index - 1); 5985 Out << '_'; 5986 } 5987 5988 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 5989 if (SeqID == 0) { 5990 // Nothing. 5991 } else if (SeqID == 1) { 5992 Out << '0'; 5993 } else { 5994 SeqID--; 5995 5996 // <seq-id> is encoded in base-36, using digits and upper case letters. 5997 char Buffer[7]; // log(2**32) / log(36) ~= 7 5998 MutableArrayRef<char> BufferRef(Buffer); 5999 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 6000 6001 for (; SeqID != 0; SeqID /= 36) { 6002 unsigned C = SeqID % 36; 6003 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 6004 } 6005 6006 Out.write(I.base(), I - BufferRef.rbegin()); 6007 } 6008 Out << '_'; 6009 } 6010 6011 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 6012 bool result = mangleSubstitution(tname); 6013 assert(result && "no existing substitution for template name"); 6014 (void) result; 6015 } 6016 6017 // <substitution> ::= S <seq-id> _ 6018 // ::= S_ 6019 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 6020 // Try one of the standard substitutions first. 6021 if (mangleStandardSubstitution(ND)) 6022 return true; 6023 6024 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 6025 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 6026 } 6027 6028 bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) { 6029 assert(NNS->getKind() == NestedNameSpecifier::Identifier && 6030 "mangleSubstitution(NestedNameSpecifier *) is only used for " 6031 "identifier nested name specifiers."); 6032 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS); 6033 return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS)); 6034 } 6035 6036 /// Determine whether the given type has any qualifiers that are relevant for 6037 /// substitutions. 6038 static bool hasMangledSubstitutionQualifiers(QualType T) { 6039 Qualifiers Qs = T.getQualifiers(); 6040 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned(); 6041 } 6042 6043 bool CXXNameMangler::mangleSubstitution(QualType T) { 6044 if (!hasMangledSubstitutionQualifiers(T)) { 6045 if (const RecordType *RT = T->getAs<RecordType>()) 6046 return mangleSubstitution(RT->getDecl()); 6047 } 6048 6049 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 6050 6051 return mangleSubstitution(TypePtr); 6052 } 6053 6054 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 6055 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 6056 return mangleSubstitution(TD); 6057 6058 Template = Context.getASTContext().getCanonicalTemplateName(Template); 6059 return mangleSubstitution( 6060 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 6061 } 6062 6063 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 6064 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 6065 if (I == Substitutions.end()) 6066 return false; 6067 6068 unsigned SeqID = I->second; 6069 Out << 'S'; 6070 mangleSeqID(SeqID); 6071 6072 return true; 6073 } 6074 6075 /// Returns whether S is a template specialization of std::Name with a single 6076 /// argument of type A. 6077 bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name, 6078 QualType A) { 6079 if (S.isNull()) 6080 return false; 6081 6082 const RecordType *RT = S->getAs<RecordType>(); 6083 if (!RT) 6084 return false; 6085 6086 const ClassTemplateSpecializationDecl *SD = 6087 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6088 if (!SD || !SD->getIdentifier()->isStr(Name)) 6089 return false; 6090 6091 if (!isStdNamespace(Context.getEffectiveDeclContext(SD))) 6092 return false; 6093 6094 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 6095 if (TemplateArgs.size() != 1) 6096 return false; 6097 6098 if (TemplateArgs[0].getAsType() != A) 6099 return false; 6100 6101 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6102 return false; 6103 6104 return true; 6105 } 6106 6107 /// Returns whether SD is a template specialization std::Name<char, 6108 /// std::char_traits<char> [, std::allocator<char>]> 6109 /// HasAllocator controls whether the 3rd template argument is needed. 6110 bool CXXNameMangler::isStdCharSpecialization( 6111 const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name, 6112 bool HasAllocator) { 6113 if (!SD->getIdentifier()->isStr(Name)) 6114 return false; 6115 6116 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 6117 if (TemplateArgs.size() != (HasAllocator ? 3 : 2)) 6118 return false; 6119 6120 QualType A = TemplateArgs[0].getAsType(); 6121 if (A.isNull()) 6122 return false; 6123 // Plain 'char' is named Char_S or Char_U depending on the target ABI. 6124 if (!A->isSpecificBuiltinType(BuiltinType::Char_S) && 6125 !A->isSpecificBuiltinType(BuiltinType::Char_U)) 6126 return false; 6127 6128 if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A)) 6129 return false; 6130 6131 if (HasAllocator && 6132 !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A)) 6133 return false; 6134 6135 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6136 return false; 6137 6138 return true; 6139 } 6140 6141 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 6142 // <substitution> ::= St # ::std:: 6143 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 6144 if (isStd(NS)) { 6145 Out << "St"; 6146 return true; 6147 } 6148 return false; 6149 } 6150 6151 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 6152 if (!isStdNamespace(Context.getEffectiveDeclContext(TD))) 6153 return false; 6154 6155 if (TD->getOwningModuleForLinkage()) 6156 return false; 6157 6158 // <substitution> ::= Sa # ::std::allocator 6159 if (TD->getIdentifier()->isStr("allocator")) { 6160 Out << "Sa"; 6161 return true; 6162 } 6163 6164 // <<substitution> ::= Sb # ::std::basic_string 6165 if (TD->getIdentifier()->isStr("basic_string")) { 6166 Out << "Sb"; 6167 return true; 6168 } 6169 return false; 6170 } 6171 6172 if (const ClassTemplateSpecializationDecl *SD = 6173 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 6174 if (!isStdNamespace(Context.getEffectiveDeclContext(SD))) 6175 return false; 6176 6177 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6178 return false; 6179 6180 // <substitution> ::= Ss # ::std::basic_string<char, 6181 // ::std::char_traits<char>, 6182 // ::std::allocator<char> > 6183 if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) { 6184 Out << "Ss"; 6185 return true; 6186 } 6187 6188 // <substitution> ::= Si # ::std::basic_istream<char, 6189 // ::std::char_traits<char> > 6190 if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) { 6191 Out << "Si"; 6192 return true; 6193 } 6194 6195 // <substitution> ::= So # ::std::basic_ostream<char, 6196 // ::std::char_traits<char> > 6197 if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) { 6198 Out << "So"; 6199 return true; 6200 } 6201 6202 // <substitution> ::= Sd # ::std::basic_iostream<char, 6203 // ::std::char_traits<char> > 6204 if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) { 6205 Out << "Sd"; 6206 return true; 6207 } 6208 return false; 6209 } 6210 6211 return false; 6212 } 6213 6214 void CXXNameMangler::addSubstitution(QualType T) { 6215 if (!hasMangledSubstitutionQualifiers(T)) { 6216 if (const RecordType *RT = T->getAs<RecordType>()) { 6217 addSubstitution(RT->getDecl()); 6218 return; 6219 } 6220 } 6221 6222 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 6223 addSubstitution(TypePtr); 6224 } 6225 6226 void CXXNameMangler::addSubstitution(TemplateName Template) { 6227 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 6228 return addSubstitution(TD); 6229 6230 Template = Context.getASTContext().getCanonicalTemplateName(Template); 6231 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 6232 } 6233 6234 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 6235 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 6236 Substitutions[Ptr] = SeqID++; 6237 } 6238 6239 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) { 6240 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!"); 6241 if (Other->SeqID > SeqID) { 6242 Substitutions.swap(Other->Substitutions); 6243 SeqID = Other->SeqID; 6244 } 6245 } 6246 6247 CXXNameMangler::AbiTagList 6248 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) { 6249 // When derived abi tags are disabled there is no need to make any list. 6250 if (DisableDerivedAbiTags) 6251 return AbiTagList(); 6252 6253 llvm::raw_null_ostream NullOutStream; 6254 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream); 6255 TrackReturnTypeTags.disableDerivedAbiTags(); 6256 6257 const FunctionProtoType *Proto = 6258 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 6259 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push(); 6260 TrackReturnTypeTags.FunctionTypeDepth.enterResultType(); 6261 TrackReturnTypeTags.mangleType(Proto->getReturnType()); 6262 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType(); 6263 TrackReturnTypeTags.FunctionTypeDepth.pop(saved); 6264 6265 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 6266 } 6267 6268 CXXNameMangler::AbiTagList 6269 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) { 6270 // When derived abi tags are disabled there is no need to make any list. 6271 if (DisableDerivedAbiTags) 6272 return AbiTagList(); 6273 6274 llvm::raw_null_ostream NullOutStream; 6275 CXXNameMangler TrackVariableType(*this, NullOutStream); 6276 TrackVariableType.disableDerivedAbiTags(); 6277 6278 TrackVariableType.mangleType(VD->getType()); 6279 6280 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 6281 } 6282 6283 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C, 6284 const VarDecl *VD) { 6285 llvm::raw_null_ostream NullOutStream; 6286 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true); 6287 TrackAbiTags.mangle(VD); 6288 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size(); 6289 } 6290 6291 // 6292 6293 /// Mangles the name of the declaration D and emits that name to the given 6294 /// output stream. 6295 /// 6296 /// If the declaration D requires a mangled name, this routine will emit that 6297 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 6298 /// and this routine will return false. In this case, the caller should just 6299 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 6300 /// name. 6301 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD, 6302 raw_ostream &Out) { 6303 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 6304 assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) && 6305 "Invalid mangleName() call, argument is not a variable or function!"); 6306 6307 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 6308 getASTContext().getSourceManager(), 6309 "Mangling declaration"); 6310 6311 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) { 6312 auto Type = GD.getCtorType(); 6313 CXXNameMangler Mangler(*this, Out, CD, Type); 6314 return Mangler.mangle(GlobalDecl(CD, Type)); 6315 } 6316 6317 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) { 6318 auto Type = GD.getDtorType(); 6319 CXXNameMangler Mangler(*this, Out, DD, Type); 6320 return Mangler.mangle(GlobalDecl(DD, Type)); 6321 } 6322 6323 CXXNameMangler Mangler(*this, Out, D); 6324 Mangler.mangle(GD); 6325 } 6326 6327 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 6328 raw_ostream &Out) { 6329 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 6330 Mangler.mangle(GlobalDecl(D, Ctor_Comdat)); 6331 } 6332 6333 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 6334 raw_ostream &Out) { 6335 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 6336 Mangler.mangle(GlobalDecl(D, Dtor_Comdat)); 6337 } 6338 6339 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 6340 const ThunkInfo &Thunk, 6341 raw_ostream &Out) { 6342 // <special-name> ::= T <call-offset> <base encoding> 6343 // # base is the nominal target function of thunk 6344 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 6345 // # base is the nominal target function of thunk 6346 // # first call-offset is 'this' adjustment 6347 // # second call-offset is result adjustment 6348 6349 assert(!isa<CXXDestructorDecl>(MD) && 6350 "Use mangleCXXDtor for destructor decls!"); 6351 CXXNameMangler Mangler(*this, Out); 6352 Mangler.getStream() << "_ZT"; 6353 if (!Thunk.Return.isEmpty()) 6354 Mangler.getStream() << 'c'; 6355 6356 // Mangle the 'this' pointer adjustment. 6357 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 6358 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 6359 6360 // Mangle the return pointer adjustment if there is one. 6361 if (!Thunk.Return.isEmpty()) 6362 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 6363 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 6364 6365 Mangler.mangleFunctionEncoding(MD); 6366 } 6367 6368 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 6369 const CXXDestructorDecl *DD, CXXDtorType Type, 6370 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 6371 // <special-name> ::= T <call-offset> <base encoding> 6372 // # base is the nominal target function of thunk 6373 CXXNameMangler Mangler(*this, Out, DD, Type); 6374 Mangler.getStream() << "_ZT"; 6375 6376 // Mangle the 'this' pointer adjustment. 6377 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 6378 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 6379 6380 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type)); 6381 } 6382 6383 /// Returns the mangled name for a guard variable for the passed in VarDecl. 6384 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 6385 raw_ostream &Out) { 6386 // <special-name> ::= GV <object name> # Guard variable for one-time 6387 // # initialization 6388 CXXNameMangler Mangler(*this, Out); 6389 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 6390 // be a bug that is fixed in trunk. 6391 Mangler.getStream() << "_ZGV"; 6392 Mangler.mangleName(D); 6393 } 6394 6395 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 6396 raw_ostream &Out) { 6397 // These symbols are internal in the Itanium ABI, so the names don't matter. 6398 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 6399 // avoid duplicate symbols. 6400 Out << "__cxx_global_var_init"; 6401 } 6402 6403 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 6404 raw_ostream &Out) { 6405 // Prefix the mangling of D with __dtor_. 6406 CXXNameMangler Mangler(*this, Out); 6407 Mangler.getStream() << "__dtor_"; 6408 if (shouldMangleDeclName(D)) 6409 Mangler.mangle(D); 6410 else 6411 Mangler.getStream() << D->getName(); 6412 } 6413 6414 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D, 6415 raw_ostream &Out) { 6416 // Clang generates these internal-linkage functions as part of its 6417 // implementation of the XL ABI. 6418 CXXNameMangler Mangler(*this, Out); 6419 Mangler.getStream() << "__finalize_"; 6420 if (shouldMangleDeclName(D)) 6421 Mangler.mangle(D); 6422 else 6423 Mangler.getStream() << D->getName(); 6424 } 6425 6426 void ItaniumMangleContextImpl::mangleSEHFilterExpression( 6427 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 6428 CXXNameMangler Mangler(*this, Out); 6429 Mangler.getStream() << "__filt_"; 6430 if (shouldMangleDeclName(EnclosingDecl)) 6431 Mangler.mangle(EnclosingDecl); 6432 else 6433 Mangler.getStream() << EnclosingDecl->getName(); 6434 } 6435 6436 void ItaniumMangleContextImpl::mangleSEHFinallyBlock( 6437 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 6438 CXXNameMangler Mangler(*this, Out); 6439 Mangler.getStream() << "__fin_"; 6440 if (shouldMangleDeclName(EnclosingDecl)) 6441 Mangler.mangle(EnclosingDecl); 6442 else 6443 Mangler.getStream() << EnclosingDecl->getName(); 6444 } 6445 6446 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 6447 raw_ostream &Out) { 6448 // <special-name> ::= TH <object name> 6449 CXXNameMangler Mangler(*this, Out); 6450 Mangler.getStream() << "_ZTH"; 6451 Mangler.mangleName(D); 6452 } 6453 6454 void 6455 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 6456 raw_ostream &Out) { 6457 // <special-name> ::= TW <object name> 6458 CXXNameMangler Mangler(*this, Out); 6459 Mangler.getStream() << "_ZTW"; 6460 Mangler.mangleName(D); 6461 } 6462 6463 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 6464 unsigned ManglingNumber, 6465 raw_ostream &Out) { 6466 // We match the GCC mangling here. 6467 // <special-name> ::= GR <object name> 6468 CXXNameMangler Mangler(*this, Out); 6469 Mangler.getStream() << "_ZGR"; 6470 Mangler.mangleName(D); 6471 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 6472 Mangler.mangleSeqID(ManglingNumber - 1); 6473 } 6474 6475 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 6476 raw_ostream &Out) { 6477 // <special-name> ::= TV <type> # virtual table 6478 CXXNameMangler Mangler(*this, Out); 6479 Mangler.getStream() << "_ZTV"; 6480 Mangler.mangleNameOrStandardSubstitution(RD); 6481 } 6482 6483 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 6484 raw_ostream &Out) { 6485 // <special-name> ::= TT <type> # VTT structure 6486 CXXNameMangler Mangler(*this, Out); 6487 Mangler.getStream() << "_ZTT"; 6488 Mangler.mangleNameOrStandardSubstitution(RD); 6489 } 6490 6491 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 6492 int64_t Offset, 6493 const CXXRecordDecl *Type, 6494 raw_ostream &Out) { 6495 // <special-name> ::= TC <type> <offset number> _ <base type> 6496 CXXNameMangler Mangler(*this, Out); 6497 Mangler.getStream() << "_ZTC"; 6498 Mangler.mangleNameOrStandardSubstitution(RD); 6499 Mangler.getStream() << Offset; 6500 Mangler.getStream() << '_'; 6501 Mangler.mangleNameOrStandardSubstitution(Type); 6502 } 6503 6504 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 6505 // <special-name> ::= TI <type> # typeinfo structure 6506 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 6507 CXXNameMangler Mangler(*this, Out); 6508 Mangler.getStream() << "_ZTI"; 6509 Mangler.mangleType(Ty); 6510 } 6511 6512 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 6513 raw_ostream &Out) { 6514 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 6515 CXXNameMangler Mangler(*this, Out); 6516 Mangler.getStream() << "_ZTS"; 6517 Mangler.mangleType(Ty); 6518 } 6519 6520 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 6521 mangleCXXRTTIName(Ty, Out); 6522 } 6523 6524 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 6525 llvm_unreachable("Can't mangle string literals"); 6526 } 6527 6528 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda, 6529 raw_ostream &Out) { 6530 CXXNameMangler Mangler(*this, Out); 6531 Mangler.mangleLambdaSig(Lambda); 6532 } 6533 6534 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context, 6535 DiagnosticsEngine &Diags, 6536 bool IsAux) { 6537 return new ItaniumMangleContextImpl( 6538 Context, Diags, 6539 [](ASTContext &, const NamedDecl *) -> llvm::Optional<unsigned> { 6540 return llvm::None; 6541 }, 6542 IsAux); 6543 } 6544 6545 ItaniumMangleContext * 6546 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags, 6547 DiscriminatorOverrideTy DiscriminatorOverride, 6548 bool IsAux) { 6549 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride, 6550 IsAux); 6551 } 6552