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