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