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