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 void CXXNameMangler::mangleType(QualType T) { 1844 // If our type is instantiation-dependent but not dependent, we mangle 1845 // it as it was written in the source, removing any top-level sugar. 1846 // Otherwise, use the canonical type. 1847 // 1848 // FIXME: This is an approximation of the instantiation-dependent name 1849 // mangling rules, since we should really be using the type as written and 1850 // augmented via semantic analysis (i.e., with implicit conversions and 1851 // default template arguments) for any instantiation-dependent type. 1852 // Unfortunately, that requires several changes to our AST: 1853 // - Instantiation-dependent TemplateSpecializationTypes will need to be 1854 // uniqued, so that we can handle substitutions properly 1855 // - Default template arguments will need to be represented in the 1856 // TemplateSpecializationType, since they need to be mangled even though 1857 // they aren't written. 1858 // - Conversions on non-type template arguments need to be expressed, since 1859 // they can affect the mangling of sizeof/alignof. 1860 if (!T->isInstantiationDependentType() || T->isDependentType()) 1861 T = T.getCanonicalType(); 1862 else { 1863 // Desugar any types that are purely sugar. 1864 do { 1865 // Don't desugar through template specialization types that aren't 1866 // type aliases. We need to mangle the template arguments as written. 1867 if (const TemplateSpecializationType *TST 1868 = dyn_cast<TemplateSpecializationType>(T)) 1869 if (!TST->isTypeAlias()) 1870 break; 1871 1872 QualType Desugared 1873 = T.getSingleStepDesugaredType(Context.getASTContext()); 1874 if (Desugared == T) 1875 break; 1876 1877 T = Desugared; 1878 } while (true); 1879 } 1880 SplitQualType split = T.split(); 1881 Qualifiers quals = split.Quals; 1882 const Type *ty = split.Ty; 1883 1884 bool isSubstitutable = quals || !isa<BuiltinType>(T); 1885 if (isSubstitutable && mangleSubstitution(T)) 1886 return; 1887 1888 // If we're mangling a qualified array type, push the qualifiers to 1889 // the element type. 1890 if (quals && isa<ArrayType>(T)) { 1891 ty = Context.getASTContext().getAsArrayType(T); 1892 quals = Qualifiers(); 1893 1894 // Note that we don't update T: we want to add the 1895 // substitution at the original type. 1896 } 1897 1898 if (quals) { 1899 mangleQualifiers(quals); 1900 // Recurse: even if the qualified type isn't yet substitutable, 1901 // the unqualified type might be. 1902 mangleType(QualType(ty, 0)); 1903 } else { 1904 switch (ty->getTypeClass()) { 1905 #define ABSTRACT_TYPE(CLASS, PARENT) 1906 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 1907 case Type::CLASS: \ 1908 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 1909 return; 1910 #define TYPE(CLASS, PARENT) \ 1911 case Type::CLASS: \ 1912 mangleType(static_cast<const CLASS##Type*>(ty)); \ 1913 break; 1914 #include "clang/AST/TypeNodes.def" 1915 } 1916 } 1917 1918 // Add the substitution. 1919 if (isSubstitutable) 1920 addSubstitution(T); 1921 } 1922 1923 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) { 1924 if (!mangleStandardSubstitution(ND)) 1925 mangleName(ND); 1926 } 1927 1928 void CXXNameMangler::mangleType(const BuiltinType *T) { 1929 // <type> ::= <builtin-type> 1930 // <builtin-type> ::= v # void 1931 // ::= w # wchar_t 1932 // ::= b # bool 1933 // ::= c # char 1934 // ::= a # signed char 1935 // ::= h # unsigned char 1936 // ::= s # short 1937 // ::= t # unsigned short 1938 // ::= i # int 1939 // ::= j # unsigned int 1940 // ::= l # long 1941 // ::= m # unsigned long 1942 // ::= x # long long, __int64 1943 // ::= y # unsigned long long, __int64 1944 // ::= n # __int128 1945 // ::= o # unsigned __int128 1946 // ::= f # float 1947 // ::= d # double 1948 // ::= e # long double, __float80 1949 // UNSUPPORTED: ::= g # __float128 1950 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) 1951 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) 1952 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) 1953 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 1954 // ::= Di # char32_t 1955 // ::= Ds # char16_t 1956 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 1957 // ::= u <source-name> # vendor extended type 1958 switch (T->getKind()) { 1959 case BuiltinType::Void: Out << 'v'; break; 1960 case BuiltinType::Bool: Out << 'b'; break; 1961 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break; 1962 case BuiltinType::UChar: Out << 'h'; break; 1963 case BuiltinType::UShort: Out << 't'; break; 1964 case BuiltinType::UInt: Out << 'j'; break; 1965 case BuiltinType::ULong: Out << 'm'; break; 1966 case BuiltinType::ULongLong: Out << 'y'; break; 1967 case BuiltinType::UInt128: Out << 'o'; break; 1968 case BuiltinType::SChar: Out << 'a'; break; 1969 case BuiltinType::WChar_S: 1970 case BuiltinType::WChar_U: Out << 'w'; break; 1971 case BuiltinType::Char16: Out << "Ds"; break; 1972 case BuiltinType::Char32: Out << "Di"; break; 1973 case BuiltinType::Short: Out << 's'; break; 1974 case BuiltinType::Int: Out << 'i'; break; 1975 case BuiltinType::Long: Out << 'l'; break; 1976 case BuiltinType::LongLong: Out << 'x'; break; 1977 case BuiltinType::Int128: Out << 'n'; break; 1978 case BuiltinType::Half: Out << "Dh"; break; 1979 case BuiltinType::Float: Out << 'f'; break; 1980 case BuiltinType::Double: Out << 'd'; break; 1981 case BuiltinType::LongDouble: Out << 'e'; break; 1982 case BuiltinType::NullPtr: Out << "Dn"; break; 1983 1984 #define BUILTIN_TYPE(Id, SingletonId) 1985 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 1986 case BuiltinType::Id: 1987 #include "clang/AST/BuiltinTypes.def" 1988 case BuiltinType::Dependent: 1989 llvm_unreachable("mangling a placeholder type"); 1990 case BuiltinType::ObjCId: Out << "11objc_object"; break; 1991 case BuiltinType::ObjCClass: Out << "10objc_class"; break; 1992 case BuiltinType::ObjCSel: Out << "13objc_selector"; break; 1993 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break; 1994 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break; 1995 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break; 1996 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break; 1997 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break; 1998 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break; 1999 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break; 2000 case BuiltinType::OCLEvent: Out << "9ocl_event"; break; 2001 } 2002 } 2003 2004 // <type> ::= <function-type> 2005 // <function-type> ::= [<CV-qualifiers>] F [Y] 2006 // <bare-function-type> [<ref-qualifier>] E 2007 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 2008 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 2009 // e.g. "const" in "int (A::*)() const". 2010 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals())); 2011 2012 Out << 'F'; 2013 2014 // FIXME: We don't have enough information in the AST to produce the 'Y' 2015 // encoding for extern "C" function types. 2016 mangleBareFunctionType(T, /*MangleReturnType=*/true); 2017 2018 // Mangle the ref-qualifier, if present. 2019 mangleRefQualifier(T->getRefQualifier()); 2020 2021 Out << 'E'; 2022 } 2023 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 2024 llvm_unreachable("Can't mangle K&R function prototypes"); 2025 } 2026 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T, 2027 bool MangleReturnType) { 2028 // We should never be mangling something without a prototype. 2029 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 2030 2031 // Record that we're in a function type. See mangleFunctionParam 2032 // for details on what we're trying to achieve here. 2033 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 2034 2035 // <bare-function-type> ::= <signature type>+ 2036 if (MangleReturnType) { 2037 FunctionTypeDepth.enterResultType(); 2038 mangleType(Proto->getReturnType()); 2039 FunctionTypeDepth.leaveResultType(); 2040 } 2041 2042 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 2043 // <builtin-type> ::= v # void 2044 Out << 'v'; 2045 2046 FunctionTypeDepth.pop(saved); 2047 return; 2048 } 2049 2050 for (const auto &Arg : Proto->param_types()) 2051 mangleType(Context.getASTContext().getSignatureParameterType(Arg)); 2052 2053 FunctionTypeDepth.pop(saved); 2054 2055 // <builtin-type> ::= z # ellipsis 2056 if (Proto->isVariadic()) 2057 Out << 'z'; 2058 } 2059 2060 // <type> ::= <class-enum-type> 2061 // <class-enum-type> ::= <name> 2062 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 2063 mangleName(T->getDecl()); 2064 } 2065 2066 // <type> ::= <class-enum-type> 2067 // <class-enum-type> ::= <name> 2068 void CXXNameMangler::mangleType(const EnumType *T) { 2069 mangleType(static_cast<const TagType*>(T)); 2070 } 2071 void CXXNameMangler::mangleType(const RecordType *T) { 2072 mangleType(static_cast<const TagType*>(T)); 2073 } 2074 void CXXNameMangler::mangleType(const TagType *T) { 2075 mangleName(T->getDecl()); 2076 } 2077 2078 // <type> ::= <array-type> 2079 // <array-type> ::= A <positive dimension number> _ <element type> 2080 // ::= A [<dimension expression>] _ <element type> 2081 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 2082 Out << 'A' << T->getSize() << '_'; 2083 mangleType(T->getElementType()); 2084 } 2085 void CXXNameMangler::mangleType(const VariableArrayType *T) { 2086 Out << 'A'; 2087 // decayed vla types (size 0) will just be skipped. 2088 if (T->getSizeExpr()) 2089 mangleExpression(T->getSizeExpr()); 2090 Out << '_'; 2091 mangleType(T->getElementType()); 2092 } 2093 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 2094 Out << 'A'; 2095 mangleExpression(T->getSizeExpr()); 2096 Out << '_'; 2097 mangleType(T->getElementType()); 2098 } 2099 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 2100 Out << "A_"; 2101 mangleType(T->getElementType()); 2102 } 2103 2104 // <type> ::= <pointer-to-member-type> 2105 // <pointer-to-member-type> ::= M <class type> <member type> 2106 void CXXNameMangler::mangleType(const MemberPointerType *T) { 2107 Out << 'M'; 2108 mangleType(QualType(T->getClass(), 0)); 2109 QualType PointeeType = T->getPointeeType(); 2110 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 2111 mangleType(FPT); 2112 2113 // Itanium C++ ABI 5.1.8: 2114 // 2115 // The type of a non-static member function is considered to be different, 2116 // for the purposes of substitution, from the type of a namespace-scope or 2117 // static member function whose type appears similar. The types of two 2118 // non-static member functions are considered to be different, for the 2119 // purposes of substitution, if the functions are members of different 2120 // classes. In other words, for the purposes of substitution, the class of 2121 // which the function is a member is considered part of the type of 2122 // function. 2123 2124 // Given that we already substitute member function pointers as a 2125 // whole, the net effect of this rule is just to unconditionally 2126 // suppress substitution on the function type in a member pointer. 2127 // We increment the SeqID here to emulate adding an entry to the 2128 // substitution table. 2129 ++SeqID; 2130 } else 2131 mangleType(PointeeType); 2132 } 2133 2134 // <type> ::= <template-param> 2135 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 2136 mangleTemplateParameter(T->getIndex()); 2137 } 2138 2139 // <type> ::= <template-param> 2140 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 2141 // FIXME: not clear how to mangle this! 2142 // template <class T...> class A { 2143 // template <class U...> void foo(T(*)(U) x...); 2144 // }; 2145 Out << "_SUBSTPACK_"; 2146 } 2147 2148 // <type> ::= P <type> # pointer-to 2149 void CXXNameMangler::mangleType(const PointerType *T) { 2150 Out << 'P'; 2151 mangleType(T->getPointeeType()); 2152 } 2153 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 2154 Out << 'P'; 2155 mangleType(T->getPointeeType()); 2156 } 2157 2158 // <type> ::= R <type> # reference-to 2159 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 2160 Out << 'R'; 2161 mangleType(T->getPointeeType()); 2162 } 2163 2164 // <type> ::= O <type> # rvalue reference-to (C++0x) 2165 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 2166 Out << 'O'; 2167 mangleType(T->getPointeeType()); 2168 } 2169 2170 // <type> ::= C <type> # complex pair (C 2000) 2171 void CXXNameMangler::mangleType(const ComplexType *T) { 2172 Out << 'C'; 2173 mangleType(T->getElementType()); 2174 } 2175 2176 // ARM's ABI for Neon vector types specifies that they should be mangled as 2177 // if they are structs (to match ARM's initial implementation). The 2178 // vector type must be one of the special types predefined by ARM. 2179 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 2180 QualType EltType = T->getElementType(); 2181 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 2182 const char *EltName = nullptr; 2183 if (T->getVectorKind() == VectorType::NeonPolyVector) { 2184 switch (cast<BuiltinType>(EltType)->getKind()) { 2185 case BuiltinType::SChar: 2186 case BuiltinType::UChar: 2187 EltName = "poly8_t"; 2188 break; 2189 case BuiltinType::Short: 2190 case BuiltinType::UShort: 2191 EltName = "poly16_t"; 2192 break; 2193 case BuiltinType::ULongLong: 2194 EltName = "poly64_t"; 2195 break; 2196 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 2197 } 2198 } else { 2199 switch (cast<BuiltinType>(EltType)->getKind()) { 2200 case BuiltinType::SChar: EltName = "int8_t"; break; 2201 case BuiltinType::UChar: EltName = "uint8_t"; break; 2202 case BuiltinType::Short: EltName = "int16_t"; break; 2203 case BuiltinType::UShort: EltName = "uint16_t"; break; 2204 case BuiltinType::Int: EltName = "int32_t"; break; 2205 case BuiltinType::UInt: EltName = "uint32_t"; break; 2206 case BuiltinType::LongLong: EltName = "int64_t"; break; 2207 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 2208 case BuiltinType::Double: EltName = "float64_t"; break; 2209 case BuiltinType::Float: EltName = "float32_t"; break; 2210 case BuiltinType::Half: EltName = "float16_t";break; 2211 default: 2212 llvm_unreachable("unexpected Neon vector element type"); 2213 } 2214 } 2215 const char *BaseName = nullptr; 2216 unsigned BitSize = (T->getNumElements() * 2217 getASTContext().getTypeSize(EltType)); 2218 if (BitSize == 64) 2219 BaseName = "__simd64_"; 2220 else { 2221 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 2222 BaseName = "__simd128_"; 2223 } 2224 Out << strlen(BaseName) + strlen(EltName); 2225 Out << BaseName << EltName; 2226 } 2227 2228 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 2229 switch (EltType->getKind()) { 2230 case BuiltinType::SChar: 2231 return "Int8"; 2232 case BuiltinType::Short: 2233 return "Int16"; 2234 case BuiltinType::Int: 2235 return "Int32"; 2236 case BuiltinType::Long: 2237 case BuiltinType::LongLong: 2238 return "Int64"; 2239 case BuiltinType::UChar: 2240 return "Uint8"; 2241 case BuiltinType::UShort: 2242 return "Uint16"; 2243 case BuiltinType::UInt: 2244 return "Uint32"; 2245 case BuiltinType::ULong: 2246 case BuiltinType::ULongLong: 2247 return "Uint64"; 2248 case BuiltinType::Half: 2249 return "Float16"; 2250 case BuiltinType::Float: 2251 return "Float32"; 2252 case BuiltinType::Double: 2253 return "Float64"; 2254 default: 2255 llvm_unreachable("Unexpected vector element base type"); 2256 } 2257 } 2258 2259 // AArch64's ABI for Neon vector types specifies that they should be mangled as 2260 // the equivalent internal name. The vector type must be one of the special 2261 // types predefined by ARM. 2262 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 2263 QualType EltType = T->getElementType(); 2264 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 2265 unsigned BitSize = 2266 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 2267 (void)BitSize; // Silence warning. 2268 2269 assert((BitSize == 64 || BitSize == 128) && 2270 "Neon vector type not 64 or 128 bits"); 2271 2272 StringRef EltName; 2273 if (T->getVectorKind() == VectorType::NeonPolyVector) { 2274 switch (cast<BuiltinType>(EltType)->getKind()) { 2275 case BuiltinType::UChar: 2276 EltName = "Poly8"; 2277 break; 2278 case BuiltinType::UShort: 2279 EltName = "Poly16"; 2280 break; 2281 case BuiltinType::ULong: 2282 EltName = "Poly64"; 2283 break; 2284 default: 2285 llvm_unreachable("unexpected Neon polynomial vector element type"); 2286 } 2287 } else 2288 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 2289 2290 std::string TypeName = 2291 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str(); 2292 Out << TypeName.length() << TypeName; 2293 } 2294 2295 // GNU extension: vector types 2296 // <type> ::= <vector-type> 2297 // <vector-type> ::= Dv <positive dimension number> _ 2298 // <extended element type> 2299 // ::= Dv [<dimension expression>] _ <element type> 2300 // <extended element type> ::= <element type> 2301 // ::= p # AltiVec vector pixel 2302 // ::= b # Altivec vector bool 2303 void CXXNameMangler::mangleType(const VectorType *T) { 2304 if ((T->getVectorKind() == VectorType::NeonVector || 2305 T->getVectorKind() == VectorType::NeonPolyVector)) { 2306 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 2307 llvm::Triple::ArchType Arch = 2308 getASTContext().getTargetInfo().getTriple().getArch(); 2309 if ((Arch == llvm::Triple::aarch64 || 2310 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 2311 mangleAArch64NeonVectorType(T); 2312 else 2313 mangleNeonVectorType(T); 2314 return; 2315 } 2316 Out << "Dv" << T->getNumElements() << '_'; 2317 if (T->getVectorKind() == VectorType::AltiVecPixel) 2318 Out << 'p'; 2319 else if (T->getVectorKind() == VectorType::AltiVecBool) 2320 Out << 'b'; 2321 else 2322 mangleType(T->getElementType()); 2323 } 2324 void CXXNameMangler::mangleType(const ExtVectorType *T) { 2325 mangleType(static_cast<const VectorType*>(T)); 2326 } 2327 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 2328 Out << "Dv"; 2329 mangleExpression(T->getSizeExpr()); 2330 Out << '_'; 2331 mangleType(T->getElementType()); 2332 } 2333 2334 void CXXNameMangler::mangleType(const PackExpansionType *T) { 2335 // <type> ::= Dp <type> # pack expansion (C++0x) 2336 Out << "Dp"; 2337 mangleType(T->getPattern()); 2338 } 2339 2340 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 2341 mangleSourceName(T->getDecl()->getIdentifier()); 2342 } 2343 2344 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 2345 if (!T->qual_empty()) { 2346 // Mangle protocol qualifiers. 2347 SmallString<64> QualStr; 2348 llvm::raw_svector_ostream QualOS(QualStr); 2349 QualOS << "objcproto"; 2350 for (const auto *I : T->quals()) { 2351 StringRef name = I->getName(); 2352 QualOS << name.size() << name; 2353 } 2354 QualOS.flush(); 2355 Out << 'U' << QualStr.size() << QualStr; 2356 } 2357 mangleType(T->getBaseType()); 2358 } 2359 2360 void CXXNameMangler::mangleType(const BlockPointerType *T) { 2361 Out << "U13block_pointer"; 2362 mangleType(T->getPointeeType()); 2363 } 2364 2365 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 2366 // Mangle injected class name types as if the user had written the 2367 // specialization out fully. It may not actually be possible to see 2368 // this mangling, though. 2369 mangleType(T->getInjectedSpecializationType()); 2370 } 2371 2372 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 2373 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 2374 mangleName(TD, T->getArgs(), T->getNumArgs()); 2375 } else { 2376 if (mangleSubstitution(QualType(T, 0))) 2377 return; 2378 2379 mangleTemplatePrefix(T->getTemplateName()); 2380 2381 // FIXME: GCC does not appear to mangle the template arguments when 2382 // the template in question is a dependent template name. Should we 2383 // emulate that badness? 2384 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 2385 addSubstitution(QualType(T, 0)); 2386 } 2387 } 2388 2389 void CXXNameMangler::mangleType(const DependentNameType *T) { 2390 // Proposal by cxx-abi-dev, 2014-03-26 2391 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 2392 // # dependent elaborated type specifier using 2393 // # 'typename' 2394 // ::= Ts <name> # dependent elaborated type specifier using 2395 // # 'struct' or 'class' 2396 // ::= Tu <name> # dependent elaborated type specifier using 2397 // # 'union' 2398 // ::= Te <name> # dependent elaborated type specifier using 2399 // # 'enum' 2400 switch (T->getKeyword()) { 2401 case ETK_Typename: 2402 break; 2403 case ETK_Struct: 2404 case ETK_Class: 2405 case ETK_Interface: 2406 Out << "Ts"; 2407 break; 2408 case ETK_Union: 2409 Out << "Tu"; 2410 break; 2411 case ETK_Enum: 2412 Out << "Te"; 2413 break; 2414 default: 2415 llvm_unreachable("unexpected keyword for dependent type name"); 2416 } 2417 // Typename types are always nested 2418 Out << 'N'; 2419 manglePrefix(T->getQualifier()); 2420 mangleSourceName(T->getIdentifier()); 2421 Out << 'E'; 2422 } 2423 2424 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 2425 // Dependently-scoped template types are nested if they have a prefix. 2426 Out << 'N'; 2427 2428 // TODO: avoid making this TemplateName. 2429 TemplateName Prefix = 2430 getASTContext().getDependentTemplateName(T->getQualifier(), 2431 T->getIdentifier()); 2432 mangleTemplatePrefix(Prefix); 2433 2434 // FIXME: GCC does not appear to mangle the template arguments when 2435 // the template in question is a dependent template name. Should we 2436 // emulate that badness? 2437 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 2438 Out << 'E'; 2439 } 2440 2441 void CXXNameMangler::mangleType(const TypeOfType *T) { 2442 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 2443 // "extension with parameters" mangling. 2444 Out << "u6typeof"; 2445 } 2446 2447 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 2448 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 2449 // "extension with parameters" mangling. 2450 Out << "u6typeof"; 2451 } 2452 2453 void CXXNameMangler::mangleType(const DecltypeType *T) { 2454 Expr *E = T->getUnderlyingExpr(); 2455 2456 // type ::= Dt <expression> E # decltype of an id-expression 2457 // # or class member access 2458 // ::= DT <expression> E # decltype of an expression 2459 2460 // This purports to be an exhaustive list of id-expressions and 2461 // class member accesses. Note that we do not ignore parentheses; 2462 // parentheses change the semantics of decltype for these 2463 // expressions (and cause the mangler to use the other form). 2464 if (isa<DeclRefExpr>(E) || 2465 isa<MemberExpr>(E) || 2466 isa<UnresolvedLookupExpr>(E) || 2467 isa<DependentScopeDeclRefExpr>(E) || 2468 isa<CXXDependentScopeMemberExpr>(E) || 2469 isa<UnresolvedMemberExpr>(E)) 2470 Out << "Dt"; 2471 else 2472 Out << "DT"; 2473 mangleExpression(E); 2474 Out << 'E'; 2475 } 2476 2477 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 2478 // If this is dependent, we need to record that. If not, we simply 2479 // mangle it as the underlying type since they are equivalent. 2480 if (T->isDependentType()) { 2481 Out << 'U'; 2482 2483 switch (T->getUTTKind()) { 2484 case UnaryTransformType::EnumUnderlyingType: 2485 Out << "3eut"; 2486 break; 2487 } 2488 } 2489 2490 mangleType(T->getUnderlyingType()); 2491 } 2492 2493 void CXXNameMangler::mangleType(const AutoType *T) { 2494 QualType D = T->getDeducedType(); 2495 // <builtin-type> ::= Da # dependent auto 2496 if (D.isNull()) 2497 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 2498 else 2499 mangleType(D); 2500 } 2501 2502 void CXXNameMangler::mangleType(const AtomicType *T) { 2503 // <type> ::= U <source-name> <type> # vendor extended type qualifier 2504 // (Until there's a standardized mangling...) 2505 Out << "U7_Atomic"; 2506 mangleType(T->getValueType()); 2507 } 2508 2509 void CXXNameMangler::mangleIntegerLiteral(QualType T, 2510 const llvm::APSInt &Value) { 2511 // <expr-primary> ::= L <type> <value number> E # integer literal 2512 Out << 'L'; 2513 2514 mangleType(T); 2515 if (T->isBooleanType()) { 2516 // Boolean values are encoded as 0/1. 2517 Out << (Value.getBoolValue() ? '1' : '0'); 2518 } else { 2519 mangleNumber(Value); 2520 } 2521 Out << 'E'; 2522 2523 } 2524 2525 /// Mangles a member expression. 2526 void CXXNameMangler::mangleMemberExpr(const Expr *base, 2527 bool isArrow, 2528 NestedNameSpecifier *qualifier, 2529 NamedDecl *firstQualifierLookup, 2530 DeclarationName member, 2531 unsigned arity) { 2532 // <expression> ::= dt <expression> <unresolved-name> 2533 // ::= pt <expression> <unresolved-name> 2534 if (base) { 2535 2536 // Ignore member expressions involving anonymous unions. 2537 while (const auto *RT = base->getType()->getAs<RecordType>()) { 2538 if (!RT->getDecl()->isAnonymousStructOrUnion()) 2539 break; 2540 const auto *ME = dyn_cast<MemberExpr>(base); 2541 if (!ME) 2542 break; 2543 base = ME->getBase(); 2544 isArrow = ME->isArrow(); 2545 } 2546 2547 if (base->isImplicitCXXThis()) { 2548 // Note: GCC mangles member expressions to the implicit 'this' as 2549 // *this., whereas we represent them as this->. The Itanium C++ ABI 2550 // does not specify anything here, so we follow GCC. 2551 Out << "dtdefpT"; 2552 } else { 2553 Out << (isArrow ? "pt" : "dt"); 2554 mangleExpression(base); 2555 } 2556 } 2557 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity); 2558 } 2559 2560 /// Look at the callee of the given call expression and determine if 2561 /// it's a parenthesized id-expression which would have triggered ADL 2562 /// otherwise. 2563 static bool isParenthesizedADLCallee(const CallExpr *call) { 2564 const Expr *callee = call->getCallee(); 2565 const Expr *fn = callee->IgnoreParens(); 2566 2567 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 2568 // too, but for those to appear in the callee, it would have to be 2569 // parenthesized. 2570 if (callee == fn) return false; 2571 2572 // Must be an unresolved lookup. 2573 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 2574 if (!lookup) return false; 2575 2576 assert(!lookup->requiresADL()); 2577 2578 // Must be an unqualified lookup. 2579 if (lookup->getQualifier()) return false; 2580 2581 // Must not have found a class member. Note that if one is a class 2582 // member, they're all class members. 2583 if (lookup->getNumDecls() > 0 && 2584 (*lookup->decls_begin())->isCXXClassMember()) 2585 return false; 2586 2587 // Otherwise, ADL would have been triggered. 2588 return true; 2589 } 2590 2591 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 2592 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 2593 Out << CastEncoding; 2594 mangleType(ECE->getType()); 2595 mangleExpression(ECE->getSubExpr()); 2596 } 2597 2598 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { 2599 // <expression> ::= <unary operator-name> <expression> 2600 // ::= <binary operator-name> <expression> <expression> 2601 // ::= <trinary operator-name> <expression> <expression> <expression> 2602 // ::= cv <type> expression # conversion with one argument 2603 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 2604 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 2605 // ::= sc <type> <expression> # static_cast<type> (expression) 2606 // ::= cc <type> <expression> # const_cast<type> (expression) 2607 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 2608 // ::= st <type> # sizeof (a type) 2609 // ::= at <type> # alignof (a type) 2610 // ::= <template-param> 2611 // ::= <function-param> 2612 // ::= sr <type> <unqualified-name> # dependent name 2613 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 2614 // ::= ds <expression> <expression> # expr.*expr 2615 // ::= sZ <template-param> # size of a parameter pack 2616 // ::= sZ <function-param> # size of a function parameter pack 2617 // ::= <expr-primary> 2618 // <expr-primary> ::= L <type> <value number> E # integer literal 2619 // ::= L <type <value float> E # floating literal 2620 // ::= L <mangled-name> E # external name 2621 // ::= fpT # 'this' expression 2622 QualType ImplicitlyConvertedToType; 2623 2624 recurse: 2625 switch (E->getStmtClass()) { 2626 case Expr::NoStmtClass: 2627 #define ABSTRACT_STMT(Type) 2628 #define EXPR(Type, Base) 2629 #define STMT(Type, Base) \ 2630 case Expr::Type##Class: 2631 #include "clang/AST/StmtNodes.inc" 2632 // fallthrough 2633 2634 // These all can only appear in local or variable-initialization 2635 // contexts and so should never appear in a mangling. 2636 case Expr::AddrLabelExprClass: 2637 case Expr::DesignatedInitExprClass: 2638 case Expr::ImplicitValueInitExprClass: 2639 case Expr::ParenListExprClass: 2640 case Expr::LambdaExprClass: 2641 case Expr::MSPropertyRefExprClass: 2642 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 2643 llvm_unreachable("unexpected statement kind"); 2644 2645 // FIXME: invent manglings for all these. 2646 case Expr::BlockExprClass: 2647 case Expr::CXXPseudoDestructorExprClass: 2648 case Expr::ChooseExprClass: 2649 case Expr::CompoundLiteralExprClass: 2650 case Expr::ExtVectorElementExprClass: 2651 case Expr::GenericSelectionExprClass: 2652 case Expr::ObjCEncodeExprClass: 2653 case Expr::ObjCIsaExprClass: 2654 case Expr::ObjCIvarRefExprClass: 2655 case Expr::ObjCMessageExprClass: 2656 case Expr::ObjCPropertyRefExprClass: 2657 case Expr::ObjCProtocolExprClass: 2658 case Expr::ObjCSelectorExprClass: 2659 case Expr::ObjCStringLiteralClass: 2660 case Expr::ObjCBoxedExprClass: 2661 case Expr::ObjCArrayLiteralClass: 2662 case Expr::ObjCDictionaryLiteralClass: 2663 case Expr::ObjCSubscriptRefExprClass: 2664 case Expr::ObjCIndirectCopyRestoreExprClass: 2665 case Expr::OffsetOfExprClass: 2666 case Expr::PredefinedExprClass: 2667 case Expr::ShuffleVectorExprClass: 2668 case Expr::ConvertVectorExprClass: 2669 case Expr::StmtExprClass: 2670 case Expr::TypeTraitExprClass: 2671 case Expr::ArrayTypeTraitExprClass: 2672 case Expr::ExpressionTraitExprClass: 2673 case Expr::VAArgExprClass: 2674 case Expr::CUDAKernelCallExprClass: 2675 case Expr::AsTypeExprClass: 2676 case Expr::PseudoObjectExprClass: 2677 case Expr::AtomicExprClass: 2678 { 2679 // As bad as this diagnostic is, it's better than crashing. 2680 DiagnosticsEngine &Diags = Context.getDiags(); 2681 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2682 "cannot yet mangle expression type %0"); 2683 Diags.Report(E->getExprLoc(), DiagID) 2684 << E->getStmtClassName() << E->getSourceRange(); 2685 break; 2686 } 2687 2688 case Expr::CXXUuidofExprClass: { 2689 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 2690 if (UE->isTypeOperand()) { 2691 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 2692 Out << "u8__uuidoft"; 2693 mangleType(UuidT); 2694 } else { 2695 Expr *UuidExp = UE->getExprOperand(); 2696 Out << "u8__uuidofz"; 2697 mangleExpression(UuidExp, Arity); 2698 } 2699 break; 2700 } 2701 2702 // Even gcc-4.5 doesn't mangle this. 2703 case Expr::BinaryConditionalOperatorClass: { 2704 DiagnosticsEngine &Diags = Context.getDiags(); 2705 unsigned DiagID = 2706 Diags.getCustomDiagID(DiagnosticsEngine::Error, 2707 "?: operator with omitted middle operand cannot be mangled"); 2708 Diags.Report(E->getExprLoc(), DiagID) 2709 << E->getStmtClassName() << E->getSourceRange(); 2710 break; 2711 } 2712 2713 // These are used for internal purposes and cannot be meaningfully mangled. 2714 case Expr::OpaqueValueExprClass: 2715 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 2716 2717 case Expr::InitListExprClass: { 2718 Out << "il"; 2719 const InitListExpr *InitList = cast<InitListExpr>(E); 2720 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 2721 mangleExpression(InitList->getInit(i)); 2722 Out << "E"; 2723 break; 2724 } 2725 2726 case Expr::CXXDefaultArgExprClass: 2727 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity); 2728 break; 2729 2730 case Expr::CXXDefaultInitExprClass: 2731 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity); 2732 break; 2733 2734 case Expr::CXXStdInitializerListExprClass: 2735 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity); 2736 break; 2737 2738 case Expr::SubstNonTypeTemplateParmExprClass: 2739 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), 2740 Arity); 2741 break; 2742 2743 case Expr::UserDefinedLiteralClass: 2744 // We follow g++'s approach of mangling a UDL as a call to the literal 2745 // operator. 2746 case Expr::CXXMemberCallExprClass: // fallthrough 2747 case Expr::CallExprClass: { 2748 const CallExpr *CE = cast<CallExpr>(E); 2749 2750 // <expression> ::= cp <simple-id> <expression>* E 2751 // We use this mangling only when the call would use ADL except 2752 // for being parenthesized. Per discussion with David 2753 // Vandervoorde, 2011.04.25. 2754 if (isParenthesizedADLCallee(CE)) { 2755 Out << "cp"; 2756 // The callee here is a parenthesized UnresolvedLookupExpr with 2757 // no qualifier and should always get mangled as a <simple-id> 2758 // anyway. 2759 2760 // <expression> ::= cl <expression>* E 2761 } else { 2762 Out << "cl"; 2763 } 2764 2765 mangleExpression(CE->getCallee(), CE->getNumArgs()); 2766 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I) 2767 mangleExpression(CE->getArg(I)); 2768 Out << 'E'; 2769 break; 2770 } 2771 2772 case Expr::CXXNewExprClass: { 2773 const CXXNewExpr *New = cast<CXXNewExpr>(E); 2774 if (New->isGlobalNew()) Out << "gs"; 2775 Out << (New->isArray() ? "na" : "nw"); 2776 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 2777 E = New->placement_arg_end(); I != E; ++I) 2778 mangleExpression(*I); 2779 Out << '_'; 2780 mangleType(New->getAllocatedType()); 2781 if (New->hasInitializer()) { 2782 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 2783 Out << "il"; 2784 else 2785 Out << "pi"; 2786 const Expr *Init = New->getInitializer(); 2787 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 2788 // Directly inline the initializers. 2789 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 2790 E = CCE->arg_end(); 2791 I != E; ++I) 2792 mangleExpression(*I); 2793 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 2794 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 2795 mangleExpression(PLE->getExpr(i)); 2796 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 2797 isa<InitListExpr>(Init)) { 2798 // Only take InitListExprs apart for list-initialization. 2799 const InitListExpr *InitList = cast<InitListExpr>(Init); 2800 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 2801 mangleExpression(InitList->getInit(i)); 2802 } else 2803 mangleExpression(Init); 2804 } 2805 Out << 'E'; 2806 break; 2807 } 2808 2809 case Expr::MemberExprClass: { 2810 const MemberExpr *ME = cast<MemberExpr>(E); 2811 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2812 ME->getQualifier(), nullptr, 2813 ME->getMemberDecl()->getDeclName(), Arity); 2814 break; 2815 } 2816 2817 case Expr::UnresolvedMemberExprClass: { 2818 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 2819 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2820 ME->getQualifier(), nullptr, ME->getMemberName(), 2821 Arity); 2822 if (ME->hasExplicitTemplateArgs()) 2823 mangleTemplateArgs(ME->getExplicitTemplateArgs()); 2824 break; 2825 } 2826 2827 case Expr::CXXDependentScopeMemberExprClass: { 2828 const CXXDependentScopeMemberExpr *ME 2829 = cast<CXXDependentScopeMemberExpr>(E); 2830 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2831 ME->getQualifier(), ME->getFirstQualifierFoundInScope(), 2832 ME->getMember(), Arity); 2833 if (ME->hasExplicitTemplateArgs()) 2834 mangleTemplateArgs(ME->getExplicitTemplateArgs()); 2835 break; 2836 } 2837 2838 case Expr::UnresolvedLookupExprClass: { 2839 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 2840 mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity); 2841 2842 // All the <unresolved-name> productions end in a 2843 // base-unresolved-name, where <template-args> are just tacked 2844 // onto the end. 2845 if (ULE->hasExplicitTemplateArgs()) 2846 mangleTemplateArgs(ULE->getExplicitTemplateArgs()); 2847 break; 2848 } 2849 2850 case Expr::CXXUnresolvedConstructExprClass: { 2851 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 2852 unsigned N = CE->arg_size(); 2853 2854 Out << "cv"; 2855 mangleType(CE->getType()); 2856 if (N != 1) Out << '_'; 2857 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 2858 if (N != 1) Out << 'E'; 2859 break; 2860 } 2861 2862 case Expr::CXXTemporaryObjectExprClass: 2863 case Expr::CXXConstructExprClass: { 2864 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E); 2865 unsigned N = CE->getNumArgs(); 2866 2867 if (CE->isListInitialization()) 2868 Out << "tl"; 2869 else 2870 Out << "cv"; 2871 mangleType(CE->getType()); 2872 if (N != 1) Out << '_'; 2873 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 2874 if (N != 1) Out << 'E'; 2875 break; 2876 } 2877 2878 case Expr::CXXScalarValueInitExprClass: 2879 Out <<"cv"; 2880 mangleType(E->getType()); 2881 Out <<"_E"; 2882 break; 2883 2884 case Expr::CXXNoexceptExprClass: 2885 Out << "nx"; 2886 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 2887 break; 2888 2889 case Expr::UnaryExprOrTypeTraitExprClass: { 2890 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 2891 2892 if (!SAE->isInstantiationDependent()) { 2893 // Itanium C++ ABI: 2894 // If the operand of a sizeof or alignof operator is not 2895 // instantiation-dependent it is encoded as an integer literal 2896 // reflecting the result of the operator. 2897 // 2898 // If the result of the operator is implicitly converted to a known 2899 // integer type, that type is used for the literal; otherwise, the type 2900 // of std::size_t or std::ptrdiff_t is used. 2901 QualType T = (ImplicitlyConvertedToType.isNull() || 2902 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 2903 : ImplicitlyConvertedToType; 2904 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 2905 mangleIntegerLiteral(T, V); 2906 break; 2907 } 2908 2909 switch(SAE->getKind()) { 2910 case UETT_SizeOf: 2911 Out << 's'; 2912 break; 2913 case UETT_AlignOf: 2914 Out << 'a'; 2915 break; 2916 case UETT_VecStep: 2917 DiagnosticsEngine &Diags = Context.getDiags(); 2918 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2919 "cannot yet mangle vec_step expression"); 2920 Diags.Report(DiagID); 2921 return; 2922 } 2923 if (SAE->isArgumentType()) { 2924 Out << 't'; 2925 mangleType(SAE->getArgumentType()); 2926 } else { 2927 Out << 'z'; 2928 mangleExpression(SAE->getArgumentExpr()); 2929 } 2930 break; 2931 } 2932 2933 case Expr::CXXThrowExprClass: { 2934 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 2935 // <expression> ::= tw <expression> # throw expression 2936 // ::= tr # rethrow 2937 if (TE->getSubExpr()) { 2938 Out << "tw"; 2939 mangleExpression(TE->getSubExpr()); 2940 } else { 2941 Out << "tr"; 2942 } 2943 break; 2944 } 2945 2946 case Expr::CXXTypeidExprClass: { 2947 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 2948 // <expression> ::= ti <type> # typeid (type) 2949 // ::= te <expression> # typeid (expression) 2950 if (TIE->isTypeOperand()) { 2951 Out << "ti"; 2952 mangleType(TIE->getTypeOperand(Context.getASTContext())); 2953 } else { 2954 Out << "te"; 2955 mangleExpression(TIE->getExprOperand()); 2956 } 2957 break; 2958 } 2959 2960 case Expr::CXXDeleteExprClass: { 2961 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 2962 // <expression> ::= [gs] dl <expression> # [::] delete expr 2963 // ::= [gs] da <expression> # [::] delete [] expr 2964 if (DE->isGlobalDelete()) Out << "gs"; 2965 Out << (DE->isArrayForm() ? "da" : "dl"); 2966 mangleExpression(DE->getArgument()); 2967 break; 2968 } 2969 2970 case Expr::UnaryOperatorClass: { 2971 const UnaryOperator *UO = cast<UnaryOperator>(E); 2972 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 2973 /*Arity=*/1); 2974 mangleExpression(UO->getSubExpr()); 2975 break; 2976 } 2977 2978 case Expr::ArraySubscriptExprClass: { 2979 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 2980 2981 // Array subscript is treated as a syntactically weird form of 2982 // binary operator. 2983 Out << "ix"; 2984 mangleExpression(AE->getLHS()); 2985 mangleExpression(AE->getRHS()); 2986 break; 2987 } 2988 2989 case Expr::CompoundAssignOperatorClass: // fallthrough 2990 case Expr::BinaryOperatorClass: { 2991 const BinaryOperator *BO = cast<BinaryOperator>(E); 2992 if (BO->getOpcode() == BO_PtrMemD) 2993 Out << "ds"; 2994 else 2995 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 2996 /*Arity=*/2); 2997 mangleExpression(BO->getLHS()); 2998 mangleExpression(BO->getRHS()); 2999 break; 3000 } 3001 3002 case Expr::ConditionalOperatorClass: { 3003 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 3004 mangleOperatorName(OO_Conditional, /*Arity=*/3); 3005 mangleExpression(CO->getCond()); 3006 mangleExpression(CO->getLHS(), Arity); 3007 mangleExpression(CO->getRHS(), Arity); 3008 break; 3009 } 3010 3011 case Expr::ImplicitCastExprClass: { 3012 ImplicitlyConvertedToType = E->getType(); 3013 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 3014 goto recurse; 3015 } 3016 3017 case Expr::ObjCBridgedCastExprClass: { 3018 // Mangle ownership casts as a vendor extended operator __bridge, 3019 // __bridge_transfer, or __bridge_retain. 3020 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 3021 Out << "v1U" << Kind.size() << Kind; 3022 } 3023 // Fall through to mangle the cast itself. 3024 3025 case Expr::CStyleCastExprClass: 3026 case Expr::CXXFunctionalCastExprClass: 3027 mangleCastExpression(E, "cv"); 3028 break; 3029 3030 case Expr::CXXStaticCastExprClass: 3031 mangleCastExpression(E, "sc"); 3032 break; 3033 case Expr::CXXDynamicCastExprClass: 3034 mangleCastExpression(E, "dc"); 3035 break; 3036 case Expr::CXXReinterpretCastExprClass: 3037 mangleCastExpression(E, "rc"); 3038 break; 3039 case Expr::CXXConstCastExprClass: 3040 mangleCastExpression(E, "cc"); 3041 break; 3042 3043 case Expr::CXXOperatorCallExprClass: { 3044 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 3045 unsigned NumArgs = CE->getNumArgs(); 3046 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 3047 // Mangle the arguments. 3048 for (unsigned i = 0; i != NumArgs; ++i) 3049 mangleExpression(CE->getArg(i)); 3050 break; 3051 } 3052 3053 case Expr::ParenExprClass: 3054 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity); 3055 break; 3056 3057 case Expr::DeclRefExprClass: { 3058 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 3059 3060 switch (D->getKind()) { 3061 default: 3062 // <expr-primary> ::= L <mangled-name> E # external name 3063 Out << 'L'; 3064 mangle(D, "_Z"); 3065 Out << 'E'; 3066 break; 3067 3068 case Decl::ParmVar: 3069 mangleFunctionParam(cast<ParmVarDecl>(D)); 3070 break; 3071 3072 case Decl::EnumConstant: { 3073 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 3074 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 3075 break; 3076 } 3077 3078 case Decl::NonTypeTemplateParm: { 3079 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 3080 mangleTemplateParameter(PD->getIndex()); 3081 break; 3082 } 3083 3084 } 3085 3086 break; 3087 } 3088 3089 case Expr::SubstNonTypeTemplateParmPackExprClass: 3090 // FIXME: not clear how to mangle this! 3091 // template <unsigned N...> class A { 3092 // template <class U...> void foo(U (&x)[N]...); 3093 // }; 3094 Out << "_SUBSTPACK_"; 3095 break; 3096 3097 case Expr::FunctionParmPackExprClass: { 3098 // FIXME: not clear how to mangle this! 3099 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 3100 Out << "v110_SUBSTPACK"; 3101 mangleFunctionParam(FPPE->getParameterPack()); 3102 break; 3103 } 3104 3105 case Expr::DependentScopeDeclRefExprClass: { 3106 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 3107 mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(), 3108 Arity); 3109 3110 // All the <unresolved-name> productions end in a 3111 // base-unresolved-name, where <template-args> are just tacked 3112 // onto the end. 3113 if (DRE->hasExplicitTemplateArgs()) 3114 mangleTemplateArgs(DRE->getExplicitTemplateArgs()); 3115 break; 3116 } 3117 3118 case Expr::CXXBindTemporaryExprClass: 3119 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr()); 3120 break; 3121 3122 case Expr::ExprWithCleanupsClass: 3123 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity); 3124 break; 3125 3126 case Expr::FloatingLiteralClass: { 3127 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 3128 Out << 'L'; 3129 mangleType(FL->getType()); 3130 mangleFloat(FL->getValue()); 3131 Out << 'E'; 3132 break; 3133 } 3134 3135 case Expr::CharacterLiteralClass: 3136 Out << 'L'; 3137 mangleType(E->getType()); 3138 Out << cast<CharacterLiteral>(E)->getValue(); 3139 Out << 'E'; 3140 break; 3141 3142 // FIXME. __objc_yes/__objc_no are mangled same as true/false 3143 case Expr::ObjCBoolLiteralExprClass: 3144 Out << "Lb"; 3145 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 3146 Out << 'E'; 3147 break; 3148 3149 case Expr::CXXBoolLiteralExprClass: 3150 Out << "Lb"; 3151 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 3152 Out << 'E'; 3153 break; 3154 3155 case Expr::IntegerLiteralClass: { 3156 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 3157 if (E->getType()->isSignedIntegerType()) 3158 Value.setIsSigned(true); 3159 mangleIntegerLiteral(E->getType(), Value); 3160 break; 3161 } 3162 3163 case Expr::ImaginaryLiteralClass: { 3164 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 3165 // Mangle as if a complex literal. 3166 // Proposal from David Vandevoorde, 2010.06.30. 3167 Out << 'L'; 3168 mangleType(E->getType()); 3169 if (const FloatingLiteral *Imag = 3170 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 3171 // Mangle a floating-point zero of the appropriate type. 3172 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 3173 Out << '_'; 3174 mangleFloat(Imag->getValue()); 3175 } else { 3176 Out << "0_"; 3177 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 3178 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 3179 Value.setIsSigned(true); 3180 mangleNumber(Value); 3181 } 3182 Out << 'E'; 3183 break; 3184 } 3185 3186 case Expr::StringLiteralClass: { 3187 // Revised proposal from David Vandervoorde, 2010.07.15. 3188 Out << 'L'; 3189 assert(isa<ConstantArrayType>(E->getType())); 3190 mangleType(E->getType()); 3191 Out << 'E'; 3192 break; 3193 } 3194 3195 case Expr::GNUNullExprClass: 3196 // FIXME: should this really be mangled the same as nullptr? 3197 // fallthrough 3198 3199 case Expr::CXXNullPtrLiteralExprClass: { 3200 Out << "LDnE"; 3201 break; 3202 } 3203 3204 case Expr::PackExpansionExprClass: 3205 Out << "sp"; 3206 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 3207 break; 3208 3209 case Expr::SizeOfPackExprClass: { 3210 Out << "sZ"; 3211 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack(); 3212 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 3213 mangleTemplateParameter(TTP->getIndex()); 3214 else if (const NonTypeTemplateParmDecl *NTTP 3215 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 3216 mangleTemplateParameter(NTTP->getIndex()); 3217 else if (const TemplateTemplateParmDecl *TempTP 3218 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 3219 mangleTemplateParameter(TempTP->getIndex()); 3220 else 3221 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 3222 break; 3223 } 3224 3225 case Expr::MaterializeTemporaryExprClass: { 3226 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()); 3227 break; 3228 } 3229 3230 case Expr::CXXFoldExprClass: { 3231 auto *FE = cast<CXXFoldExpr>(E); 3232 if (FE->isLeftFold()) 3233 Out << (FE->getInit() ? "fL" : "fl"); 3234 else 3235 Out << (FE->getInit() ? "fR" : "fr"); 3236 3237 if (FE->getOperator() == BO_PtrMemD) 3238 Out << "ds"; 3239 else 3240 mangleOperatorName( 3241 BinaryOperator::getOverloadedOperator(FE->getOperator()), 3242 /*Arity=*/2); 3243 3244 if (FE->getLHS()) 3245 mangleExpression(FE->getLHS()); 3246 if (FE->getRHS()) 3247 mangleExpression(FE->getRHS()); 3248 break; 3249 } 3250 3251 case Expr::CXXThisExprClass: 3252 Out << "fpT"; 3253 break; 3254 } 3255 } 3256 3257 /// Mangle an expression which refers to a parameter variable. 3258 /// 3259 /// <expression> ::= <function-param> 3260 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 3261 /// <function-param> ::= fp <top-level CV-qualifiers> 3262 /// <parameter-2 non-negative number> _ # L == 0, I > 0 3263 /// <function-param> ::= fL <L-1 non-negative number> 3264 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 3265 /// <function-param> ::= fL <L-1 non-negative number> 3266 /// p <top-level CV-qualifiers> 3267 /// <I-1 non-negative number> _ # L > 0, I > 0 3268 /// 3269 /// L is the nesting depth of the parameter, defined as 1 if the 3270 /// parameter comes from the innermost function prototype scope 3271 /// enclosing the current context, 2 if from the next enclosing 3272 /// function prototype scope, and so on, with one special case: if 3273 /// we've processed the full parameter clause for the innermost 3274 /// function type, then L is one less. This definition conveniently 3275 /// makes it irrelevant whether a function's result type was written 3276 /// trailing or leading, but is otherwise overly complicated; the 3277 /// numbering was first designed without considering references to 3278 /// parameter in locations other than return types, and then the 3279 /// mangling had to be generalized without changing the existing 3280 /// manglings. 3281 /// 3282 /// I is the zero-based index of the parameter within its parameter 3283 /// declaration clause. Note that the original ABI document describes 3284 /// this using 1-based ordinals. 3285 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 3286 unsigned parmDepth = parm->getFunctionScopeDepth(); 3287 unsigned parmIndex = parm->getFunctionScopeIndex(); 3288 3289 // Compute 'L'. 3290 // parmDepth does not include the declaring function prototype. 3291 // FunctionTypeDepth does account for that. 3292 assert(parmDepth < FunctionTypeDepth.getDepth()); 3293 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 3294 if (FunctionTypeDepth.isInResultType()) 3295 nestingDepth--; 3296 3297 if (nestingDepth == 0) { 3298 Out << "fp"; 3299 } else { 3300 Out << "fL" << (nestingDepth - 1) << 'p'; 3301 } 3302 3303 // Top-level qualifiers. We don't have to worry about arrays here, 3304 // because parameters declared as arrays should already have been 3305 // transformed to have pointer type. FIXME: apparently these don't 3306 // get mangled if used as an rvalue of a known non-class type? 3307 assert(!parm->getType()->isArrayType() 3308 && "parameter's type is still an array type?"); 3309 mangleQualifiers(parm->getType().getQualifiers()); 3310 3311 // Parameter index. 3312 if (parmIndex != 0) { 3313 Out << (parmIndex - 1); 3314 } 3315 Out << '_'; 3316 } 3317 3318 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) { 3319 // <ctor-dtor-name> ::= C1 # complete object constructor 3320 // ::= C2 # base object constructor 3321 // 3322 // In addition, C5 is a comdat name with C1 and C2 in it. 3323 switch (T) { 3324 case Ctor_Complete: 3325 Out << "C1"; 3326 break; 3327 case Ctor_Base: 3328 Out << "C2"; 3329 break; 3330 case Ctor_Comdat: 3331 Out << "C5"; 3332 break; 3333 } 3334 } 3335 3336 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 3337 // <ctor-dtor-name> ::= D0 # deleting destructor 3338 // ::= D1 # complete object destructor 3339 // ::= D2 # base object destructor 3340 // 3341 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 3342 switch (T) { 3343 case Dtor_Deleting: 3344 Out << "D0"; 3345 break; 3346 case Dtor_Complete: 3347 Out << "D1"; 3348 break; 3349 case Dtor_Base: 3350 Out << "D2"; 3351 break; 3352 case Dtor_Comdat: 3353 Out << "D5"; 3354 break; 3355 } 3356 } 3357 3358 void CXXNameMangler::mangleTemplateArgs( 3359 const ASTTemplateArgumentListInfo &TemplateArgs) { 3360 // <template-args> ::= I <template-arg>+ E 3361 Out << 'I'; 3362 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i) 3363 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument()); 3364 Out << 'E'; 3365 } 3366 3367 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) { 3368 // <template-args> ::= I <template-arg>+ E 3369 Out << 'I'; 3370 for (unsigned i = 0, e = AL.size(); i != e; ++i) 3371 mangleTemplateArg(AL[i]); 3372 Out << 'E'; 3373 } 3374 3375 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs, 3376 unsigned NumTemplateArgs) { 3377 // <template-args> ::= I <template-arg>+ E 3378 Out << 'I'; 3379 for (unsigned i = 0; i != NumTemplateArgs; ++i) 3380 mangleTemplateArg(TemplateArgs[i]); 3381 Out << 'E'; 3382 } 3383 3384 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { 3385 // <template-arg> ::= <type> # type or template 3386 // ::= X <expression> E # expression 3387 // ::= <expr-primary> # simple expressions 3388 // ::= J <template-arg>* E # argument pack 3389 if (!A.isInstantiationDependent() || A.isDependent()) 3390 A = Context.getASTContext().getCanonicalTemplateArgument(A); 3391 3392 switch (A.getKind()) { 3393 case TemplateArgument::Null: 3394 llvm_unreachable("Cannot mangle NULL template argument"); 3395 3396 case TemplateArgument::Type: 3397 mangleType(A.getAsType()); 3398 break; 3399 case TemplateArgument::Template: 3400 // This is mangled as <type>. 3401 mangleType(A.getAsTemplate()); 3402 break; 3403 case TemplateArgument::TemplateExpansion: 3404 // <type> ::= Dp <type> # pack expansion (C++0x) 3405 Out << "Dp"; 3406 mangleType(A.getAsTemplateOrTemplatePattern()); 3407 break; 3408 case TemplateArgument::Expression: { 3409 // It's possible to end up with a DeclRefExpr here in certain 3410 // dependent cases, in which case we should mangle as a 3411 // declaration. 3412 const Expr *E = A.getAsExpr()->IgnoreParens(); 3413 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3414 const ValueDecl *D = DRE->getDecl(); 3415 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 3416 Out << "L"; 3417 mangle(D, "_Z"); 3418 Out << 'E'; 3419 break; 3420 } 3421 } 3422 3423 Out << 'X'; 3424 mangleExpression(E); 3425 Out << 'E'; 3426 break; 3427 } 3428 case TemplateArgument::Integral: 3429 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 3430 break; 3431 case TemplateArgument::Declaration: { 3432 // <expr-primary> ::= L <mangled-name> E # external name 3433 // Clang produces AST's where pointer-to-member-function expressions 3434 // and pointer-to-function expressions are represented as a declaration not 3435 // an expression. We compensate for it here to produce the correct mangling. 3436 ValueDecl *D = A.getAsDecl(); 3437 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType(); 3438 if (compensateMangling) { 3439 Out << 'X'; 3440 mangleOperatorName(OO_Amp, 1); 3441 } 3442 3443 Out << 'L'; 3444 // References to external entities use the mangled name; if the name would 3445 // not normally be manged then mangle it as unqualified. 3446 // 3447 // FIXME: The ABI specifies that external names here should have _Z, but 3448 // gcc leaves this off. 3449 if (compensateMangling) 3450 mangle(D, "_Z"); 3451 else 3452 mangle(D, "Z"); 3453 Out << 'E'; 3454 3455 if (compensateMangling) 3456 Out << 'E'; 3457 3458 break; 3459 } 3460 case TemplateArgument::NullPtr: { 3461 // <expr-primary> ::= L <type> 0 E 3462 Out << 'L'; 3463 mangleType(A.getNullPtrType()); 3464 Out << "0E"; 3465 break; 3466 } 3467 case TemplateArgument::Pack: { 3468 // <template-arg> ::= J <template-arg>* E 3469 Out << 'J'; 3470 for (const auto &P : A.pack_elements()) 3471 mangleTemplateArg(P); 3472 Out << 'E'; 3473 } 3474 } 3475 } 3476 3477 void CXXNameMangler::mangleTemplateParameter(unsigned Index) { 3478 // <template-param> ::= T_ # first template parameter 3479 // ::= T <parameter-2 non-negative number> _ 3480 if (Index == 0) 3481 Out << "T_"; 3482 else 3483 Out << 'T' << (Index - 1) << '_'; 3484 } 3485 3486 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 3487 if (SeqID == 1) 3488 Out << '0'; 3489 else if (SeqID > 1) { 3490 SeqID--; 3491 3492 // <seq-id> is encoded in base-36, using digits and upper case letters. 3493 char Buffer[7]; // log(2**32) / log(36) ~= 7 3494 MutableArrayRef<char> BufferRef(Buffer); 3495 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 3496 3497 for (; SeqID != 0; SeqID /= 36) { 3498 unsigned C = SeqID % 36; 3499 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 3500 } 3501 3502 Out.write(I.base(), I - BufferRef.rbegin()); 3503 } 3504 Out << '_'; 3505 } 3506 3507 void CXXNameMangler::mangleExistingSubstitution(QualType type) { 3508 bool result = mangleSubstitution(type); 3509 assert(result && "no existing substitution for type"); 3510 (void) result; 3511 } 3512 3513 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 3514 bool result = mangleSubstitution(tname); 3515 assert(result && "no existing substitution for template name"); 3516 (void) result; 3517 } 3518 3519 // <substitution> ::= S <seq-id> _ 3520 // ::= S_ 3521 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 3522 // Try one of the standard substitutions first. 3523 if (mangleStandardSubstitution(ND)) 3524 return true; 3525 3526 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 3527 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 3528 } 3529 3530 /// \brief Determine whether the given type has any qualifiers that are 3531 /// relevant for substitutions. 3532 static bool hasMangledSubstitutionQualifiers(QualType T) { 3533 Qualifiers Qs = T.getQualifiers(); 3534 return Qs.getCVRQualifiers() || Qs.hasAddressSpace(); 3535 } 3536 3537 bool CXXNameMangler::mangleSubstitution(QualType T) { 3538 if (!hasMangledSubstitutionQualifiers(T)) { 3539 if (const RecordType *RT = T->getAs<RecordType>()) 3540 return mangleSubstitution(RT->getDecl()); 3541 } 3542 3543 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 3544 3545 return mangleSubstitution(TypePtr); 3546 } 3547 3548 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 3549 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 3550 return mangleSubstitution(TD); 3551 3552 Template = Context.getASTContext().getCanonicalTemplateName(Template); 3553 return mangleSubstitution( 3554 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 3555 } 3556 3557 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 3558 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 3559 if (I == Substitutions.end()) 3560 return false; 3561 3562 unsigned SeqID = I->second; 3563 Out << 'S'; 3564 mangleSeqID(SeqID); 3565 3566 return true; 3567 } 3568 3569 static bool isCharType(QualType T) { 3570 if (T.isNull()) 3571 return false; 3572 3573 return T->isSpecificBuiltinType(BuiltinType::Char_S) || 3574 T->isSpecificBuiltinType(BuiltinType::Char_U); 3575 } 3576 3577 /// isCharSpecialization - Returns whether a given type is a template 3578 /// specialization of a given name with a single argument of type char. 3579 static bool isCharSpecialization(QualType T, const char *Name) { 3580 if (T.isNull()) 3581 return false; 3582 3583 const RecordType *RT = T->getAs<RecordType>(); 3584 if (!RT) 3585 return false; 3586 3587 const ClassTemplateSpecializationDecl *SD = 3588 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 3589 if (!SD) 3590 return false; 3591 3592 if (!isStdNamespace(getEffectiveDeclContext(SD))) 3593 return false; 3594 3595 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3596 if (TemplateArgs.size() != 1) 3597 return false; 3598 3599 if (!isCharType(TemplateArgs[0].getAsType())) 3600 return false; 3601 3602 return SD->getIdentifier()->getName() == Name; 3603 } 3604 3605 template <std::size_t StrLen> 3606 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD, 3607 const char (&Str)[StrLen]) { 3608 if (!SD->getIdentifier()->isStr(Str)) 3609 return false; 3610 3611 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3612 if (TemplateArgs.size() != 2) 3613 return false; 3614 3615 if (!isCharType(TemplateArgs[0].getAsType())) 3616 return false; 3617 3618 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 3619 return false; 3620 3621 return true; 3622 } 3623 3624 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 3625 // <substitution> ::= St # ::std:: 3626 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 3627 if (isStd(NS)) { 3628 Out << "St"; 3629 return true; 3630 } 3631 } 3632 3633 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 3634 if (!isStdNamespace(getEffectiveDeclContext(TD))) 3635 return false; 3636 3637 // <substitution> ::= Sa # ::std::allocator 3638 if (TD->getIdentifier()->isStr("allocator")) { 3639 Out << "Sa"; 3640 return true; 3641 } 3642 3643 // <<substitution> ::= Sb # ::std::basic_string 3644 if (TD->getIdentifier()->isStr("basic_string")) { 3645 Out << "Sb"; 3646 return true; 3647 } 3648 } 3649 3650 if (const ClassTemplateSpecializationDecl *SD = 3651 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 3652 if (!isStdNamespace(getEffectiveDeclContext(SD))) 3653 return false; 3654 3655 // <substitution> ::= Ss # ::std::basic_string<char, 3656 // ::std::char_traits<char>, 3657 // ::std::allocator<char> > 3658 if (SD->getIdentifier()->isStr("basic_string")) { 3659 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3660 3661 if (TemplateArgs.size() != 3) 3662 return false; 3663 3664 if (!isCharType(TemplateArgs[0].getAsType())) 3665 return false; 3666 3667 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 3668 return false; 3669 3670 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator")) 3671 return false; 3672 3673 Out << "Ss"; 3674 return true; 3675 } 3676 3677 // <substitution> ::= Si # ::std::basic_istream<char, 3678 // ::std::char_traits<char> > 3679 if (isStreamCharSpecialization(SD, "basic_istream")) { 3680 Out << "Si"; 3681 return true; 3682 } 3683 3684 // <substitution> ::= So # ::std::basic_ostream<char, 3685 // ::std::char_traits<char> > 3686 if (isStreamCharSpecialization(SD, "basic_ostream")) { 3687 Out << "So"; 3688 return true; 3689 } 3690 3691 // <substitution> ::= Sd # ::std::basic_iostream<char, 3692 // ::std::char_traits<char> > 3693 if (isStreamCharSpecialization(SD, "basic_iostream")) { 3694 Out << "Sd"; 3695 return true; 3696 } 3697 } 3698 return false; 3699 } 3700 3701 void CXXNameMangler::addSubstitution(QualType T) { 3702 if (!hasMangledSubstitutionQualifiers(T)) { 3703 if (const RecordType *RT = T->getAs<RecordType>()) { 3704 addSubstitution(RT->getDecl()); 3705 return; 3706 } 3707 } 3708 3709 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 3710 addSubstitution(TypePtr); 3711 } 3712 3713 void CXXNameMangler::addSubstitution(TemplateName Template) { 3714 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 3715 return addSubstitution(TD); 3716 3717 Template = Context.getASTContext().getCanonicalTemplateName(Template); 3718 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 3719 } 3720 3721 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 3722 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 3723 Substitutions[Ptr] = SeqID++; 3724 } 3725 3726 // 3727 3728 /// \brief Mangles the name of the declaration D and emits that name to the 3729 /// given output stream. 3730 /// 3731 /// If the declaration D requires a mangled name, this routine will emit that 3732 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 3733 /// and this routine will return false. In this case, the caller should just 3734 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 3735 /// name. 3736 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D, 3737 raw_ostream &Out) { 3738 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) && 3739 "Invalid mangleName() call, argument is not a variable or function!"); 3740 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) && 3741 "Invalid mangleName() call on 'structor decl!"); 3742 3743 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 3744 getASTContext().getSourceManager(), 3745 "Mangling declaration"); 3746 3747 CXXNameMangler Mangler(*this, Out, D); 3748 return Mangler.mangle(D); 3749 } 3750 3751 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D, 3752 CXXCtorType Type, 3753 raw_ostream &Out) { 3754 CXXNameMangler Mangler(*this, Out, D, Type); 3755 Mangler.mangle(D); 3756 } 3757 3758 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D, 3759 CXXDtorType Type, 3760 raw_ostream &Out) { 3761 CXXNameMangler Mangler(*this, Out, D, Type); 3762 Mangler.mangle(D); 3763 } 3764 3765 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 3766 raw_ostream &Out) { 3767 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 3768 Mangler.mangle(D); 3769 } 3770 3771 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 3772 raw_ostream &Out) { 3773 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 3774 Mangler.mangle(D); 3775 } 3776 3777 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 3778 const ThunkInfo &Thunk, 3779 raw_ostream &Out) { 3780 // <special-name> ::= T <call-offset> <base encoding> 3781 // # base is the nominal target function of thunk 3782 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 3783 // # base is the nominal target function of thunk 3784 // # first call-offset is 'this' adjustment 3785 // # second call-offset is result adjustment 3786 3787 assert(!isa<CXXDestructorDecl>(MD) && 3788 "Use mangleCXXDtor for destructor decls!"); 3789 CXXNameMangler Mangler(*this, Out); 3790 Mangler.getStream() << "_ZT"; 3791 if (!Thunk.Return.isEmpty()) 3792 Mangler.getStream() << 'c'; 3793 3794 // Mangle the 'this' pointer adjustment. 3795 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 3796 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 3797 3798 // Mangle the return pointer adjustment if there is one. 3799 if (!Thunk.Return.isEmpty()) 3800 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 3801 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 3802 3803 Mangler.mangleFunctionEncoding(MD); 3804 } 3805 3806 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 3807 const CXXDestructorDecl *DD, CXXDtorType Type, 3808 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 3809 // <special-name> ::= T <call-offset> <base encoding> 3810 // # base is the nominal target function of thunk 3811 CXXNameMangler Mangler(*this, Out, DD, Type); 3812 Mangler.getStream() << "_ZT"; 3813 3814 // Mangle the 'this' pointer adjustment. 3815 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 3816 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 3817 3818 Mangler.mangleFunctionEncoding(DD); 3819 } 3820 3821 /// mangleGuardVariable - Returns the mangled name for a guard variable 3822 /// for the passed in VarDecl. 3823 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 3824 raw_ostream &Out) { 3825 // <special-name> ::= GV <object name> # Guard variable for one-time 3826 // # initialization 3827 CXXNameMangler Mangler(*this, Out); 3828 Mangler.getStream() << "_ZGV"; 3829 Mangler.mangleName(D); 3830 } 3831 3832 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 3833 raw_ostream &Out) { 3834 // These symbols are internal in the Itanium ABI, so the names don't matter. 3835 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 3836 // avoid duplicate symbols. 3837 Out << "__cxx_global_var_init"; 3838 } 3839 3840 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 3841 raw_ostream &Out) { 3842 // Prefix the mangling of D with __dtor_. 3843 CXXNameMangler Mangler(*this, Out); 3844 Mangler.getStream() << "__dtor_"; 3845 if (shouldMangleDeclName(D)) 3846 Mangler.mangle(D); 3847 else 3848 Mangler.getStream() << D->getName(); 3849 } 3850 3851 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 3852 raw_ostream &Out) { 3853 // <special-name> ::= TH <object name> 3854 CXXNameMangler Mangler(*this, Out); 3855 Mangler.getStream() << "_ZTH"; 3856 Mangler.mangleName(D); 3857 } 3858 3859 void 3860 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 3861 raw_ostream &Out) { 3862 // <special-name> ::= TW <object name> 3863 CXXNameMangler Mangler(*this, Out); 3864 Mangler.getStream() << "_ZTW"; 3865 Mangler.mangleName(D); 3866 } 3867 3868 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 3869 unsigned ManglingNumber, 3870 raw_ostream &Out) { 3871 // We match the GCC mangling here. 3872 // <special-name> ::= GR <object name> 3873 CXXNameMangler Mangler(*this, Out); 3874 Mangler.getStream() << "_ZGR"; 3875 Mangler.mangleName(D); 3876 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 3877 Mangler.mangleSeqID(ManglingNumber - 1); 3878 } 3879 3880 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 3881 raw_ostream &Out) { 3882 // <special-name> ::= TV <type> # virtual table 3883 CXXNameMangler Mangler(*this, Out); 3884 Mangler.getStream() << "_ZTV"; 3885 Mangler.mangleNameOrStandardSubstitution(RD); 3886 } 3887 3888 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 3889 raw_ostream &Out) { 3890 // <special-name> ::= TT <type> # VTT structure 3891 CXXNameMangler Mangler(*this, Out); 3892 Mangler.getStream() << "_ZTT"; 3893 Mangler.mangleNameOrStandardSubstitution(RD); 3894 } 3895 3896 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 3897 int64_t Offset, 3898 const CXXRecordDecl *Type, 3899 raw_ostream &Out) { 3900 // <special-name> ::= TC <type> <offset number> _ <base type> 3901 CXXNameMangler Mangler(*this, Out); 3902 Mangler.getStream() << "_ZTC"; 3903 Mangler.mangleNameOrStandardSubstitution(RD); 3904 Mangler.getStream() << Offset; 3905 Mangler.getStream() << '_'; 3906 Mangler.mangleNameOrStandardSubstitution(Type); 3907 } 3908 3909 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 3910 // <special-name> ::= TI <type> # typeinfo structure 3911 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 3912 CXXNameMangler Mangler(*this, Out); 3913 Mangler.getStream() << "_ZTI"; 3914 Mangler.mangleType(Ty); 3915 } 3916 3917 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 3918 raw_ostream &Out) { 3919 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 3920 CXXNameMangler Mangler(*this, Out); 3921 Mangler.getStream() << "_ZTS"; 3922 Mangler.mangleType(Ty); 3923 } 3924 3925 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 3926 mangleCXXRTTIName(Ty, Out); 3927 } 3928 3929 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 3930 llvm_unreachable("Can't mangle string literals"); 3931 } 3932 3933 ItaniumMangleContext * 3934 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) { 3935 return new ItaniumMangleContextImpl(Context, Diags); 3936 } 3937