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 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ] 2305 case LangAS::ptr32_sptr: 2306 ASString = "ptr32_sptr"; 2307 break; 2308 case LangAS::ptr32_uptr: 2309 ASString = "ptr32_uptr"; 2310 break; 2311 case LangAS::ptr64: 2312 ASString = "ptr64"; 2313 break; 2314 } 2315 } 2316 if (!ASString.empty()) 2317 mangleVendorQualifier(ASString); 2318 } 2319 2320 // The ARC ownership qualifiers start with underscores. 2321 // Objective-C ARC Extension: 2322 // 2323 // <type> ::= U "__strong" 2324 // <type> ::= U "__weak" 2325 // <type> ::= U "__autoreleasing" 2326 // 2327 // Note: we emit __weak first to preserve the order as 2328 // required by the Itanium ABI. 2329 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak) 2330 mangleVendorQualifier("__weak"); 2331 2332 // __unaligned (from -fms-extensions) 2333 if (Quals.hasUnaligned()) 2334 mangleVendorQualifier("__unaligned"); 2335 2336 // Remaining ARC ownership qualifiers. 2337 switch (Quals.getObjCLifetime()) { 2338 case Qualifiers::OCL_None: 2339 break; 2340 2341 case Qualifiers::OCL_Weak: 2342 // Do nothing as we already handled this case above. 2343 break; 2344 2345 case Qualifiers::OCL_Strong: 2346 mangleVendorQualifier("__strong"); 2347 break; 2348 2349 case Qualifiers::OCL_Autoreleasing: 2350 mangleVendorQualifier("__autoreleasing"); 2351 break; 2352 2353 case Qualifiers::OCL_ExplicitNone: 2354 // The __unsafe_unretained qualifier is *not* mangled, so that 2355 // __unsafe_unretained types in ARC produce the same manglings as the 2356 // equivalent (but, naturally, unqualified) types in non-ARC, providing 2357 // better ABI compatibility. 2358 // 2359 // It's safe to do this because unqualified 'id' won't show up 2360 // in any type signatures that need to be mangled. 2361 break; 2362 } 2363 2364 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const 2365 if (Quals.hasRestrict()) 2366 Out << 'r'; 2367 if (Quals.hasVolatile()) 2368 Out << 'V'; 2369 if (Quals.hasConst()) 2370 Out << 'K'; 2371 } 2372 2373 void CXXNameMangler::mangleVendorQualifier(StringRef name) { 2374 Out << 'U' << name.size() << name; 2375 } 2376 2377 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 2378 // <ref-qualifier> ::= R # lvalue reference 2379 // ::= O # rvalue-reference 2380 switch (RefQualifier) { 2381 case RQ_None: 2382 break; 2383 2384 case RQ_LValue: 2385 Out << 'R'; 2386 break; 2387 2388 case RQ_RValue: 2389 Out << 'O'; 2390 break; 2391 } 2392 } 2393 2394 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 2395 Context.mangleObjCMethodName(MD, Out); 2396 } 2397 2398 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty, 2399 ASTContext &Ctx) { 2400 if (Quals) 2401 return true; 2402 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel)) 2403 return true; 2404 if (Ty->isOpenCLSpecificType()) 2405 return true; 2406 if (Ty->isBuiltinType()) 2407 return false; 2408 // Through to Clang 6.0, we accidentally treated undeduced auto types as 2409 // substitution candidates. 2410 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 && 2411 isa<AutoType>(Ty)) 2412 return false; 2413 return true; 2414 } 2415 2416 void CXXNameMangler::mangleType(QualType T) { 2417 // If our type is instantiation-dependent but not dependent, we mangle 2418 // it as it was written in the source, removing any top-level sugar. 2419 // Otherwise, use the canonical type. 2420 // 2421 // FIXME: This is an approximation of the instantiation-dependent name 2422 // mangling rules, since we should really be using the type as written and 2423 // augmented via semantic analysis (i.e., with implicit conversions and 2424 // default template arguments) for any instantiation-dependent type. 2425 // Unfortunately, that requires several changes to our AST: 2426 // - Instantiation-dependent TemplateSpecializationTypes will need to be 2427 // uniqued, so that we can handle substitutions properly 2428 // - Default template arguments will need to be represented in the 2429 // TemplateSpecializationType, since they need to be mangled even though 2430 // they aren't written. 2431 // - Conversions on non-type template arguments need to be expressed, since 2432 // they can affect the mangling of sizeof/alignof. 2433 // 2434 // FIXME: This is wrong when mapping to the canonical type for a dependent 2435 // type discards instantiation-dependent portions of the type, such as for: 2436 // 2437 // template<typename T, int N> void f(T (&)[sizeof(N)]); 2438 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17) 2439 // 2440 // It's also wrong in the opposite direction when instantiation-dependent, 2441 // canonically-equivalent types differ in some irrelevant portion of inner 2442 // type sugar. In such cases, we fail to form correct substitutions, eg: 2443 // 2444 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*)); 2445 // 2446 // We should instead canonicalize the non-instantiation-dependent parts, 2447 // regardless of whether the type as a whole is dependent or instantiation 2448 // dependent. 2449 if (!T->isInstantiationDependentType() || T->isDependentType()) 2450 T = T.getCanonicalType(); 2451 else { 2452 // Desugar any types that are purely sugar. 2453 do { 2454 // Don't desugar through template specialization types that aren't 2455 // type aliases. We need to mangle the template arguments as written. 2456 if (const TemplateSpecializationType *TST 2457 = dyn_cast<TemplateSpecializationType>(T)) 2458 if (!TST->isTypeAlias()) 2459 break; 2460 2461 QualType Desugared 2462 = T.getSingleStepDesugaredType(Context.getASTContext()); 2463 if (Desugared == T) 2464 break; 2465 2466 T = Desugared; 2467 } while (true); 2468 } 2469 SplitQualType split = T.split(); 2470 Qualifiers quals = split.Quals; 2471 const Type *ty = split.Ty; 2472 2473 bool isSubstitutable = 2474 isTypeSubstitutable(quals, ty, Context.getASTContext()); 2475 if (isSubstitutable && mangleSubstitution(T)) 2476 return; 2477 2478 // If we're mangling a qualified array type, push the qualifiers to 2479 // the element type. 2480 if (quals && isa<ArrayType>(T)) { 2481 ty = Context.getASTContext().getAsArrayType(T); 2482 quals = Qualifiers(); 2483 2484 // Note that we don't update T: we want to add the 2485 // substitution at the original type. 2486 } 2487 2488 if (quals || ty->isDependentAddressSpaceType()) { 2489 if (const DependentAddressSpaceType *DAST = 2490 dyn_cast<DependentAddressSpaceType>(ty)) { 2491 SplitQualType splitDAST = DAST->getPointeeType().split(); 2492 mangleQualifiers(splitDAST.Quals, DAST); 2493 mangleType(QualType(splitDAST.Ty, 0)); 2494 } else { 2495 mangleQualifiers(quals); 2496 2497 // Recurse: even if the qualified type isn't yet substitutable, 2498 // the unqualified type might be. 2499 mangleType(QualType(ty, 0)); 2500 } 2501 } else { 2502 switch (ty->getTypeClass()) { 2503 #define ABSTRACT_TYPE(CLASS, PARENT) 2504 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 2505 case Type::CLASS: \ 2506 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 2507 return; 2508 #define TYPE(CLASS, PARENT) \ 2509 case Type::CLASS: \ 2510 mangleType(static_cast<const CLASS##Type*>(ty)); \ 2511 break; 2512 #include "clang/AST/TypeNodes.inc" 2513 } 2514 } 2515 2516 // Add the substitution. 2517 if (isSubstitutable) 2518 addSubstitution(T); 2519 } 2520 2521 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) { 2522 if (!mangleStandardSubstitution(ND)) 2523 mangleName(ND); 2524 } 2525 2526 void CXXNameMangler::mangleType(const BuiltinType *T) { 2527 // <type> ::= <builtin-type> 2528 // <builtin-type> ::= v # void 2529 // ::= w # wchar_t 2530 // ::= b # bool 2531 // ::= c # char 2532 // ::= a # signed char 2533 // ::= h # unsigned char 2534 // ::= s # short 2535 // ::= t # unsigned short 2536 // ::= i # int 2537 // ::= j # unsigned int 2538 // ::= l # long 2539 // ::= m # unsigned long 2540 // ::= x # long long, __int64 2541 // ::= y # unsigned long long, __int64 2542 // ::= n # __int128 2543 // ::= o # unsigned __int128 2544 // ::= f # float 2545 // ::= d # double 2546 // ::= e # long double, __float80 2547 // ::= g # __float128 2548 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) 2549 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) 2550 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) 2551 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 2552 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits); 2553 // ::= Di # char32_t 2554 // ::= Ds # char16_t 2555 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 2556 // ::= u <source-name> # vendor extended type 2557 std::string type_name; 2558 switch (T->getKind()) { 2559 case BuiltinType::Void: 2560 Out << 'v'; 2561 break; 2562 case BuiltinType::Bool: 2563 Out << 'b'; 2564 break; 2565 case BuiltinType::Char_U: 2566 case BuiltinType::Char_S: 2567 Out << 'c'; 2568 break; 2569 case BuiltinType::UChar: 2570 Out << 'h'; 2571 break; 2572 case BuiltinType::UShort: 2573 Out << 't'; 2574 break; 2575 case BuiltinType::UInt: 2576 Out << 'j'; 2577 break; 2578 case BuiltinType::ULong: 2579 Out << 'm'; 2580 break; 2581 case BuiltinType::ULongLong: 2582 Out << 'y'; 2583 break; 2584 case BuiltinType::UInt128: 2585 Out << 'o'; 2586 break; 2587 case BuiltinType::SChar: 2588 Out << 'a'; 2589 break; 2590 case BuiltinType::WChar_S: 2591 case BuiltinType::WChar_U: 2592 Out << 'w'; 2593 break; 2594 case BuiltinType::Char8: 2595 Out << "Du"; 2596 break; 2597 case BuiltinType::Char16: 2598 Out << "Ds"; 2599 break; 2600 case BuiltinType::Char32: 2601 Out << "Di"; 2602 break; 2603 case BuiltinType::Short: 2604 Out << 's'; 2605 break; 2606 case BuiltinType::Int: 2607 Out << 'i'; 2608 break; 2609 case BuiltinType::Long: 2610 Out << 'l'; 2611 break; 2612 case BuiltinType::LongLong: 2613 Out << 'x'; 2614 break; 2615 case BuiltinType::Int128: 2616 Out << 'n'; 2617 break; 2618 case BuiltinType::Float16: 2619 Out << "DF16_"; 2620 break; 2621 case BuiltinType::ShortAccum: 2622 case BuiltinType::Accum: 2623 case BuiltinType::LongAccum: 2624 case BuiltinType::UShortAccum: 2625 case BuiltinType::UAccum: 2626 case BuiltinType::ULongAccum: 2627 case BuiltinType::ShortFract: 2628 case BuiltinType::Fract: 2629 case BuiltinType::LongFract: 2630 case BuiltinType::UShortFract: 2631 case BuiltinType::UFract: 2632 case BuiltinType::ULongFract: 2633 case BuiltinType::SatShortAccum: 2634 case BuiltinType::SatAccum: 2635 case BuiltinType::SatLongAccum: 2636 case BuiltinType::SatUShortAccum: 2637 case BuiltinType::SatUAccum: 2638 case BuiltinType::SatULongAccum: 2639 case BuiltinType::SatShortFract: 2640 case BuiltinType::SatFract: 2641 case BuiltinType::SatLongFract: 2642 case BuiltinType::SatUShortFract: 2643 case BuiltinType::SatUFract: 2644 case BuiltinType::SatULongFract: 2645 llvm_unreachable("Fixed point types are disabled for c++"); 2646 case BuiltinType::Half: 2647 Out << "Dh"; 2648 break; 2649 case BuiltinType::Float: 2650 Out << 'f'; 2651 break; 2652 case BuiltinType::Double: 2653 Out << 'd'; 2654 break; 2655 case BuiltinType::LongDouble: { 2656 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP && 2657 getASTContext().getLangOpts().OpenMPIsDevice 2658 ? getASTContext().getAuxTargetInfo() 2659 : &getASTContext().getTargetInfo(); 2660 Out << TI->getLongDoubleMangling(); 2661 break; 2662 } 2663 case BuiltinType::Float128: { 2664 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP && 2665 getASTContext().getLangOpts().OpenMPIsDevice 2666 ? getASTContext().getAuxTargetInfo() 2667 : &getASTContext().getTargetInfo(); 2668 Out << TI->getFloat128Mangling(); 2669 break; 2670 } 2671 case BuiltinType::NullPtr: 2672 Out << "Dn"; 2673 break; 2674 2675 #define BUILTIN_TYPE(Id, SingletonId) 2676 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2677 case BuiltinType::Id: 2678 #include "clang/AST/BuiltinTypes.def" 2679 case BuiltinType::Dependent: 2680 if (!NullOut) 2681 llvm_unreachable("mangling a placeholder type"); 2682 break; 2683 case BuiltinType::ObjCId: 2684 Out << "11objc_object"; 2685 break; 2686 case BuiltinType::ObjCClass: 2687 Out << "10objc_class"; 2688 break; 2689 case BuiltinType::ObjCSel: 2690 Out << "13objc_selector"; 2691 break; 2692 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2693 case BuiltinType::Id: \ 2694 type_name = "ocl_" #ImgType "_" #Suffix; \ 2695 Out << type_name.size() << type_name; \ 2696 break; 2697 #include "clang/Basic/OpenCLImageTypes.def" 2698 case BuiltinType::OCLSampler: 2699 Out << "11ocl_sampler"; 2700 break; 2701 case BuiltinType::OCLEvent: 2702 Out << "9ocl_event"; 2703 break; 2704 case BuiltinType::OCLClkEvent: 2705 Out << "12ocl_clkevent"; 2706 break; 2707 case BuiltinType::OCLQueue: 2708 Out << "9ocl_queue"; 2709 break; 2710 case BuiltinType::OCLReserveID: 2711 Out << "13ocl_reserveid"; 2712 break; 2713 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2714 case BuiltinType::Id: \ 2715 type_name = "ocl_" #ExtType; \ 2716 Out << type_name.size() << type_name; \ 2717 break; 2718 #include "clang/Basic/OpenCLExtensionTypes.def" 2719 // The SVE types are effectively target-specific. The mangling scheme 2720 // is defined in the appendices to the Procedure Call Standard for the 2721 // Arm Architecture. 2722 #define SVE_TYPE(Name, Id, SingletonId) \ 2723 case BuiltinType::Id: \ 2724 type_name = Name; \ 2725 Out << 'u' << type_name.size() << type_name; \ 2726 break; 2727 #include "clang/Basic/AArch64SVEACLETypes.def" 2728 } 2729 } 2730 2731 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) { 2732 switch (CC) { 2733 case CC_C: 2734 return ""; 2735 2736 case CC_X86VectorCall: 2737 case CC_X86Pascal: 2738 case CC_X86RegCall: 2739 case CC_AAPCS: 2740 case CC_AAPCS_VFP: 2741 case CC_AArch64VectorCall: 2742 case CC_IntelOclBicc: 2743 case CC_SpirFunction: 2744 case CC_OpenCLKernel: 2745 case CC_PreserveMost: 2746 case CC_PreserveAll: 2747 // FIXME: we should be mangling all of the above. 2748 return ""; 2749 2750 case CC_X86ThisCall: 2751 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is 2752 // used explicitly. At this point, we don't have that much information in 2753 // the AST, since clang tends to bake the convention into the canonical 2754 // function type. thiscall only rarely used explicitly, so don't mangle it 2755 // for now. 2756 return ""; 2757 2758 case CC_X86StdCall: 2759 return "stdcall"; 2760 case CC_X86FastCall: 2761 return "fastcall"; 2762 case CC_X86_64SysV: 2763 return "sysv_abi"; 2764 case CC_Win64: 2765 return "ms_abi"; 2766 case CC_Swift: 2767 return "swiftcall"; 2768 } 2769 llvm_unreachable("bad calling convention"); 2770 } 2771 2772 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) { 2773 // Fast path. 2774 if (T->getExtInfo() == FunctionType::ExtInfo()) 2775 return; 2776 2777 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 2778 // This will get more complicated in the future if we mangle other 2779 // things here; but for now, since we mangle ns_returns_retained as 2780 // a qualifier on the result type, we can get away with this: 2781 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC()); 2782 if (!CCQualifier.empty()) 2783 mangleVendorQualifier(CCQualifier); 2784 2785 // FIXME: regparm 2786 // FIXME: noreturn 2787 } 2788 2789 void 2790 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { 2791 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 2792 2793 // Note that these are *not* substitution candidates. Demanglers might 2794 // have trouble with this if the parameter type is fully substituted. 2795 2796 switch (PI.getABI()) { 2797 case ParameterABI::Ordinary: 2798 break; 2799 2800 // All of these start with "swift", so they come before "ns_consumed". 2801 case ParameterABI::SwiftContext: 2802 case ParameterABI::SwiftErrorResult: 2803 case ParameterABI::SwiftIndirectResult: 2804 mangleVendorQualifier(getParameterABISpelling(PI.getABI())); 2805 break; 2806 } 2807 2808 if (PI.isConsumed()) 2809 mangleVendorQualifier("ns_consumed"); 2810 2811 if (PI.isNoEscape()) 2812 mangleVendorQualifier("noescape"); 2813 } 2814 2815 // <type> ::= <function-type> 2816 // <function-type> ::= [<CV-qualifiers>] F [Y] 2817 // <bare-function-type> [<ref-qualifier>] E 2818 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 2819 mangleExtFunctionInfo(T); 2820 2821 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 2822 // e.g. "const" in "int (A::*)() const". 2823 mangleQualifiers(T->getMethodQuals()); 2824 2825 // Mangle instantiation-dependent exception-specification, if present, 2826 // per cxx-abi-dev proposal on 2016-10-11. 2827 if (T->hasInstantiationDependentExceptionSpec()) { 2828 if (isComputedNoexcept(T->getExceptionSpecType())) { 2829 Out << "DO"; 2830 mangleExpression(T->getNoexceptExpr()); 2831 Out << "E"; 2832 } else { 2833 assert(T->getExceptionSpecType() == EST_Dynamic); 2834 Out << "Dw"; 2835 for (auto ExceptTy : T->exceptions()) 2836 mangleType(ExceptTy); 2837 Out << "E"; 2838 } 2839 } else if (T->isNothrow()) { 2840 Out << "Do"; 2841 } 2842 2843 Out << 'F'; 2844 2845 // FIXME: We don't have enough information in the AST to produce the 'Y' 2846 // encoding for extern "C" function types. 2847 mangleBareFunctionType(T, /*MangleReturnType=*/true); 2848 2849 // Mangle the ref-qualifier, if present. 2850 mangleRefQualifier(T->getRefQualifier()); 2851 2852 Out << 'E'; 2853 } 2854 2855 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 2856 // Function types without prototypes can arise when mangling a function type 2857 // within an overloadable function in C. We mangle these as the absence of any 2858 // parameter types (not even an empty parameter list). 2859 Out << 'F'; 2860 2861 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 2862 2863 FunctionTypeDepth.enterResultType(); 2864 mangleType(T->getReturnType()); 2865 FunctionTypeDepth.leaveResultType(); 2866 2867 FunctionTypeDepth.pop(saved); 2868 Out << 'E'; 2869 } 2870 2871 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto, 2872 bool MangleReturnType, 2873 const FunctionDecl *FD) { 2874 // Record that we're in a function type. See mangleFunctionParam 2875 // for details on what we're trying to achieve here. 2876 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 2877 2878 // <bare-function-type> ::= <signature type>+ 2879 if (MangleReturnType) { 2880 FunctionTypeDepth.enterResultType(); 2881 2882 // Mangle ns_returns_retained as an order-sensitive qualifier here. 2883 if (Proto->getExtInfo().getProducesResult() && FD == nullptr) 2884 mangleVendorQualifier("ns_returns_retained"); 2885 2886 // Mangle the return type without any direct ARC ownership qualifiers. 2887 QualType ReturnTy = Proto->getReturnType(); 2888 if (ReturnTy.getObjCLifetime()) { 2889 auto SplitReturnTy = ReturnTy.split(); 2890 SplitReturnTy.Quals.removeObjCLifetime(); 2891 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy); 2892 } 2893 mangleType(ReturnTy); 2894 2895 FunctionTypeDepth.leaveResultType(); 2896 } 2897 2898 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 2899 // <builtin-type> ::= v # void 2900 Out << 'v'; 2901 2902 FunctionTypeDepth.pop(saved); 2903 return; 2904 } 2905 2906 assert(!FD || FD->getNumParams() == Proto->getNumParams()); 2907 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 2908 // Mangle extended parameter info as order-sensitive qualifiers here. 2909 if (Proto->hasExtParameterInfos() && FD == nullptr) { 2910 mangleExtParameterInfo(Proto->getExtParameterInfo(I)); 2911 } 2912 2913 // Mangle the type. 2914 QualType ParamTy = Proto->getParamType(I); 2915 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy)); 2916 2917 if (FD) { 2918 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) { 2919 // Attr can only take 1 character, so we can hardcode the length below. 2920 assert(Attr->getType() <= 9 && Attr->getType() >= 0); 2921 if (Attr->isDynamic()) 2922 Out << "U25pass_dynamic_object_size" << Attr->getType(); 2923 else 2924 Out << "U17pass_object_size" << Attr->getType(); 2925 } 2926 } 2927 } 2928 2929 FunctionTypeDepth.pop(saved); 2930 2931 // <builtin-type> ::= z # ellipsis 2932 if (Proto->isVariadic()) 2933 Out << 'z'; 2934 } 2935 2936 // <type> ::= <class-enum-type> 2937 // <class-enum-type> ::= <name> 2938 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 2939 mangleName(T->getDecl()); 2940 } 2941 2942 // <type> ::= <class-enum-type> 2943 // <class-enum-type> ::= <name> 2944 void CXXNameMangler::mangleType(const EnumType *T) { 2945 mangleType(static_cast<const TagType*>(T)); 2946 } 2947 void CXXNameMangler::mangleType(const RecordType *T) { 2948 mangleType(static_cast<const TagType*>(T)); 2949 } 2950 void CXXNameMangler::mangleType(const TagType *T) { 2951 mangleName(T->getDecl()); 2952 } 2953 2954 // <type> ::= <array-type> 2955 // <array-type> ::= A <positive dimension number> _ <element type> 2956 // ::= A [<dimension expression>] _ <element type> 2957 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 2958 Out << 'A' << T->getSize() << '_'; 2959 mangleType(T->getElementType()); 2960 } 2961 void CXXNameMangler::mangleType(const VariableArrayType *T) { 2962 Out << 'A'; 2963 // decayed vla types (size 0) will just be skipped. 2964 if (T->getSizeExpr()) 2965 mangleExpression(T->getSizeExpr()); 2966 Out << '_'; 2967 mangleType(T->getElementType()); 2968 } 2969 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 2970 Out << 'A'; 2971 mangleExpression(T->getSizeExpr()); 2972 Out << '_'; 2973 mangleType(T->getElementType()); 2974 } 2975 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 2976 Out << "A_"; 2977 mangleType(T->getElementType()); 2978 } 2979 2980 // <type> ::= <pointer-to-member-type> 2981 // <pointer-to-member-type> ::= M <class type> <member type> 2982 void CXXNameMangler::mangleType(const MemberPointerType *T) { 2983 Out << 'M'; 2984 mangleType(QualType(T->getClass(), 0)); 2985 QualType PointeeType = T->getPointeeType(); 2986 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 2987 mangleType(FPT); 2988 2989 // Itanium C++ ABI 5.1.8: 2990 // 2991 // The type of a non-static member function is considered to be different, 2992 // for the purposes of substitution, from the type of a namespace-scope or 2993 // static member function whose type appears similar. The types of two 2994 // non-static member functions are considered to be different, for the 2995 // purposes of substitution, if the functions are members of different 2996 // classes. In other words, for the purposes of substitution, the class of 2997 // which the function is a member is considered part of the type of 2998 // function. 2999 3000 // Given that we already substitute member function pointers as a 3001 // whole, the net effect of this rule is just to unconditionally 3002 // suppress substitution on the function type in a member pointer. 3003 // We increment the SeqID here to emulate adding an entry to the 3004 // substitution table. 3005 ++SeqID; 3006 } else 3007 mangleType(PointeeType); 3008 } 3009 3010 // <type> ::= <template-param> 3011 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 3012 mangleTemplateParameter(T->getDepth(), T->getIndex()); 3013 } 3014 3015 // <type> ::= <template-param> 3016 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 3017 // FIXME: not clear how to mangle this! 3018 // template <class T...> class A { 3019 // template <class U...> void foo(T(*)(U) x...); 3020 // }; 3021 Out << "_SUBSTPACK_"; 3022 } 3023 3024 // <type> ::= P <type> # pointer-to 3025 void CXXNameMangler::mangleType(const PointerType *T) { 3026 Out << 'P'; 3027 mangleType(T->getPointeeType()); 3028 } 3029 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 3030 Out << 'P'; 3031 mangleType(T->getPointeeType()); 3032 } 3033 3034 // <type> ::= R <type> # reference-to 3035 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 3036 Out << 'R'; 3037 mangleType(T->getPointeeType()); 3038 } 3039 3040 // <type> ::= O <type> # rvalue reference-to (C++0x) 3041 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 3042 Out << 'O'; 3043 mangleType(T->getPointeeType()); 3044 } 3045 3046 // <type> ::= C <type> # complex pair (C 2000) 3047 void CXXNameMangler::mangleType(const ComplexType *T) { 3048 Out << 'C'; 3049 mangleType(T->getElementType()); 3050 } 3051 3052 // ARM's ABI for Neon vector types specifies that they should be mangled as 3053 // if they are structs (to match ARM's initial implementation). The 3054 // vector type must be one of the special types predefined by ARM. 3055 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 3056 QualType EltType = T->getElementType(); 3057 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3058 const char *EltName = nullptr; 3059 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3060 switch (cast<BuiltinType>(EltType)->getKind()) { 3061 case BuiltinType::SChar: 3062 case BuiltinType::UChar: 3063 EltName = "poly8_t"; 3064 break; 3065 case BuiltinType::Short: 3066 case BuiltinType::UShort: 3067 EltName = "poly16_t"; 3068 break; 3069 case BuiltinType::ULongLong: 3070 EltName = "poly64_t"; 3071 break; 3072 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 3073 } 3074 } else { 3075 switch (cast<BuiltinType>(EltType)->getKind()) { 3076 case BuiltinType::SChar: EltName = "int8_t"; break; 3077 case BuiltinType::UChar: EltName = "uint8_t"; break; 3078 case BuiltinType::Short: EltName = "int16_t"; break; 3079 case BuiltinType::UShort: EltName = "uint16_t"; break; 3080 case BuiltinType::Int: EltName = "int32_t"; break; 3081 case BuiltinType::UInt: EltName = "uint32_t"; break; 3082 case BuiltinType::LongLong: EltName = "int64_t"; break; 3083 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 3084 case BuiltinType::Double: EltName = "float64_t"; break; 3085 case BuiltinType::Float: EltName = "float32_t"; break; 3086 case BuiltinType::Half: EltName = "float16_t";break; 3087 default: 3088 llvm_unreachable("unexpected Neon vector element type"); 3089 } 3090 } 3091 const char *BaseName = nullptr; 3092 unsigned BitSize = (T->getNumElements() * 3093 getASTContext().getTypeSize(EltType)); 3094 if (BitSize == 64) 3095 BaseName = "__simd64_"; 3096 else { 3097 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 3098 BaseName = "__simd128_"; 3099 } 3100 Out << strlen(BaseName) + strlen(EltName); 3101 Out << BaseName << EltName; 3102 } 3103 3104 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) { 3105 DiagnosticsEngine &Diags = Context.getDiags(); 3106 unsigned DiagID = Diags.getCustomDiagID( 3107 DiagnosticsEngine::Error, 3108 "cannot mangle this dependent neon vector type yet"); 3109 Diags.Report(T->getAttributeLoc(), DiagID); 3110 } 3111 3112 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 3113 switch (EltType->getKind()) { 3114 case BuiltinType::SChar: 3115 return "Int8"; 3116 case BuiltinType::Short: 3117 return "Int16"; 3118 case BuiltinType::Int: 3119 return "Int32"; 3120 case BuiltinType::Long: 3121 case BuiltinType::LongLong: 3122 return "Int64"; 3123 case BuiltinType::UChar: 3124 return "Uint8"; 3125 case BuiltinType::UShort: 3126 return "Uint16"; 3127 case BuiltinType::UInt: 3128 return "Uint32"; 3129 case BuiltinType::ULong: 3130 case BuiltinType::ULongLong: 3131 return "Uint64"; 3132 case BuiltinType::Half: 3133 return "Float16"; 3134 case BuiltinType::Float: 3135 return "Float32"; 3136 case BuiltinType::Double: 3137 return "Float64"; 3138 default: 3139 llvm_unreachable("Unexpected vector element base type"); 3140 } 3141 } 3142 3143 // AArch64's ABI for Neon vector types specifies that they should be mangled as 3144 // the equivalent internal name. The vector type must be one of the special 3145 // types predefined by ARM. 3146 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 3147 QualType EltType = T->getElementType(); 3148 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3149 unsigned BitSize = 3150 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 3151 (void)BitSize; // Silence warning. 3152 3153 assert((BitSize == 64 || BitSize == 128) && 3154 "Neon vector type not 64 or 128 bits"); 3155 3156 StringRef EltName; 3157 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3158 switch (cast<BuiltinType>(EltType)->getKind()) { 3159 case BuiltinType::UChar: 3160 EltName = "Poly8"; 3161 break; 3162 case BuiltinType::UShort: 3163 EltName = "Poly16"; 3164 break; 3165 case BuiltinType::ULong: 3166 case BuiltinType::ULongLong: 3167 EltName = "Poly64"; 3168 break; 3169 default: 3170 llvm_unreachable("unexpected Neon polynomial vector element type"); 3171 } 3172 } else 3173 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 3174 3175 std::string TypeName = 3176 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str(); 3177 Out << TypeName.length() << TypeName; 3178 } 3179 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) { 3180 DiagnosticsEngine &Diags = Context.getDiags(); 3181 unsigned DiagID = Diags.getCustomDiagID( 3182 DiagnosticsEngine::Error, 3183 "cannot mangle this dependent neon vector type yet"); 3184 Diags.Report(T->getAttributeLoc(), DiagID); 3185 } 3186 3187 // GNU extension: vector types 3188 // <type> ::= <vector-type> 3189 // <vector-type> ::= Dv <positive dimension number> _ 3190 // <extended element type> 3191 // ::= Dv [<dimension expression>] _ <element type> 3192 // <extended element type> ::= <element type> 3193 // ::= p # AltiVec vector pixel 3194 // ::= b # Altivec vector bool 3195 void CXXNameMangler::mangleType(const VectorType *T) { 3196 if ((T->getVectorKind() == VectorType::NeonVector || 3197 T->getVectorKind() == VectorType::NeonPolyVector)) { 3198 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3199 llvm::Triple::ArchType Arch = 3200 getASTContext().getTargetInfo().getTriple().getArch(); 3201 if ((Arch == llvm::Triple::aarch64 || 3202 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 3203 mangleAArch64NeonVectorType(T); 3204 else 3205 mangleNeonVectorType(T); 3206 return; 3207 } 3208 Out << "Dv" << T->getNumElements() << '_'; 3209 if (T->getVectorKind() == VectorType::AltiVecPixel) 3210 Out << 'p'; 3211 else if (T->getVectorKind() == VectorType::AltiVecBool) 3212 Out << 'b'; 3213 else 3214 mangleType(T->getElementType()); 3215 } 3216 3217 void CXXNameMangler::mangleType(const DependentVectorType *T) { 3218 if ((T->getVectorKind() == VectorType::NeonVector || 3219 T->getVectorKind() == VectorType::NeonPolyVector)) { 3220 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3221 llvm::Triple::ArchType Arch = 3222 getASTContext().getTargetInfo().getTriple().getArch(); 3223 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) && 3224 !Target.isOSDarwin()) 3225 mangleAArch64NeonVectorType(T); 3226 else 3227 mangleNeonVectorType(T); 3228 return; 3229 } 3230 3231 Out << "Dv"; 3232 mangleExpression(T->getSizeExpr()); 3233 Out << '_'; 3234 if (T->getVectorKind() == VectorType::AltiVecPixel) 3235 Out << 'p'; 3236 else if (T->getVectorKind() == VectorType::AltiVecBool) 3237 Out << 'b'; 3238 else 3239 mangleType(T->getElementType()); 3240 } 3241 3242 void CXXNameMangler::mangleType(const ExtVectorType *T) { 3243 mangleType(static_cast<const VectorType*>(T)); 3244 } 3245 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 3246 Out << "Dv"; 3247 mangleExpression(T->getSizeExpr()); 3248 Out << '_'; 3249 mangleType(T->getElementType()); 3250 } 3251 3252 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) { 3253 SplitQualType split = T->getPointeeType().split(); 3254 mangleQualifiers(split.Quals, T); 3255 mangleType(QualType(split.Ty, 0)); 3256 } 3257 3258 void CXXNameMangler::mangleType(const PackExpansionType *T) { 3259 // <type> ::= Dp <type> # pack expansion (C++0x) 3260 Out << "Dp"; 3261 mangleType(T->getPattern()); 3262 } 3263 3264 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 3265 mangleSourceName(T->getDecl()->getIdentifier()); 3266 } 3267 3268 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 3269 // Treat __kindof as a vendor extended type qualifier. 3270 if (T->isKindOfType()) 3271 Out << "U8__kindof"; 3272 3273 if (!T->qual_empty()) { 3274 // Mangle protocol qualifiers. 3275 SmallString<64> QualStr; 3276 llvm::raw_svector_ostream QualOS(QualStr); 3277 QualOS << "objcproto"; 3278 for (const auto *I : T->quals()) { 3279 StringRef name = I->getName(); 3280 QualOS << name.size() << name; 3281 } 3282 Out << 'U' << QualStr.size() << QualStr; 3283 } 3284 3285 mangleType(T->getBaseType()); 3286 3287 if (T->isSpecialized()) { 3288 // Mangle type arguments as I <type>+ E 3289 Out << 'I'; 3290 for (auto typeArg : T->getTypeArgs()) 3291 mangleType(typeArg); 3292 Out << 'E'; 3293 } 3294 } 3295 3296 void CXXNameMangler::mangleType(const BlockPointerType *T) { 3297 Out << "U13block_pointer"; 3298 mangleType(T->getPointeeType()); 3299 } 3300 3301 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 3302 // Mangle injected class name types as if the user had written the 3303 // specialization out fully. It may not actually be possible to see 3304 // this mangling, though. 3305 mangleType(T->getInjectedSpecializationType()); 3306 } 3307 3308 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 3309 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 3310 mangleTemplateName(TD, T->getArgs(), T->getNumArgs()); 3311 } else { 3312 if (mangleSubstitution(QualType(T, 0))) 3313 return; 3314 3315 mangleTemplatePrefix(T->getTemplateName()); 3316 3317 // FIXME: GCC does not appear to mangle the template arguments when 3318 // the template in question is a dependent template name. Should we 3319 // emulate that badness? 3320 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 3321 addSubstitution(QualType(T, 0)); 3322 } 3323 } 3324 3325 void CXXNameMangler::mangleType(const DependentNameType *T) { 3326 // Proposal by cxx-abi-dev, 2014-03-26 3327 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 3328 // # dependent elaborated type specifier using 3329 // # 'typename' 3330 // ::= Ts <name> # dependent elaborated type specifier using 3331 // # 'struct' or 'class' 3332 // ::= Tu <name> # dependent elaborated type specifier using 3333 // # 'union' 3334 // ::= Te <name> # dependent elaborated type specifier using 3335 // # 'enum' 3336 switch (T->getKeyword()) { 3337 case ETK_None: 3338 case ETK_Typename: 3339 break; 3340 case ETK_Struct: 3341 case ETK_Class: 3342 case ETK_Interface: 3343 Out << "Ts"; 3344 break; 3345 case ETK_Union: 3346 Out << "Tu"; 3347 break; 3348 case ETK_Enum: 3349 Out << "Te"; 3350 break; 3351 } 3352 // Typename types are always nested 3353 Out << 'N'; 3354 manglePrefix(T->getQualifier()); 3355 mangleSourceName(T->getIdentifier()); 3356 Out << 'E'; 3357 } 3358 3359 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 3360 // Dependently-scoped template types are nested if they have a prefix. 3361 Out << 'N'; 3362 3363 // TODO: avoid making this TemplateName. 3364 TemplateName Prefix = 3365 getASTContext().getDependentTemplateName(T->getQualifier(), 3366 T->getIdentifier()); 3367 mangleTemplatePrefix(Prefix); 3368 3369 // FIXME: GCC does not appear to mangle the template arguments when 3370 // the template in question is a dependent template name. Should we 3371 // emulate that badness? 3372 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 3373 Out << 'E'; 3374 } 3375 3376 void CXXNameMangler::mangleType(const TypeOfType *T) { 3377 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3378 // "extension with parameters" mangling. 3379 Out << "u6typeof"; 3380 } 3381 3382 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 3383 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3384 // "extension with parameters" mangling. 3385 Out << "u6typeof"; 3386 } 3387 3388 void CXXNameMangler::mangleType(const DecltypeType *T) { 3389 Expr *E = T->getUnderlyingExpr(); 3390 3391 // type ::= Dt <expression> E # decltype of an id-expression 3392 // # or class member access 3393 // ::= DT <expression> E # decltype of an expression 3394 3395 // This purports to be an exhaustive list of id-expressions and 3396 // class member accesses. Note that we do not ignore parentheses; 3397 // parentheses change the semantics of decltype for these 3398 // expressions (and cause the mangler to use the other form). 3399 if (isa<DeclRefExpr>(E) || 3400 isa<MemberExpr>(E) || 3401 isa<UnresolvedLookupExpr>(E) || 3402 isa<DependentScopeDeclRefExpr>(E) || 3403 isa<CXXDependentScopeMemberExpr>(E) || 3404 isa<UnresolvedMemberExpr>(E)) 3405 Out << "Dt"; 3406 else 3407 Out << "DT"; 3408 mangleExpression(E); 3409 Out << 'E'; 3410 } 3411 3412 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 3413 // If this is dependent, we need to record that. If not, we simply 3414 // mangle it as the underlying type since they are equivalent. 3415 if (T->isDependentType()) { 3416 Out << 'U'; 3417 3418 switch (T->getUTTKind()) { 3419 case UnaryTransformType::EnumUnderlyingType: 3420 Out << "3eut"; 3421 break; 3422 } 3423 } 3424 3425 mangleType(T->getBaseType()); 3426 } 3427 3428 void CXXNameMangler::mangleType(const AutoType *T) { 3429 assert(T->getDeducedType().isNull() && 3430 "Deduced AutoType shouldn't be handled here!"); 3431 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType && 3432 "shouldn't need to mangle __auto_type!"); 3433 // <builtin-type> ::= Da # auto 3434 // ::= Dc # decltype(auto) 3435 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 3436 } 3437 3438 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) { 3439 // FIXME: This is not the right mangling. We also need to include a scope 3440 // here in some cases. 3441 QualType D = T->getDeducedType(); 3442 if (D.isNull()) 3443 mangleUnscopedTemplateName(T->getTemplateName(), nullptr); 3444 else 3445 mangleType(D); 3446 } 3447 3448 void CXXNameMangler::mangleType(const AtomicType *T) { 3449 // <type> ::= U <source-name> <type> # vendor extended type qualifier 3450 // (Until there's a standardized mangling...) 3451 Out << "U7_Atomic"; 3452 mangleType(T->getValueType()); 3453 } 3454 3455 void CXXNameMangler::mangleType(const PipeType *T) { 3456 // Pipe type mangling rules are described in SPIR 2.0 specification 3457 // A.1 Data types and A.3 Summary of changes 3458 // <type> ::= 8ocl_pipe 3459 Out << "8ocl_pipe"; 3460 } 3461 3462 void CXXNameMangler::mangleIntegerLiteral(QualType T, 3463 const llvm::APSInt &Value) { 3464 // <expr-primary> ::= L <type> <value number> E # integer literal 3465 Out << 'L'; 3466 3467 mangleType(T); 3468 if (T->isBooleanType()) { 3469 // Boolean values are encoded as 0/1. 3470 Out << (Value.getBoolValue() ? '1' : '0'); 3471 } else { 3472 mangleNumber(Value); 3473 } 3474 Out << 'E'; 3475 3476 } 3477 3478 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) { 3479 // Ignore member expressions involving anonymous unions. 3480 while (const auto *RT = Base->getType()->getAs<RecordType>()) { 3481 if (!RT->getDecl()->isAnonymousStructOrUnion()) 3482 break; 3483 const auto *ME = dyn_cast<MemberExpr>(Base); 3484 if (!ME) 3485 break; 3486 Base = ME->getBase(); 3487 IsArrow = ME->isArrow(); 3488 } 3489 3490 if (Base->isImplicitCXXThis()) { 3491 // Note: GCC mangles member expressions to the implicit 'this' as 3492 // *this., whereas we represent them as this->. The Itanium C++ ABI 3493 // does not specify anything here, so we follow GCC. 3494 Out << "dtdefpT"; 3495 } else { 3496 Out << (IsArrow ? "pt" : "dt"); 3497 mangleExpression(Base); 3498 } 3499 } 3500 3501 /// Mangles a member expression. 3502 void CXXNameMangler::mangleMemberExpr(const Expr *base, 3503 bool isArrow, 3504 NestedNameSpecifier *qualifier, 3505 NamedDecl *firstQualifierLookup, 3506 DeclarationName member, 3507 const TemplateArgumentLoc *TemplateArgs, 3508 unsigned NumTemplateArgs, 3509 unsigned arity) { 3510 // <expression> ::= dt <expression> <unresolved-name> 3511 // ::= pt <expression> <unresolved-name> 3512 if (base) 3513 mangleMemberExprBase(base, isArrow); 3514 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity); 3515 } 3516 3517 /// Look at the callee of the given call expression and determine if 3518 /// it's a parenthesized id-expression which would have triggered ADL 3519 /// otherwise. 3520 static bool isParenthesizedADLCallee(const CallExpr *call) { 3521 const Expr *callee = call->getCallee(); 3522 const Expr *fn = callee->IgnoreParens(); 3523 3524 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 3525 // too, but for those to appear in the callee, it would have to be 3526 // parenthesized. 3527 if (callee == fn) return false; 3528 3529 // Must be an unresolved lookup. 3530 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 3531 if (!lookup) return false; 3532 3533 assert(!lookup->requiresADL()); 3534 3535 // Must be an unqualified lookup. 3536 if (lookup->getQualifier()) return false; 3537 3538 // Must not have found a class member. Note that if one is a class 3539 // member, they're all class members. 3540 if (lookup->getNumDecls() > 0 && 3541 (*lookup->decls_begin())->isCXXClassMember()) 3542 return false; 3543 3544 // Otherwise, ADL would have been triggered. 3545 return true; 3546 } 3547 3548 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 3549 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 3550 Out << CastEncoding; 3551 mangleType(ECE->getType()); 3552 mangleExpression(ECE->getSubExpr()); 3553 } 3554 3555 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) { 3556 if (auto *Syntactic = InitList->getSyntacticForm()) 3557 InitList = Syntactic; 3558 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 3559 mangleExpression(InitList->getInit(i)); 3560 } 3561 3562 void CXXNameMangler::mangleDeclRefExpr(const NamedDecl *D) { 3563 switch (D->getKind()) { 3564 default: 3565 // <expr-primary> ::= L <mangled-name> E # external name 3566 Out << 'L'; 3567 mangle(D); 3568 Out << 'E'; 3569 break; 3570 3571 case Decl::ParmVar: 3572 mangleFunctionParam(cast<ParmVarDecl>(D)); 3573 break; 3574 3575 case Decl::EnumConstant: { 3576 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 3577 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 3578 break; 3579 } 3580 3581 case Decl::NonTypeTemplateParm: 3582 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 3583 mangleTemplateParameter(PD->getDepth(), PD->getIndex()); 3584 break; 3585 } 3586 } 3587 3588 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { 3589 // <expression> ::= <unary operator-name> <expression> 3590 // ::= <binary operator-name> <expression> <expression> 3591 // ::= <trinary operator-name> <expression> <expression> <expression> 3592 // ::= cv <type> expression # conversion with one argument 3593 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 3594 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 3595 // ::= sc <type> <expression> # static_cast<type> (expression) 3596 // ::= cc <type> <expression> # const_cast<type> (expression) 3597 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 3598 // ::= st <type> # sizeof (a type) 3599 // ::= at <type> # alignof (a type) 3600 // ::= <template-param> 3601 // ::= <function-param> 3602 // ::= sr <type> <unqualified-name> # dependent name 3603 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 3604 // ::= ds <expression> <expression> # expr.*expr 3605 // ::= sZ <template-param> # size of a parameter pack 3606 // ::= sZ <function-param> # size of a function parameter pack 3607 // ::= <expr-primary> 3608 // <expr-primary> ::= L <type> <value number> E # integer literal 3609 // ::= L <type <value float> E # floating literal 3610 // ::= L <mangled-name> E # external name 3611 // ::= fpT # 'this' expression 3612 QualType ImplicitlyConvertedToType; 3613 3614 recurse: 3615 switch (E->getStmtClass()) { 3616 case Expr::NoStmtClass: 3617 #define ABSTRACT_STMT(Type) 3618 #define EXPR(Type, Base) 3619 #define STMT(Type, Base) \ 3620 case Expr::Type##Class: 3621 #include "clang/AST/StmtNodes.inc" 3622 // fallthrough 3623 3624 // These all can only appear in local or variable-initialization 3625 // contexts and so should never appear in a mangling. 3626 case Expr::AddrLabelExprClass: 3627 case Expr::DesignatedInitUpdateExprClass: 3628 case Expr::ImplicitValueInitExprClass: 3629 case Expr::ArrayInitLoopExprClass: 3630 case Expr::ArrayInitIndexExprClass: 3631 case Expr::NoInitExprClass: 3632 case Expr::ParenListExprClass: 3633 case Expr::LambdaExprClass: 3634 case Expr::MSPropertyRefExprClass: 3635 case Expr::MSPropertySubscriptExprClass: 3636 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 3637 case Expr::OMPArraySectionExprClass: 3638 case Expr::CXXInheritedCtorInitExprClass: 3639 llvm_unreachable("unexpected statement kind"); 3640 3641 case Expr::ConstantExprClass: 3642 E = cast<ConstantExpr>(E)->getSubExpr(); 3643 goto recurse; 3644 3645 // FIXME: invent manglings for all these. 3646 case Expr::BlockExprClass: 3647 case Expr::ChooseExprClass: 3648 case Expr::CompoundLiteralExprClass: 3649 case Expr::ExtVectorElementExprClass: 3650 case Expr::GenericSelectionExprClass: 3651 case Expr::ObjCEncodeExprClass: 3652 case Expr::ObjCIsaExprClass: 3653 case Expr::ObjCIvarRefExprClass: 3654 case Expr::ObjCMessageExprClass: 3655 case Expr::ObjCPropertyRefExprClass: 3656 case Expr::ObjCProtocolExprClass: 3657 case Expr::ObjCSelectorExprClass: 3658 case Expr::ObjCStringLiteralClass: 3659 case Expr::ObjCBoxedExprClass: 3660 case Expr::ObjCArrayLiteralClass: 3661 case Expr::ObjCDictionaryLiteralClass: 3662 case Expr::ObjCSubscriptRefExprClass: 3663 case Expr::ObjCIndirectCopyRestoreExprClass: 3664 case Expr::ObjCAvailabilityCheckExprClass: 3665 case Expr::OffsetOfExprClass: 3666 case Expr::PredefinedExprClass: 3667 case Expr::ShuffleVectorExprClass: 3668 case Expr::ConvertVectorExprClass: 3669 case Expr::StmtExprClass: 3670 case Expr::TypeTraitExprClass: 3671 case Expr::ArrayTypeTraitExprClass: 3672 case Expr::ExpressionTraitExprClass: 3673 case Expr::VAArgExprClass: 3674 case Expr::CUDAKernelCallExprClass: 3675 case Expr::AsTypeExprClass: 3676 case Expr::PseudoObjectExprClass: 3677 case Expr::AtomicExprClass: 3678 case Expr::SourceLocExprClass: 3679 case Expr::FixedPointLiteralClass: 3680 case Expr::BuiltinBitCastExprClass: 3681 { 3682 if (!NullOut) { 3683 // As bad as this diagnostic is, it's better than crashing. 3684 DiagnosticsEngine &Diags = Context.getDiags(); 3685 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3686 "cannot yet mangle expression type %0"); 3687 Diags.Report(E->getExprLoc(), DiagID) 3688 << E->getStmtClassName() << E->getSourceRange(); 3689 } 3690 break; 3691 } 3692 3693 case Expr::CXXUuidofExprClass: { 3694 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 3695 if (UE->isTypeOperand()) { 3696 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 3697 Out << "u8__uuidoft"; 3698 mangleType(UuidT); 3699 } else { 3700 Expr *UuidExp = UE->getExprOperand(); 3701 Out << "u8__uuidofz"; 3702 mangleExpression(UuidExp, Arity); 3703 } 3704 break; 3705 } 3706 3707 // Even gcc-4.5 doesn't mangle this. 3708 case Expr::BinaryConditionalOperatorClass: { 3709 DiagnosticsEngine &Diags = Context.getDiags(); 3710 unsigned DiagID = 3711 Diags.getCustomDiagID(DiagnosticsEngine::Error, 3712 "?: operator with omitted middle operand cannot be mangled"); 3713 Diags.Report(E->getExprLoc(), DiagID) 3714 << E->getStmtClassName() << E->getSourceRange(); 3715 break; 3716 } 3717 3718 // These are used for internal purposes and cannot be meaningfully mangled. 3719 case Expr::OpaqueValueExprClass: 3720 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 3721 3722 case Expr::InitListExprClass: { 3723 Out << "il"; 3724 mangleInitListElements(cast<InitListExpr>(E)); 3725 Out << "E"; 3726 break; 3727 } 3728 3729 case Expr::DesignatedInitExprClass: { 3730 auto *DIE = cast<DesignatedInitExpr>(E); 3731 for (const auto &Designator : DIE->designators()) { 3732 if (Designator.isFieldDesignator()) { 3733 Out << "di"; 3734 mangleSourceName(Designator.getFieldName()); 3735 } else if (Designator.isArrayDesignator()) { 3736 Out << "dx"; 3737 mangleExpression(DIE->getArrayIndex(Designator)); 3738 } else { 3739 assert(Designator.isArrayRangeDesignator() && 3740 "unknown designator kind"); 3741 Out << "dX"; 3742 mangleExpression(DIE->getArrayRangeStart(Designator)); 3743 mangleExpression(DIE->getArrayRangeEnd(Designator)); 3744 } 3745 } 3746 mangleExpression(DIE->getInit()); 3747 break; 3748 } 3749 3750 case Expr::CXXDefaultArgExprClass: 3751 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity); 3752 break; 3753 3754 case Expr::CXXDefaultInitExprClass: 3755 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity); 3756 break; 3757 3758 case Expr::CXXStdInitializerListExprClass: 3759 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity); 3760 break; 3761 3762 case Expr::SubstNonTypeTemplateParmExprClass: 3763 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), 3764 Arity); 3765 break; 3766 3767 case Expr::UserDefinedLiteralClass: 3768 // We follow g++'s approach of mangling a UDL as a call to the literal 3769 // operator. 3770 case Expr::CXXMemberCallExprClass: // fallthrough 3771 case Expr::CallExprClass: { 3772 const CallExpr *CE = cast<CallExpr>(E); 3773 3774 // <expression> ::= cp <simple-id> <expression>* E 3775 // We use this mangling only when the call would use ADL except 3776 // for being parenthesized. Per discussion with David 3777 // Vandervoorde, 2011.04.25. 3778 if (isParenthesizedADLCallee(CE)) { 3779 Out << "cp"; 3780 // The callee here is a parenthesized UnresolvedLookupExpr with 3781 // no qualifier and should always get mangled as a <simple-id> 3782 // anyway. 3783 3784 // <expression> ::= cl <expression>* E 3785 } else { 3786 Out << "cl"; 3787 } 3788 3789 unsigned CallArity = CE->getNumArgs(); 3790 for (const Expr *Arg : CE->arguments()) 3791 if (isa<PackExpansionExpr>(Arg)) 3792 CallArity = UnknownArity; 3793 3794 mangleExpression(CE->getCallee(), CallArity); 3795 for (const Expr *Arg : CE->arguments()) 3796 mangleExpression(Arg); 3797 Out << 'E'; 3798 break; 3799 } 3800 3801 case Expr::CXXNewExprClass: { 3802 const CXXNewExpr *New = cast<CXXNewExpr>(E); 3803 if (New->isGlobalNew()) Out << "gs"; 3804 Out << (New->isArray() ? "na" : "nw"); 3805 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 3806 E = New->placement_arg_end(); I != E; ++I) 3807 mangleExpression(*I); 3808 Out << '_'; 3809 mangleType(New->getAllocatedType()); 3810 if (New->hasInitializer()) { 3811 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 3812 Out << "il"; 3813 else 3814 Out << "pi"; 3815 const Expr *Init = New->getInitializer(); 3816 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 3817 // Directly inline the initializers. 3818 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 3819 E = CCE->arg_end(); 3820 I != E; ++I) 3821 mangleExpression(*I); 3822 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 3823 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 3824 mangleExpression(PLE->getExpr(i)); 3825 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 3826 isa<InitListExpr>(Init)) { 3827 // Only take InitListExprs apart for list-initialization. 3828 mangleInitListElements(cast<InitListExpr>(Init)); 3829 } else 3830 mangleExpression(Init); 3831 } 3832 Out << 'E'; 3833 break; 3834 } 3835 3836 case Expr::CXXPseudoDestructorExprClass: { 3837 const auto *PDE = cast<CXXPseudoDestructorExpr>(E); 3838 if (const Expr *Base = PDE->getBase()) 3839 mangleMemberExprBase(Base, PDE->isArrow()); 3840 NestedNameSpecifier *Qualifier = PDE->getQualifier(); 3841 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) { 3842 if (Qualifier) { 3843 mangleUnresolvedPrefix(Qualifier, 3844 /*recursive=*/true); 3845 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()); 3846 Out << 'E'; 3847 } else { 3848 Out << "sr"; 3849 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType())) 3850 Out << 'E'; 3851 } 3852 } else if (Qualifier) { 3853 mangleUnresolvedPrefix(Qualifier); 3854 } 3855 // <base-unresolved-name> ::= dn <destructor-name> 3856 Out << "dn"; 3857 QualType DestroyedType = PDE->getDestroyedType(); 3858 mangleUnresolvedTypeOrSimpleId(DestroyedType); 3859 break; 3860 } 3861 3862 case Expr::MemberExprClass: { 3863 const MemberExpr *ME = cast<MemberExpr>(E); 3864 mangleMemberExpr(ME->getBase(), ME->isArrow(), 3865 ME->getQualifier(), nullptr, 3866 ME->getMemberDecl()->getDeclName(), 3867 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 3868 Arity); 3869 break; 3870 } 3871 3872 case Expr::UnresolvedMemberExprClass: { 3873 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 3874 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 3875 ME->isArrow(), ME->getQualifier(), nullptr, 3876 ME->getMemberName(), 3877 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 3878 Arity); 3879 break; 3880 } 3881 3882 case Expr::CXXDependentScopeMemberExprClass: { 3883 const CXXDependentScopeMemberExpr *ME 3884 = cast<CXXDependentScopeMemberExpr>(E); 3885 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 3886 ME->isArrow(), ME->getQualifier(), 3887 ME->getFirstQualifierFoundInScope(), 3888 ME->getMember(), 3889 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 3890 Arity); 3891 break; 3892 } 3893 3894 case Expr::UnresolvedLookupExprClass: { 3895 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 3896 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), 3897 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(), 3898 Arity); 3899 break; 3900 } 3901 3902 case Expr::CXXUnresolvedConstructExprClass: { 3903 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 3904 unsigned N = CE->arg_size(); 3905 3906 if (CE->isListInitialization()) { 3907 assert(N == 1 && "unexpected form for list initialization"); 3908 auto *IL = cast<InitListExpr>(CE->getArg(0)); 3909 Out << "tl"; 3910 mangleType(CE->getType()); 3911 mangleInitListElements(IL); 3912 Out << "E"; 3913 return; 3914 } 3915 3916 Out << "cv"; 3917 mangleType(CE->getType()); 3918 if (N != 1) Out << '_'; 3919 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 3920 if (N != 1) Out << 'E'; 3921 break; 3922 } 3923 3924 case Expr::CXXConstructExprClass: { 3925 const auto *CE = cast<CXXConstructExpr>(E); 3926 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) { 3927 assert( 3928 CE->getNumArgs() >= 1 && 3929 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && 3930 "implicit CXXConstructExpr must have one argument"); 3931 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0)); 3932 } 3933 Out << "il"; 3934 for (auto *E : CE->arguments()) 3935 mangleExpression(E); 3936 Out << "E"; 3937 break; 3938 } 3939 3940 case Expr::CXXTemporaryObjectExprClass: { 3941 const auto *CE = cast<CXXTemporaryObjectExpr>(E); 3942 unsigned N = CE->getNumArgs(); 3943 bool List = CE->isListInitialization(); 3944 3945 if (List) 3946 Out << "tl"; 3947 else 3948 Out << "cv"; 3949 mangleType(CE->getType()); 3950 if (!List && N != 1) 3951 Out << '_'; 3952 if (CE->isStdInitListInitialization()) { 3953 // We implicitly created a std::initializer_list<T> for the first argument 3954 // of a constructor of type U in an expression of the form U{a, b, c}. 3955 // Strip all the semantic gunk off the initializer list. 3956 auto *SILE = 3957 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit()); 3958 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit()); 3959 mangleInitListElements(ILE); 3960 } else { 3961 for (auto *E : CE->arguments()) 3962 mangleExpression(E); 3963 } 3964 if (List || N != 1) 3965 Out << 'E'; 3966 break; 3967 } 3968 3969 case Expr::CXXScalarValueInitExprClass: 3970 Out << "cv"; 3971 mangleType(E->getType()); 3972 Out << "_E"; 3973 break; 3974 3975 case Expr::CXXNoexceptExprClass: 3976 Out << "nx"; 3977 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 3978 break; 3979 3980 case Expr::UnaryExprOrTypeTraitExprClass: { 3981 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 3982 3983 if (!SAE->isInstantiationDependent()) { 3984 // Itanium C++ ABI: 3985 // If the operand of a sizeof or alignof operator is not 3986 // instantiation-dependent it is encoded as an integer literal 3987 // reflecting the result of the operator. 3988 // 3989 // If the result of the operator is implicitly converted to a known 3990 // integer type, that type is used for the literal; otherwise, the type 3991 // of std::size_t or std::ptrdiff_t is used. 3992 QualType T = (ImplicitlyConvertedToType.isNull() || 3993 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 3994 : ImplicitlyConvertedToType; 3995 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 3996 mangleIntegerLiteral(T, V); 3997 break; 3998 } 3999 4000 switch(SAE->getKind()) { 4001 case UETT_SizeOf: 4002 Out << 's'; 4003 break; 4004 case UETT_PreferredAlignOf: 4005 case UETT_AlignOf: 4006 Out << 'a'; 4007 break; 4008 case UETT_VecStep: { 4009 DiagnosticsEngine &Diags = Context.getDiags(); 4010 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4011 "cannot yet mangle vec_step expression"); 4012 Diags.Report(DiagID); 4013 return; 4014 } 4015 case UETT_OpenMPRequiredSimdAlign: { 4016 DiagnosticsEngine &Diags = Context.getDiags(); 4017 unsigned DiagID = Diags.getCustomDiagID( 4018 DiagnosticsEngine::Error, 4019 "cannot yet mangle __builtin_omp_required_simd_align expression"); 4020 Diags.Report(DiagID); 4021 return; 4022 } 4023 } 4024 if (SAE->isArgumentType()) { 4025 Out << 't'; 4026 mangleType(SAE->getArgumentType()); 4027 } else { 4028 Out << 'z'; 4029 mangleExpression(SAE->getArgumentExpr()); 4030 } 4031 break; 4032 } 4033 4034 case Expr::CXXThrowExprClass: { 4035 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 4036 // <expression> ::= tw <expression> # throw expression 4037 // ::= tr # rethrow 4038 if (TE->getSubExpr()) { 4039 Out << "tw"; 4040 mangleExpression(TE->getSubExpr()); 4041 } else { 4042 Out << "tr"; 4043 } 4044 break; 4045 } 4046 4047 case Expr::CXXTypeidExprClass: { 4048 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 4049 // <expression> ::= ti <type> # typeid (type) 4050 // ::= te <expression> # typeid (expression) 4051 if (TIE->isTypeOperand()) { 4052 Out << "ti"; 4053 mangleType(TIE->getTypeOperand(Context.getASTContext())); 4054 } else { 4055 Out << "te"; 4056 mangleExpression(TIE->getExprOperand()); 4057 } 4058 break; 4059 } 4060 4061 case Expr::CXXDeleteExprClass: { 4062 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 4063 // <expression> ::= [gs] dl <expression> # [::] delete expr 4064 // ::= [gs] da <expression> # [::] delete [] expr 4065 if (DE->isGlobalDelete()) Out << "gs"; 4066 Out << (DE->isArrayForm() ? "da" : "dl"); 4067 mangleExpression(DE->getArgument()); 4068 break; 4069 } 4070 4071 case Expr::UnaryOperatorClass: { 4072 const UnaryOperator *UO = cast<UnaryOperator>(E); 4073 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 4074 /*Arity=*/1); 4075 mangleExpression(UO->getSubExpr()); 4076 break; 4077 } 4078 4079 case Expr::ArraySubscriptExprClass: { 4080 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 4081 4082 // Array subscript is treated as a syntactically weird form of 4083 // binary operator. 4084 Out << "ix"; 4085 mangleExpression(AE->getLHS()); 4086 mangleExpression(AE->getRHS()); 4087 break; 4088 } 4089 4090 case Expr::CompoundAssignOperatorClass: // fallthrough 4091 case Expr::BinaryOperatorClass: { 4092 const BinaryOperator *BO = cast<BinaryOperator>(E); 4093 if (BO->getOpcode() == BO_PtrMemD) 4094 Out << "ds"; 4095 else 4096 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 4097 /*Arity=*/2); 4098 mangleExpression(BO->getLHS()); 4099 mangleExpression(BO->getRHS()); 4100 break; 4101 } 4102 4103 case Expr::CXXRewrittenBinaryOperatorClass: { 4104 // The mangled form represents the original syntax. 4105 CXXRewrittenBinaryOperator::DecomposedForm Decomposed = 4106 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm(); 4107 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode), 4108 /*Arity=*/2); 4109 mangleExpression(Decomposed.LHS); 4110 mangleExpression(Decomposed.RHS); 4111 break; 4112 } 4113 4114 case Expr::ConditionalOperatorClass: { 4115 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 4116 mangleOperatorName(OO_Conditional, /*Arity=*/3); 4117 mangleExpression(CO->getCond()); 4118 mangleExpression(CO->getLHS(), Arity); 4119 mangleExpression(CO->getRHS(), Arity); 4120 break; 4121 } 4122 4123 case Expr::ImplicitCastExprClass: { 4124 ImplicitlyConvertedToType = E->getType(); 4125 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4126 goto recurse; 4127 } 4128 4129 case Expr::ObjCBridgedCastExprClass: { 4130 // Mangle ownership casts as a vendor extended operator __bridge, 4131 // __bridge_transfer, or __bridge_retain. 4132 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 4133 Out << "v1U" << Kind.size() << Kind; 4134 } 4135 // Fall through to mangle the cast itself. 4136 LLVM_FALLTHROUGH; 4137 4138 case Expr::CStyleCastExprClass: 4139 mangleCastExpression(E, "cv"); 4140 break; 4141 4142 case Expr::CXXFunctionalCastExprClass: { 4143 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit(); 4144 // FIXME: Add isImplicit to CXXConstructExpr. 4145 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub)) 4146 if (CCE->getParenOrBraceRange().isInvalid()) 4147 Sub = CCE->getArg(0)->IgnoreImplicit(); 4148 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub)) 4149 Sub = StdInitList->getSubExpr()->IgnoreImplicit(); 4150 if (auto *IL = dyn_cast<InitListExpr>(Sub)) { 4151 Out << "tl"; 4152 mangleType(E->getType()); 4153 mangleInitListElements(IL); 4154 Out << "E"; 4155 } else { 4156 mangleCastExpression(E, "cv"); 4157 } 4158 break; 4159 } 4160 4161 case Expr::CXXStaticCastExprClass: 4162 mangleCastExpression(E, "sc"); 4163 break; 4164 case Expr::CXXDynamicCastExprClass: 4165 mangleCastExpression(E, "dc"); 4166 break; 4167 case Expr::CXXReinterpretCastExprClass: 4168 mangleCastExpression(E, "rc"); 4169 break; 4170 case Expr::CXXConstCastExprClass: 4171 mangleCastExpression(E, "cc"); 4172 break; 4173 4174 case Expr::CXXOperatorCallExprClass: { 4175 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 4176 unsigned NumArgs = CE->getNumArgs(); 4177 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax 4178 // (the enclosing MemberExpr covers the syntactic portion). 4179 if (CE->getOperator() != OO_Arrow) 4180 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 4181 // Mangle the arguments. 4182 for (unsigned i = 0; i != NumArgs; ++i) 4183 mangleExpression(CE->getArg(i)); 4184 break; 4185 } 4186 4187 case Expr::ParenExprClass: 4188 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity); 4189 break; 4190 4191 4192 case Expr::ConceptSpecializationExprClass: { 4193 // <expr-primary> ::= L <mangled-name> E # external name 4194 Out << "L_Z"; 4195 auto *CSE = cast<ConceptSpecializationExpr>(E); 4196 mangleTemplateName(CSE->getNamedConcept(), 4197 CSE->getTemplateArguments().data(), 4198 CSE->getTemplateArguments().size()); 4199 Out << 'E'; 4200 break; 4201 } 4202 4203 case Expr::DeclRefExprClass: 4204 mangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl()); 4205 break; 4206 4207 case Expr::SubstNonTypeTemplateParmPackExprClass: 4208 // FIXME: not clear how to mangle this! 4209 // template <unsigned N...> class A { 4210 // template <class U...> void foo(U (&x)[N]...); 4211 // }; 4212 Out << "_SUBSTPACK_"; 4213 break; 4214 4215 case Expr::FunctionParmPackExprClass: { 4216 // FIXME: not clear how to mangle this! 4217 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 4218 Out << "v110_SUBSTPACK"; 4219 mangleDeclRefExpr(FPPE->getParameterPack()); 4220 break; 4221 } 4222 4223 case Expr::DependentScopeDeclRefExprClass: { 4224 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 4225 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), 4226 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(), 4227 Arity); 4228 break; 4229 } 4230 4231 case Expr::CXXBindTemporaryExprClass: 4232 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr()); 4233 break; 4234 4235 case Expr::ExprWithCleanupsClass: 4236 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity); 4237 break; 4238 4239 case Expr::FloatingLiteralClass: { 4240 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 4241 Out << 'L'; 4242 mangleType(FL->getType()); 4243 mangleFloat(FL->getValue()); 4244 Out << 'E'; 4245 break; 4246 } 4247 4248 case Expr::CharacterLiteralClass: 4249 Out << 'L'; 4250 mangleType(E->getType()); 4251 Out << cast<CharacterLiteral>(E)->getValue(); 4252 Out << 'E'; 4253 break; 4254 4255 // FIXME. __objc_yes/__objc_no are mangled same as true/false 4256 case Expr::ObjCBoolLiteralExprClass: 4257 Out << "Lb"; 4258 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4259 Out << 'E'; 4260 break; 4261 4262 case Expr::CXXBoolLiteralExprClass: 4263 Out << "Lb"; 4264 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4265 Out << 'E'; 4266 break; 4267 4268 case Expr::IntegerLiteralClass: { 4269 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 4270 if (E->getType()->isSignedIntegerType()) 4271 Value.setIsSigned(true); 4272 mangleIntegerLiteral(E->getType(), Value); 4273 break; 4274 } 4275 4276 case Expr::ImaginaryLiteralClass: { 4277 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 4278 // Mangle as if a complex literal. 4279 // Proposal from David Vandevoorde, 2010.06.30. 4280 Out << 'L'; 4281 mangleType(E->getType()); 4282 if (const FloatingLiteral *Imag = 4283 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 4284 // Mangle a floating-point zero of the appropriate type. 4285 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 4286 Out << '_'; 4287 mangleFloat(Imag->getValue()); 4288 } else { 4289 Out << "0_"; 4290 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 4291 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 4292 Value.setIsSigned(true); 4293 mangleNumber(Value); 4294 } 4295 Out << 'E'; 4296 break; 4297 } 4298 4299 case Expr::StringLiteralClass: { 4300 // Revised proposal from David Vandervoorde, 2010.07.15. 4301 Out << 'L'; 4302 assert(isa<ConstantArrayType>(E->getType())); 4303 mangleType(E->getType()); 4304 Out << 'E'; 4305 break; 4306 } 4307 4308 case Expr::GNUNullExprClass: 4309 // Mangle as if an integer literal 0. 4310 Out << 'L'; 4311 mangleType(E->getType()); 4312 Out << "0E"; 4313 break; 4314 4315 case Expr::CXXNullPtrLiteralExprClass: { 4316 Out << "LDnE"; 4317 break; 4318 } 4319 4320 case Expr::PackExpansionExprClass: 4321 Out << "sp"; 4322 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 4323 break; 4324 4325 case Expr::SizeOfPackExprClass: { 4326 auto *SPE = cast<SizeOfPackExpr>(E); 4327 if (SPE->isPartiallySubstituted()) { 4328 Out << "sP"; 4329 for (const auto &A : SPE->getPartialArguments()) 4330 mangleTemplateArg(A); 4331 Out << "E"; 4332 break; 4333 } 4334 4335 Out << "sZ"; 4336 const NamedDecl *Pack = SPE->getPack(); 4337 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 4338 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 4339 else if (const NonTypeTemplateParmDecl *NTTP 4340 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 4341 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex()); 4342 else if (const TemplateTemplateParmDecl *TempTP 4343 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 4344 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex()); 4345 else 4346 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 4347 break; 4348 } 4349 4350 case Expr::MaterializeTemporaryExprClass: { 4351 mangleExpression(cast<MaterializeTemporaryExpr>(E)->getSubExpr()); 4352 break; 4353 } 4354 4355 case Expr::CXXFoldExprClass: { 4356 auto *FE = cast<CXXFoldExpr>(E); 4357 if (FE->isLeftFold()) 4358 Out << (FE->getInit() ? "fL" : "fl"); 4359 else 4360 Out << (FE->getInit() ? "fR" : "fr"); 4361 4362 if (FE->getOperator() == BO_PtrMemD) 4363 Out << "ds"; 4364 else 4365 mangleOperatorName( 4366 BinaryOperator::getOverloadedOperator(FE->getOperator()), 4367 /*Arity=*/2); 4368 4369 if (FE->getLHS()) 4370 mangleExpression(FE->getLHS()); 4371 if (FE->getRHS()) 4372 mangleExpression(FE->getRHS()); 4373 break; 4374 } 4375 4376 case Expr::CXXThisExprClass: 4377 Out << "fpT"; 4378 break; 4379 4380 case Expr::CoawaitExprClass: 4381 // FIXME: Propose a non-vendor mangling. 4382 Out << "v18co_await"; 4383 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 4384 break; 4385 4386 case Expr::DependentCoawaitExprClass: 4387 // FIXME: Propose a non-vendor mangling. 4388 Out << "v18co_await"; 4389 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand()); 4390 break; 4391 4392 case Expr::CoyieldExprClass: 4393 // FIXME: Propose a non-vendor mangling. 4394 Out << "v18co_yield"; 4395 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 4396 break; 4397 } 4398 } 4399 4400 /// Mangle an expression which refers to a parameter variable. 4401 /// 4402 /// <expression> ::= <function-param> 4403 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 4404 /// <function-param> ::= fp <top-level CV-qualifiers> 4405 /// <parameter-2 non-negative number> _ # L == 0, I > 0 4406 /// <function-param> ::= fL <L-1 non-negative number> 4407 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 4408 /// <function-param> ::= fL <L-1 non-negative number> 4409 /// p <top-level CV-qualifiers> 4410 /// <I-1 non-negative number> _ # L > 0, I > 0 4411 /// 4412 /// L is the nesting depth of the parameter, defined as 1 if the 4413 /// parameter comes from the innermost function prototype scope 4414 /// enclosing the current context, 2 if from the next enclosing 4415 /// function prototype scope, and so on, with one special case: if 4416 /// we've processed the full parameter clause for the innermost 4417 /// function type, then L is one less. This definition conveniently 4418 /// makes it irrelevant whether a function's result type was written 4419 /// trailing or leading, but is otherwise overly complicated; the 4420 /// numbering was first designed without considering references to 4421 /// parameter in locations other than return types, and then the 4422 /// mangling had to be generalized without changing the existing 4423 /// manglings. 4424 /// 4425 /// I is the zero-based index of the parameter within its parameter 4426 /// declaration clause. Note that the original ABI document describes 4427 /// this using 1-based ordinals. 4428 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 4429 unsigned parmDepth = parm->getFunctionScopeDepth(); 4430 unsigned parmIndex = parm->getFunctionScopeIndex(); 4431 4432 // Compute 'L'. 4433 // parmDepth does not include the declaring function prototype. 4434 // FunctionTypeDepth does account for that. 4435 assert(parmDepth < FunctionTypeDepth.getDepth()); 4436 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 4437 if (FunctionTypeDepth.isInResultType()) 4438 nestingDepth--; 4439 4440 if (nestingDepth == 0) { 4441 Out << "fp"; 4442 } else { 4443 Out << "fL" << (nestingDepth - 1) << 'p'; 4444 } 4445 4446 // Top-level qualifiers. We don't have to worry about arrays here, 4447 // because parameters declared as arrays should already have been 4448 // transformed to have pointer type. FIXME: apparently these don't 4449 // get mangled if used as an rvalue of a known non-class type? 4450 assert(!parm->getType()->isArrayType() 4451 && "parameter's type is still an array type?"); 4452 4453 if (const DependentAddressSpaceType *DAST = 4454 dyn_cast<DependentAddressSpaceType>(parm->getType())) { 4455 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST); 4456 } else { 4457 mangleQualifiers(parm->getType().getQualifiers()); 4458 } 4459 4460 // Parameter index. 4461 if (parmIndex != 0) { 4462 Out << (parmIndex - 1); 4463 } 4464 Out << '_'; 4465 } 4466 4467 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T, 4468 const CXXRecordDecl *InheritedFrom) { 4469 // <ctor-dtor-name> ::= C1 # complete object constructor 4470 // ::= C2 # base object constructor 4471 // ::= CI1 <type> # complete inheriting constructor 4472 // ::= CI2 <type> # base inheriting constructor 4473 // 4474 // In addition, C5 is a comdat name with C1 and C2 in it. 4475 Out << 'C'; 4476 if (InheritedFrom) 4477 Out << 'I'; 4478 switch (T) { 4479 case Ctor_Complete: 4480 Out << '1'; 4481 break; 4482 case Ctor_Base: 4483 Out << '2'; 4484 break; 4485 case Ctor_Comdat: 4486 Out << '5'; 4487 break; 4488 case Ctor_DefaultClosure: 4489 case Ctor_CopyingClosure: 4490 llvm_unreachable("closure constructors don't exist for the Itanium ABI!"); 4491 } 4492 if (InheritedFrom) 4493 mangleName(InheritedFrom); 4494 } 4495 4496 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 4497 // <ctor-dtor-name> ::= D0 # deleting destructor 4498 // ::= D1 # complete object destructor 4499 // ::= D2 # base object destructor 4500 // 4501 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 4502 switch (T) { 4503 case Dtor_Deleting: 4504 Out << "D0"; 4505 break; 4506 case Dtor_Complete: 4507 Out << "D1"; 4508 break; 4509 case Dtor_Base: 4510 Out << "D2"; 4511 break; 4512 case Dtor_Comdat: 4513 Out << "D5"; 4514 break; 4515 } 4516 } 4517 4518 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs, 4519 unsigned NumTemplateArgs) { 4520 // <template-args> ::= I <template-arg>+ E 4521 Out << 'I'; 4522 for (unsigned i = 0; i != NumTemplateArgs; ++i) 4523 mangleTemplateArg(TemplateArgs[i].getArgument()); 4524 Out << 'E'; 4525 } 4526 4527 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) { 4528 // <template-args> ::= I <template-arg>+ E 4529 Out << 'I'; 4530 for (unsigned i = 0, e = AL.size(); i != e; ++i) 4531 mangleTemplateArg(AL[i]); 4532 Out << 'E'; 4533 } 4534 4535 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs, 4536 unsigned NumTemplateArgs) { 4537 // <template-args> ::= I <template-arg>+ E 4538 Out << 'I'; 4539 for (unsigned i = 0; i != NumTemplateArgs; ++i) 4540 mangleTemplateArg(TemplateArgs[i]); 4541 Out << 'E'; 4542 } 4543 4544 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { 4545 // <template-arg> ::= <type> # type or template 4546 // ::= X <expression> E # expression 4547 // ::= <expr-primary> # simple expressions 4548 // ::= J <template-arg>* E # argument pack 4549 if (!A.isInstantiationDependent() || A.isDependent()) 4550 A = Context.getASTContext().getCanonicalTemplateArgument(A); 4551 4552 switch (A.getKind()) { 4553 case TemplateArgument::Null: 4554 llvm_unreachable("Cannot mangle NULL template argument"); 4555 4556 case TemplateArgument::Type: 4557 mangleType(A.getAsType()); 4558 break; 4559 case TemplateArgument::Template: 4560 // This is mangled as <type>. 4561 mangleType(A.getAsTemplate()); 4562 break; 4563 case TemplateArgument::TemplateExpansion: 4564 // <type> ::= Dp <type> # pack expansion (C++0x) 4565 Out << "Dp"; 4566 mangleType(A.getAsTemplateOrTemplatePattern()); 4567 break; 4568 case TemplateArgument::Expression: { 4569 // It's possible to end up with a DeclRefExpr here in certain 4570 // dependent cases, in which case we should mangle as a 4571 // declaration. 4572 const Expr *E = A.getAsExpr()->IgnoreParenImpCasts(); 4573 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 4574 const ValueDecl *D = DRE->getDecl(); 4575 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 4576 Out << 'L'; 4577 mangle(D); 4578 Out << 'E'; 4579 break; 4580 } 4581 } 4582 4583 Out << 'X'; 4584 mangleExpression(E); 4585 Out << 'E'; 4586 break; 4587 } 4588 case TemplateArgument::Integral: 4589 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 4590 break; 4591 case TemplateArgument::Declaration: { 4592 // <expr-primary> ::= L <mangled-name> E # external name 4593 // Clang produces AST's where pointer-to-member-function expressions 4594 // and pointer-to-function expressions are represented as a declaration not 4595 // an expression. We compensate for it here to produce the correct mangling. 4596 ValueDecl *D = A.getAsDecl(); 4597 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType(); 4598 if (compensateMangling) { 4599 Out << 'X'; 4600 mangleOperatorName(OO_Amp, 1); 4601 } 4602 4603 Out << 'L'; 4604 // References to external entities use the mangled name; if the name would 4605 // not normally be mangled then mangle it as unqualified. 4606 mangle(D); 4607 Out << 'E'; 4608 4609 if (compensateMangling) 4610 Out << 'E'; 4611 4612 break; 4613 } 4614 case TemplateArgument::NullPtr: { 4615 // <expr-primary> ::= L <type> 0 E 4616 Out << 'L'; 4617 mangleType(A.getNullPtrType()); 4618 Out << "0E"; 4619 break; 4620 } 4621 case TemplateArgument::Pack: { 4622 // <template-arg> ::= J <template-arg>* E 4623 Out << 'J'; 4624 for (const auto &P : A.pack_elements()) 4625 mangleTemplateArg(P); 4626 Out << 'E'; 4627 } 4628 } 4629 } 4630 4631 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) { 4632 // <template-param> ::= T_ # first template parameter 4633 // ::= T <parameter-2 non-negative number> _ 4634 // ::= TL <L-1 non-negative number> __ 4635 // ::= TL <L-1 non-negative number> _ 4636 // <parameter-2 non-negative number> _ 4637 // 4638 // The latter two manglings are from a proposal here: 4639 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117 4640 Out << 'T'; 4641 if (Depth != 0) 4642 Out << 'L' << (Depth - 1) << '_'; 4643 if (Index != 0) 4644 Out << (Index - 1); 4645 Out << '_'; 4646 } 4647 4648 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 4649 if (SeqID == 1) 4650 Out << '0'; 4651 else if (SeqID > 1) { 4652 SeqID--; 4653 4654 // <seq-id> is encoded in base-36, using digits and upper case letters. 4655 char Buffer[7]; // log(2**32) / log(36) ~= 7 4656 MutableArrayRef<char> BufferRef(Buffer); 4657 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 4658 4659 for (; SeqID != 0; SeqID /= 36) { 4660 unsigned C = SeqID % 36; 4661 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 4662 } 4663 4664 Out.write(I.base(), I - BufferRef.rbegin()); 4665 } 4666 Out << '_'; 4667 } 4668 4669 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 4670 bool result = mangleSubstitution(tname); 4671 assert(result && "no existing substitution for template name"); 4672 (void) result; 4673 } 4674 4675 // <substitution> ::= S <seq-id> _ 4676 // ::= S_ 4677 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 4678 // Try one of the standard substitutions first. 4679 if (mangleStandardSubstitution(ND)) 4680 return true; 4681 4682 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 4683 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 4684 } 4685 4686 /// Determine whether the given type has any qualifiers that are relevant for 4687 /// substitutions. 4688 static bool hasMangledSubstitutionQualifiers(QualType T) { 4689 Qualifiers Qs = T.getQualifiers(); 4690 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned(); 4691 } 4692 4693 bool CXXNameMangler::mangleSubstitution(QualType T) { 4694 if (!hasMangledSubstitutionQualifiers(T)) { 4695 if (const RecordType *RT = T->getAs<RecordType>()) 4696 return mangleSubstitution(RT->getDecl()); 4697 } 4698 4699 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 4700 4701 return mangleSubstitution(TypePtr); 4702 } 4703 4704 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 4705 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 4706 return mangleSubstitution(TD); 4707 4708 Template = Context.getASTContext().getCanonicalTemplateName(Template); 4709 return mangleSubstitution( 4710 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 4711 } 4712 4713 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 4714 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 4715 if (I == Substitutions.end()) 4716 return false; 4717 4718 unsigned SeqID = I->second; 4719 Out << 'S'; 4720 mangleSeqID(SeqID); 4721 4722 return true; 4723 } 4724 4725 static bool isCharType(QualType T) { 4726 if (T.isNull()) 4727 return false; 4728 4729 return T->isSpecificBuiltinType(BuiltinType::Char_S) || 4730 T->isSpecificBuiltinType(BuiltinType::Char_U); 4731 } 4732 4733 /// Returns whether a given type is a template specialization of a given name 4734 /// with a single argument of type char. 4735 static bool isCharSpecialization(QualType T, const char *Name) { 4736 if (T.isNull()) 4737 return false; 4738 4739 const RecordType *RT = T->getAs<RecordType>(); 4740 if (!RT) 4741 return false; 4742 4743 const ClassTemplateSpecializationDecl *SD = 4744 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 4745 if (!SD) 4746 return false; 4747 4748 if (!isStdNamespace(getEffectiveDeclContext(SD))) 4749 return false; 4750 4751 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 4752 if (TemplateArgs.size() != 1) 4753 return false; 4754 4755 if (!isCharType(TemplateArgs[0].getAsType())) 4756 return false; 4757 4758 return SD->getIdentifier()->getName() == Name; 4759 } 4760 4761 template <std::size_t StrLen> 4762 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD, 4763 const char (&Str)[StrLen]) { 4764 if (!SD->getIdentifier()->isStr(Str)) 4765 return false; 4766 4767 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 4768 if (TemplateArgs.size() != 2) 4769 return false; 4770 4771 if (!isCharType(TemplateArgs[0].getAsType())) 4772 return false; 4773 4774 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 4775 return false; 4776 4777 return true; 4778 } 4779 4780 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 4781 // <substitution> ::= St # ::std:: 4782 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 4783 if (isStd(NS)) { 4784 Out << "St"; 4785 return true; 4786 } 4787 } 4788 4789 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 4790 if (!isStdNamespace(getEffectiveDeclContext(TD))) 4791 return false; 4792 4793 // <substitution> ::= Sa # ::std::allocator 4794 if (TD->getIdentifier()->isStr("allocator")) { 4795 Out << "Sa"; 4796 return true; 4797 } 4798 4799 // <<substitution> ::= Sb # ::std::basic_string 4800 if (TD->getIdentifier()->isStr("basic_string")) { 4801 Out << "Sb"; 4802 return true; 4803 } 4804 } 4805 4806 if (const ClassTemplateSpecializationDecl *SD = 4807 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 4808 if (!isStdNamespace(getEffectiveDeclContext(SD))) 4809 return false; 4810 4811 // <substitution> ::= Ss # ::std::basic_string<char, 4812 // ::std::char_traits<char>, 4813 // ::std::allocator<char> > 4814 if (SD->getIdentifier()->isStr("basic_string")) { 4815 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 4816 4817 if (TemplateArgs.size() != 3) 4818 return false; 4819 4820 if (!isCharType(TemplateArgs[0].getAsType())) 4821 return false; 4822 4823 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 4824 return false; 4825 4826 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator")) 4827 return false; 4828 4829 Out << "Ss"; 4830 return true; 4831 } 4832 4833 // <substitution> ::= Si # ::std::basic_istream<char, 4834 // ::std::char_traits<char> > 4835 if (isStreamCharSpecialization(SD, "basic_istream")) { 4836 Out << "Si"; 4837 return true; 4838 } 4839 4840 // <substitution> ::= So # ::std::basic_ostream<char, 4841 // ::std::char_traits<char> > 4842 if (isStreamCharSpecialization(SD, "basic_ostream")) { 4843 Out << "So"; 4844 return true; 4845 } 4846 4847 // <substitution> ::= Sd # ::std::basic_iostream<char, 4848 // ::std::char_traits<char> > 4849 if (isStreamCharSpecialization(SD, "basic_iostream")) { 4850 Out << "Sd"; 4851 return true; 4852 } 4853 } 4854 return false; 4855 } 4856 4857 void CXXNameMangler::addSubstitution(QualType T) { 4858 if (!hasMangledSubstitutionQualifiers(T)) { 4859 if (const RecordType *RT = T->getAs<RecordType>()) { 4860 addSubstitution(RT->getDecl()); 4861 return; 4862 } 4863 } 4864 4865 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 4866 addSubstitution(TypePtr); 4867 } 4868 4869 void CXXNameMangler::addSubstitution(TemplateName Template) { 4870 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 4871 return addSubstitution(TD); 4872 4873 Template = Context.getASTContext().getCanonicalTemplateName(Template); 4874 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 4875 } 4876 4877 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 4878 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 4879 Substitutions[Ptr] = SeqID++; 4880 } 4881 4882 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) { 4883 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!"); 4884 if (Other->SeqID > SeqID) { 4885 Substitutions.swap(Other->Substitutions); 4886 SeqID = Other->SeqID; 4887 } 4888 } 4889 4890 CXXNameMangler::AbiTagList 4891 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) { 4892 // When derived abi tags are disabled there is no need to make any list. 4893 if (DisableDerivedAbiTags) 4894 return AbiTagList(); 4895 4896 llvm::raw_null_ostream NullOutStream; 4897 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream); 4898 TrackReturnTypeTags.disableDerivedAbiTags(); 4899 4900 const FunctionProtoType *Proto = 4901 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 4902 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push(); 4903 TrackReturnTypeTags.FunctionTypeDepth.enterResultType(); 4904 TrackReturnTypeTags.mangleType(Proto->getReturnType()); 4905 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType(); 4906 TrackReturnTypeTags.FunctionTypeDepth.pop(saved); 4907 4908 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 4909 } 4910 4911 CXXNameMangler::AbiTagList 4912 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) { 4913 // When derived abi tags are disabled there is no need to make any list. 4914 if (DisableDerivedAbiTags) 4915 return AbiTagList(); 4916 4917 llvm::raw_null_ostream NullOutStream; 4918 CXXNameMangler TrackVariableType(*this, NullOutStream); 4919 TrackVariableType.disableDerivedAbiTags(); 4920 4921 TrackVariableType.mangleType(VD->getType()); 4922 4923 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 4924 } 4925 4926 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C, 4927 const VarDecl *VD) { 4928 llvm::raw_null_ostream NullOutStream; 4929 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true); 4930 TrackAbiTags.mangle(VD); 4931 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size(); 4932 } 4933 4934 // 4935 4936 /// Mangles the name of the declaration D and emits that name to the given 4937 /// output stream. 4938 /// 4939 /// If the declaration D requires a mangled name, this routine will emit that 4940 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 4941 /// and this routine will return false. In this case, the caller should just 4942 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 4943 /// name. 4944 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D, 4945 raw_ostream &Out) { 4946 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) && 4947 "Invalid mangleName() call, argument is not a variable or function!"); 4948 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) && 4949 "Invalid mangleName() call on 'structor decl!"); 4950 4951 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 4952 getASTContext().getSourceManager(), 4953 "Mangling declaration"); 4954 4955 CXXNameMangler Mangler(*this, Out, D); 4956 Mangler.mangle(D); 4957 } 4958 4959 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D, 4960 CXXCtorType Type, 4961 raw_ostream &Out) { 4962 CXXNameMangler Mangler(*this, Out, D, Type); 4963 Mangler.mangle(D); 4964 } 4965 4966 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D, 4967 CXXDtorType Type, 4968 raw_ostream &Out) { 4969 CXXNameMangler Mangler(*this, Out, D, Type); 4970 Mangler.mangle(D); 4971 } 4972 4973 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 4974 raw_ostream &Out) { 4975 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 4976 Mangler.mangle(D); 4977 } 4978 4979 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 4980 raw_ostream &Out) { 4981 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 4982 Mangler.mangle(D); 4983 } 4984 4985 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 4986 const ThunkInfo &Thunk, 4987 raw_ostream &Out) { 4988 // <special-name> ::= T <call-offset> <base encoding> 4989 // # base is the nominal target function of thunk 4990 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 4991 // # base is the nominal target function of thunk 4992 // # first call-offset is 'this' adjustment 4993 // # second call-offset is result adjustment 4994 4995 assert(!isa<CXXDestructorDecl>(MD) && 4996 "Use mangleCXXDtor for destructor decls!"); 4997 CXXNameMangler Mangler(*this, Out); 4998 Mangler.getStream() << "_ZT"; 4999 if (!Thunk.Return.isEmpty()) 5000 Mangler.getStream() << 'c'; 5001 5002 // Mangle the 'this' pointer adjustment. 5003 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 5004 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 5005 5006 // Mangle the return pointer adjustment if there is one. 5007 if (!Thunk.Return.isEmpty()) 5008 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 5009 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 5010 5011 Mangler.mangleFunctionEncoding(MD); 5012 } 5013 5014 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 5015 const CXXDestructorDecl *DD, CXXDtorType Type, 5016 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 5017 // <special-name> ::= T <call-offset> <base encoding> 5018 // # base is the nominal target function of thunk 5019 CXXNameMangler Mangler(*this, Out, DD, Type); 5020 Mangler.getStream() << "_ZT"; 5021 5022 // Mangle the 'this' pointer adjustment. 5023 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 5024 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 5025 5026 Mangler.mangleFunctionEncoding(DD); 5027 } 5028 5029 /// Returns the mangled name for a guard variable for the passed in VarDecl. 5030 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 5031 raw_ostream &Out) { 5032 // <special-name> ::= GV <object name> # Guard variable for one-time 5033 // # initialization 5034 CXXNameMangler Mangler(*this, Out); 5035 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 5036 // be a bug that is fixed in trunk. 5037 Mangler.getStream() << "_ZGV"; 5038 Mangler.mangleName(D); 5039 } 5040 5041 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 5042 raw_ostream &Out) { 5043 // These symbols are internal in the Itanium ABI, so the names don't matter. 5044 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 5045 // avoid duplicate symbols. 5046 Out << "__cxx_global_var_init"; 5047 } 5048 5049 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 5050 raw_ostream &Out) { 5051 // Prefix the mangling of D with __dtor_. 5052 CXXNameMangler Mangler(*this, Out); 5053 Mangler.getStream() << "__dtor_"; 5054 if (shouldMangleDeclName(D)) 5055 Mangler.mangle(D); 5056 else 5057 Mangler.getStream() << D->getName(); 5058 } 5059 5060 void ItaniumMangleContextImpl::mangleSEHFilterExpression( 5061 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 5062 CXXNameMangler Mangler(*this, Out); 5063 Mangler.getStream() << "__filt_"; 5064 if (shouldMangleDeclName(EnclosingDecl)) 5065 Mangler.mangle(EnclosingDecl); 5066 else 5067 Mangler.getStream() << EnclosingDecl->getName(); 5068 } 5069 5070 void ItaniumMangleContextImpl::mangleSEHFinallyBlock( 5071 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 5072 CXXNameMangler Mangler(*this, Out); 5073 Mangler.getStream() << "__fin_"; 5074 if (shouldMangleDeclName(EnclosingDecl)) 5075 Mangler.mangle(EnclosingDecl); 5076 else 5077 Mangler.getStream() << EnclosingDecl->getName(); 5078 } 5079 5080 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 5081 raw_ostream &Out) { 5082 // <special-name> ::= TH <object name> 5083 CXXNameMangler Mangler(*this, Out); 5084 Mangler.getStream() << "_ZTH"; 5085 Mangler.mangleName(D); 5086 } 5087 5088 void 5089 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 5090 raw_ostream &Out) { 5091 // <special-name> ::= TW <object name> 5092 CXXNameMangler Mangler(*this, Out); 5093 Mangler.getStream() << "_ZTW"; 5094 Mangler.mangleName(D); 5095 } 5096 5097 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 5098 unsigned ManglingNumber, 5099 raw_ostream &Out) { 5100 // We match the GCC mangling here. 5101 // <special-name> ::= GR <object name> 5102 CXXNameMangler Mangler(*this, Out); 5103 Mangler.getStream() << "_ZGR"; 5104 Mangler.mangleName(D); 5105 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 5106 Mangler.mangleSeqID(ManglingNumber - 1); 5107 } 5108 5109 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 5110 raw_ostream &Out) { 5111 // <special-name> ::= TV <type> # virtual table 5112 CXXNameMangler Mangler(*this, Out); 5113 Mangler.getStream() << "_ZTV"; 5114 Mangler.mangleNameOrStandardSubstitution(RD); 5115 } 5116 5117 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 5118 raw_ostream &Out) { 5119 // <special-name> ::= TT <type> # VTT structure 5120 CXXNameMangler Mangler(*this, Out); 5121 Mangler.getStream() << "_ZTT"; 5122 Mangler.mangleNameOrStandardSubstitution(RD); 5123 } 5124 5125 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 5126 int64_t Offset, 5127 const CXXRecordDecl *Type, 5128 raw_ostream &Out) { 5129 // <special-name> ::= TC <type> <offset number> _ <base type> 5130 CXXNameMangler Mangler(*this, Out); 5131 Mangler.getStream() << "_ZTC"; 5132 Mangler.mangleNameOrStandardSubstitution(RD); 5133 Mangler.getStream() << Offset; 5134 Mangler.getStream() << '_'; 5135 Mangler.mangleNameOrStandardSubstitution(Type); 5136 } 5137 5138 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 5139 // <special-name> ::= TI <type> # typeinfo structure 5140 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 5141 CXXNameMangler Mangler(*this, Out); 5142 Mangler.getStream() << "_ZTI"; 5143 Mangler.mangleType(Ty); 5144 } 5145 5146 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 5147 raw_ostream &Out) { 5148 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 5149 CXXNameMangler Mangler(*this, Out); 5150 Mangler.getStream() << "_ZTS"; 5151 Mangler.mangleType(Ty); 5152 } 5153 5154 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 5155 mangleCXXRTTIName(Ty, Out); 5156 } 5157 5158 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 5159 llvm_unreachable("Can't mangle string literals"); 5160 } 5161 5162 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda, 5163 raw_ostream &Out) { 5164 CXXNameMangler Mangler(*this, Out); 5165 Mangler.mangleLambdaSig(Lambda); 5166 } 5167 5168 ItaniumMangleContext * 5169 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) { 5170 return new ItaniumMangleContextImpl(Context, Diags); 5171 } 5172