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