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