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