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