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