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