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