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