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