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