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