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