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