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