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