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