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