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