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