1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/Attr.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/GlobalDecl.h" 25 #include "clang/AST/Mangle.h" 26 #include "clang/AST/VTableBuilder.h" 27 #include "clang/Basic/ABI.h" 28 #include "clang/Basic/DiagnosticOptions.h" 29 #include "clang/Basic/FileManager.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "llvm/ADT/StringExtras.h" 33 #include "llvm/Support/CRC.h" 34 #include "llvm/Support/MD5.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/StringSaver.h" 37 #include "llvm/Support/xxhash.h" 38 #include <optional> 39 40 using namespace clang; 41 42 namespace { 43 44 // Get GlobalDecl of DeclContext of local entities. 45 static GlobalDecl getGlobalDeclAsDeclContext(const DeclContext *DC) { 46 GlobalDecl GD; 47 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 48 GD = GlobalDecl(CD, Ctor_Complete); 49 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 50 GD = GlobalDecl(DD, Dtor_Complete); 51 else 52 GD = GlobalDecl(cast<FunctionDecl>(DC)); 53 return GD; 54 } 55 56 struct msvc_hashing_ostream : public llvm::raw_svector_ostream { 57 raw_ostream &OS; 58 llvm::SmallString<64> Buffer; 59 60 msvc_hashing_ostream(raw_ostream &OS) 61 : llvm::raw_svector_ostream(Buffer), OS(OS) {} 62 ~msvc_hashing_ostream() override { 63 StringRef MangledName = str(); 64 bool StartsWithEscape = MangledName.startswith("\01"); 65 if (StartsWithEscape) 66 MangledName = MangledName.drop_front(1); 67 if (MangledName.size() < 4096) { 68 OS << str(); 69 return; 70 } 71 72 llvm::MD5 Hasher; 73 llvm::MD5::MD5Result Hash; 74 Hasher.update(MangledName); 75 Hasher.final(Hash); 76 77 SmallString<32> HexString; 78 llvm::MD5::stringifyResult(Hash, HexString); 79 80 if (StartsWithEscape) 81 OS << '\01'; 82 OS << "??@" << HexString << '@'; 83 } 84 }; 85 86 static const DeclContext * 87 getLambdaDefaultArgumentDeclContext(const Decl *D) { 88 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) 89 if (RD->isLambda()) 90 if (const auto *Parm = 91 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl())) 92 return Parm->getDeclContext(); 93 return nullptr; 94 } 95 96 /// Retrieve the declaration context that should be used when mangling 97 /// the given declaration. 98 static const DeclContext *getEffectiveDeclContext(const Decl *D) { 99 // The ABI assumes that lambda closure types that occur within 100 // default arguments live in the context of the function. However, due to 101 // the way in which Clang parses and creates function declarations, this is 102 // not the case: the lambda closure type ends up living in the context 103 // where the function itself resides, because the function declaration itself 104 // had not yet been created. Fix the context here. 105 if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D)) 106 return LDADC; 107 108 // Perform the same check for block literals. 109 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 110 if (ParmVarDecl *ContextParam = 111 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) 112 return ContextParam->getDeclContext(); 113 } 114 115 const DeclContext *DC = D->getDeclContext(); 116 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) || 117 isa<OMPDeclareMapperDecl>(DC)) { 118 return getEffectiveDeclContext(cast<Decl>(DC)); 119 } 120 121 return DC->getRedeclContext(); 122 } 123 124 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) { 125 return getEffectiveDeclContext(cast<Decl>(DC)); 126 } 127 128 static const FunctionDecl *getStructor(const NamedDecl *ND) { 129 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 130 return FTD->getTemplatedDecl()->getCanonicalDecl(); 131 132 const auto *FD = cast<FunctionDecl>(ND); 133 if (const auto *FTD = FD->getPrimaryTemplate()) 134 return FTD->getTemplatedDecl()->getCanonicalDecl(); 135 136 return FD->getCanonicalDecl(); 137 } 138 139 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the 140 /// Microsoft Visual C++ ABI. 141 class MicrosoftMangleContextImpl : public MicrosoftMangleContext { 142 typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy; 143 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator; 144 llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier; 145 llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds; 146 llvm::DenseMap<GlobalDecl, unsigned> SEHFilterIds; 147 llvm::DenseMap<GlobalDecl, unsigned> SEHFinallyIds; 148 SmallString<16> AnonymousNamespaceHash; 149 150 public: 151 MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags, 152 bool IsAux = false); 153 bool shouldMangleCXXName(const NamedDecl *D) override; 154 bool shouldMangleStringLiteral(const StringLiteral *SL) override; 155 void mangleCXXName(GlobalDecl GD, raw_ostream &Out) override; 156 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD, 157 const MethodVFTableLocation &ML, 158 raw_ostream &Out) override; 159 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, 160 raw_ostream &) override; 161 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, 162 const ThisAdjustment &ThisAdjustment, 163 raw_ostream &) override; 164 void mangleCXXVFTable(const CXXRecordDecl *Derived, 165 ArrayRef<const CXXRecordDecl *> BasePath, 166 raw_ostream &Out) override; 167 void mangleCXXVBTable(const CXXRecordDecl *Derived, 168 ArrayRef<const CXXRecordDecl *> BasePath, 169 raw_ostream &Out) override; 170 void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD, 171 const CXXRecordDecl *DstRD, 172 raw_ostream &Out) override; 173 void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile, 174 bool IsUnaligned, uint32_t NumEntries, 175 raw_ostream &Out) override; 176 void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries, 177 raw_ostream &Out) override; 178 void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD, 179 CXXCtorType CT, uint32_t Size, uint32_t NVOffset, 180 int32_t VBPtrOffset, uint32_t VBIndex, 181 raw_ostream &Out) override; 182 void mangleCXXRTTI(QualType T, raw_ostream &Out) override; 183 void mangleCXXRTTIName(QualType T, raw_ostream &Out) override; 184 void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived, 185 uint32_t NVOffset, int32_t VBPtrOffset, 186 uint32_t VBTableOffset, uint32_t Flags, 187 raw_ostream &Out) override; 188 void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived, 189 raw_ostream &Out) override; 190 void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived, 191 raw_ostream &Out) override; 192 void 193 mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived, 194 ArrayRef<const CXXRecordDecl *> BasePath, 195 raw_ostream &Out) override; 196 void mangleTypeName(QualType T, raw_ostream &) override; 197 void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber, 198 raw_ostream &) override; 199 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override; 200 void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum, 201 raw_ostream &Out) override; 202 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override; 203 void mangleDynamicAtExitDestructor(const VarDecl *D, 204 raw_ostream &Out) override; 205 void mangleSEHFilterExpression(GlobalDecl EnclosingDecl, 206 raw_ostream &Out) override; 207 void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl, 208 raw_ostream &Out) override; 209 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override; 210 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { 211 const DeclContext *DC = getEffectiveDeclContext(ND); 212 if (!DC->isFunctionOrMethod()) 213 return false; 214 215 // Lambda closure types are already numbered, give out a phony number so 216 // that they demangle nicely. 217 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) { 218 if (RD->isLambda()) { 219 disc = 1; 220 return true; 221 } 222 } 223 224 // Use the canonical number for externally visible decls. 225 if (ND->isExternallyVisible()) { 226 disc = getASTContext().getManglingNumber(ND, isAux()); 227 return true; 228 } 229 230 // Anonymous tags are already numbered. 231 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) { 232 if (!Tag->hasNameForLinkage() && 233 !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) && 234 !getASTContext().getTypedefNameForUnnamedTagDecl(Tag)) 235 return false; 236 } 237 238 // Make up a reasonable number for internal decls. 239 unsigned &discriminator = Uniquifier[ND]; 240 if (!discriminator) 241 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())]; 242 disc = discriminator + 1; 243 return true; 244 } 245 246 std::string getLambdaString(const CXXRecordDecl *Lambda) override { 247 assert(Lambda->isLambda() && "RD must be a lambda!"); 248 std::string Name("<lambda_"); 249 250 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl(); 251 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber(); 252 unsigned LambdaId; 253 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl); 254 const FunctionDecl *Func = 255 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr; 256 257 if (Func) { 258 unsigned DefaultArgNo = 259 Func->getNumParams() - Parm->getFunctionScopeIndex(); 260 Name += llvm::utostr(DefaultArgNo); 261 Name += "_"; 262 } 263 264 if (LambdaManglingNumber) 265 LambdaId = LambdaManglingNumber; 266 else 267 LambdaId = getLambdaIdForDebugInfo(Lambda); 268 269 Name += llvm::utostr(LambdaId); 270 Name += ">"; 271 return Name; 272 } 273 274 unsigned getLambdaId(const CXXRecordDecl *RD) { 275 assert(RD->isLambda() && "RD must be a lambda!"); 276 assert(!RD->isExternallyVisible() && "RD must not be visible!"); 277 assert(RD->getLambdaManglingNumber() == 0 && 278 "RD must not have a mangling number!"); 279 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool> 280 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size())); 281 return Result.first->second; 282 } 283 284 unsigned getLambdaIdForDebugInfo(const CXXRecordDecl *RD) { 285 assert(RD->isLambda() && "RD must be a lambda!"); 286 assert(!RD->isExternallyVisible() && "RD must not be visible!"); 287 assert(RD->getLambdaManglingNumber() == 0 && 288 "RD must not have a mangling number!"); 289 llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator Result = 290 LambdaIds.find(RD); 291 // The lambda should exist, but return 0 in case it doesn't. 292 if (Result == LambdaIds.end()) 293 return 0; 294 return Result->second; 295 } 296 297 /// Return a character sequence that is (somewhat) unique to the TU suitable 298 /// for mangling anonymous namespaces. 299 StringRef getAnonymousNamespaceHash() const { 300 return AnonymousNamespaceHash; 301 } 302 303 private: 304 void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out); 305 }; 306 307 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the 308 /// Microsoft Visual C++ ABI. 309 class MicrosoftCXXNameMangler { 310 MicrosoftMangleContextImpl &Context; 311 raw_ostream &Out; 312 313 /// The "structor" is the top-level declaration being mangled, if 314 /// that's not a template specialization; otherwise it's the pattern 315 /// for that specialization. 316 const NamedDecl *Structor; 317 unsigned StructorType; 318 319 typedef llvm::SmallVector<std::string, 10> BackRefVec; 320 BackRefVec NameBackReferences; 321 322 typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap; 323 ArgBackRefMap FunArgBackReferences; 324 ArgBackRefMap TemplateArgBackReferences; 325 326 typedef llvm::DenseMap<const void *, StringRef> TemplateArgStringMap; 327 TemplateArgStringMap TemplateArgStrings; 328 llvm::StringSaver TemplateArgStringStorage; 329 llvm::BumpPtrAllocator TemplateArgStringStorageAlloc; 330 331 typedef std::set<std::pair<int, bool>> PassObjectSizeArgsSet; 332 PassObjectSizeArgsSet PassObjectSizeArgs; 333 334 ASTContext &getASTContext() const { return Context.getASTContext(); } 335 336 const bool PointersAre64Bit; 337 338 public: 339 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result }; 340 341 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_) 342 : Context(C), Out(Out_), Structor(nullptr), StructorType(-1), 343 TemplateArgStringStorage(TemplateArgStringStorageAlloc), 344 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth( 345 LangAS::Default) == 64) {} 346 347 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_, 348 const CXXConstructorDecl *D, CXXCtorType Type) 349 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 350 TemplateArgStringStorage(TemplateArgStringStorageAlloc), 351 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth( 352 LangAS::Default) == 64) {} 353 354 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_, 355 const CXXDestructorDecl *D, CXXDtorType Type) 356 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 357 TemplateArgStringStorage(TemplateArgStringStorageAlloc), 358 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth( 359 LangAS::Default) == 64) {} 360 361 raw_ostream &getStream() const { return Out; } 362 363 void mangle(GlobalDecl GD, StringRef Prefix = "?"); 364 void mangleName(GlobalDecl GD); 365 void mangleFunctionEncoding(GlobalDecl GD, bool ShouldMangle); 366 void mangleVariableEncoding(const VarDecl *VD); 367 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD, 368 StringRef Prefix = "$"); 369 void mangleMemberFunctionPointer(const CXXRecordDecl *RD, 370 const CXXMethodDecl *MD, 371 StringRef Prefix = "$"); 372 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD, 373 const MethodVFTableLocation &ML); 374 void mangleNumber(int64_t Number); 375 void mangleNumber(llvm::APSInt Number); 376 void mangleFloat(llvm::APFloat Number); 377 void mangleBits(llvm::APInt Number); 378 void mangleTagTypeKind(TagTypeKind TK); 379 void mangleArtificialTagType(TagTypeKind TK, StringRef UnqualifiedName, 380 ArrayRef<StringRef> NestedNames = std::nullopt); 381 void mangleAddressSpaceType(QualType T, Qualifiers Quals, SourceRange Range); 382 void mangleType(QualType T, SourceRange Range, 383 QualifierMangleMode QMM = QMM_Mangle); 384 void mangleFunctionType(const FunctionType *T, 385 const FunctionDecl *D = nullptr, 386 bool ForceThisQuals = false, 387 bool MangleExceptionSpec = true); 388 void mangleNestedName(GlobalDecl GD); 389 390 private: 391 bool isStructorDecl(const NamedDecl *ND) const { 392 return ND == Structor || getStructor(ND) == Structor; 393 } 394 395 bool is64BitPointer(Qualifiers Quals) const { 396 LangAS AddrSpace = Quals.getAddressSpace(); 397 return AddrSpace == LangAS::ptr64 || 398 (PointersAre64Bit && !(AddrSpace == LangAS::ptr32_sptr || 399 AddrSpace == LangAS::ptr32_uptr)); 400 } 401 402 void mangleUnqualifiedName(GlobalDecl GD) { 403 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName()); 404 } 405 void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name); 406 void mangleSourceName(StringRef Name); 407 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc); 408 void mangleCXXDtorType(CXXDtorType T); 409 void mangleQualifiers(Qualifiers Quals, bool IsMember); 410 void mangleRefQualifier(RefQualifierKind RefQualifier); 411 void manglePointerCVQualifiers(Qualifiers Quals); 412 void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType); 413 414 void mangleUnscopedTemplateName(GlobalDecl GD); 415 void 416 mangleTemplateInstantiationName(GlobalDecl GD, 417 const TemplateArgumentList &TemplateArgs); 418 void mangleObjCMethodName(const ObjCMethodDecl *MD); 419 420 void mangleFunctionArgumentType(QualType T, SourceRange Range); 421 void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA); 422 423 bool isArtificialTagType(QualType T) const; 424 425 // Declare manglers for every type class. 426 #define ABSTRACT_TYPE(CLASS, PARENT) 427 #define NON_CANONICAL_TYPE(CLASS, PARENT) 428 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \ 429 Qualifiers Quals, \ 430 SourceRange Range); 431 #include "clang/AST/TypeNodes.inc" 432 #undef ABSTRACT_TYPE 433 #undef NON_CANONICAL_TYPE 434 #undef TYPE 435 436 void mangleType(const TagDecl *TD); 437 void mangleDecayedArrayType(const ArrayType *T); 438 void mangleArrayType(const ArrayType *T); 439 void mangleFunctionClass(const FunctionDecl *FD); 440 void mangleCallingConvention(CallingConv CC); 441 void mangleCallingConvention(const FunctionType *T); 442 void mangleIntegerLiteral(const llvm::APSInt &Number, 443 const NonTypeTemplateParmDecl *PD = nullptr, 444 QualType TemplateArgType = QualType()); 445 void mangleExpression(const Expr *E, const NonTypeTemplateParmDecl *PD); 446 void mangleThrowSpecification(const FunctionProtoType *T); 447 448 void mangleTemplateArgs(const TemplateDecl *TD, 449 const TemplateArgumentList &TemplateArgs); 450 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA, 451 const NamedDecl *Parm); 452 void mangleTemplateArgValue(QualType T, const APValue &V, 453 bool WithScalarType = false); 454 455 void mangleObjCProtocol(const ObjCProtocolDecl *PD); 456 void mangleObjCLifetime(const QualType T, Qualifiers Quals, 457 SourceRange Range); 458 void mangleObjCKindOfType(const ObjCObjectType *T, Qualifiers Quals, 459 SourceRange Range); 460 }; 461 } 462 463 MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context, 464 DiagnosticsEngine &Diags, 465 bool IsAux) 466 : MicrosoftMangleContext(Context, Diags, IsAux) { 467 // To mangle anonymous namespaces, hash the path to the main source file. The 468 // path should be whatever (probably relative) path was passed on the command 469 // line. The goal is for the compiler to produce the same output regardless of 470 // working directory, so use the uncanonicalized relative path. 471 // 472 // It's important to make the mangled names unique because, when CodeView 473 // debug info is in use, the debugger uses mangled type names to distinguish 474 // between otherwise identically named types in anonymous namespaces. 475 // 476 // These symbols are always internal, so there is no need for the hash to 477 // match what MSVC produces. For the same reason, clang is free to change the 478 // hash at any time without breaking compatibility with old versions of clang. 479 // The generated names are intended to look similar to what MSVC generates, 480 // which are something like "?A0x01234567@". 481 SourceManager &SM = Context.getSourceManager(); 482 if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) { 483 // Truncate the hash so we get 8 characters of hexadecimal. 484 uint32_t TruncatedHash = uint32_t(xxHash64(FE->getName())); 485 AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash); 486 } else { 487 // If we don't have a path to the main file, we'll just use 0. 488 AnonymousNamespaceHash = "0"; 489 } 490 } 491 492 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) { 493 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 494 LanguageLinkage L = FD->getLanguageLinkage(); 495 // Overloadable functions need mangling. 496 if (FD->hasAttr<OverloadableAttr>()) 497 return true; 498 499 // The ABI expects that we would never mangle "typical" user-defined entry 500 // points regardless of visibility or freestanding-ness. 501 // 502 // N.B. This is distinct from asking about "main". "main" has a lot of 503 // special rules associated with it in the standard while these 504 // user-defined entry points are outside of the purview of the standard. 505 // For example, there can be only one definition for "main" in a standards 506 // compliant program; however nothing forbids the existence of wmain and 507 // WinMain in the same translation unit. 508 if (FD->isMSVCRTEntryPoint()) 509 return false; 510 511 // C++ functions and those whose names are not a simple identifier need 512 // mangling. 513 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage) 514 return true; 515 516 // C functions are not mangled. 517 if (L == CLanguageLinkage) 518 return false; 519 } 520 521 // Otherwise, no mangling is done outside C++ mode. 522 if (!getASTContext().getLangOpts().CPlusPlus) 523 return false; 524 525 const VarDecl *VD = dyn_cast<VarDecl>(D); 526 if (VD && !isa<DecompositionDecl>(D)) { 527 // C variables are not mangled. 528 if (VD->isExternC()) 529 return false; 530 531 // Variables at global scope with internal linkage are not mangled. 532 const DeclContext *DC = getEffectiveDeclContext(D); 533 // Check for extern variable declared locally. 534 if (DC->isFunctionOrMethod() && D->hasLinkage()) 535 while (!DC->isNamespace() && !DC->isTranslationUnit()) 536 DC = getEffectiveParentContext(DC); 537 538 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage && 539 !isa<VarTemplateSpecializationDecl>(D) && 540 D->getIdentifier() != nullptr) 541 return false; 542 } 543 544 return true; 545 } 546 547 bool 548 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) { 549 return true; 550 } 551 552 void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) { 553 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 554 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names. 555 // Therefore it's really important that we don't decorate the 556 // name with leading underscores or leading/trailing at signs. So, by 557 // default, we emit an asm marker at the start so we get the name right. 558 // Callers can override this with a custom prefix. 559 560 // <mangled-name> ::= ? <name> <type-encoding> 561 Out << Prefix; 562 mangleName(GD); 563 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 564 mangleFunctionEncoding(GD, Context.shouldMangleDeclName(FD)); 565 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 566 mangleVariableEncoding(VD); 567 else if (isa<MSGuidDecl>(D)) 568 // MSVC appears to mangle GUIDs as if they were variables of type 569 // 'const struct __s_GUID'. 570 Out << "3U__s_GUID@@B"; 571 else if (isa<TemplateParamObjectDecl>(D)) { 572 // Template parameter objects don't get a <type-encoding>; their type is 573 // specified as part of their value. 574 } else 575 llvm_unreachable("Tried to mangle unexpected NamedDecl!"); 576 } 577 578 void MicrosoftCXXNameMangler::mangleFunctionEncoding(GlobalDecl GD, 579 bool ShouldMangle) { 580 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 581 // <type-encoding> ::= <function-class> <function-type> 582 583 // Since MSVC operates on the type as written and not the canonical type, it 584 // actually matters which decl we have here. MSVC appears to choose the 585 // first, since it is most likely to be the declaration in a header file. 586 FD = FD->getFirstDecl(); 587 588 // We should never ever see a FunctionNoProtoType at this point. 589 // We don't even know how to mangle their types anyway :). 590 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>(); 591 592 // extern "C" functions can hold entities that must be mangled. 593 // As it stands, these functions still need to get expressed in the full 594 // external name. They have their class and type omitted, replaced with '9'. 595 if (ShouldMangle) { 596 // We would like to mangle all extern "C" functions using this additional 597 // component but this would break compatibility with MSVC's behavior. 598 // Instead, do this when we know that compatibility isn't important (in 599 // other words, when it is an overloaded extern "C" function). 600 if (FD->isExternC() && FD->hasAttr<OverloadableAttr>()) 601 Out << "$$J0"; 602 603 mangleFunctionClass(FD); 604 605 mangleFunctionType(FT, FD, false, false); 606 } else { 607 Out << '9'; 608 } 609 } 610 611 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) { 612 // <type-encoding> ::= <storage-class> <variable-type> 613 // <storage-class> ::= 0 # private static member 614 // ::= 1 # protected static member 615 // ::= 2 # public static member 616 // ::= 3 # global 617 // ::= 4 # static local 618 619 // The first character in the encoding (after the name) is the storage class. 620 if (VD->isStaticDataMember()) { 621 // If it's a static member, it also encodes the access level. 622 switch (VD->getAccess()) { 623 default: 624 case AS_private: Out << '0'; break; 625 case AS_protected: Out << '1'; break; 626 case AS_public: Out << '2'; break; 627 } 628 } 629 else if (!VD->isStaticLocal()) 630 Out << '3'; 631 else 632 Out << '4'; 633 // Now mangle the type. 634 // <variable-type> ::= <type> <cvr-qualifiers> 635 // ::= <type> <pointee-cvr-qualifiers> # pointers, references 636 // Pointers and references are odd. The type of 'int * const foo;' gets 637 // mangled as 'QAHA' instead of 'PAHB', for example. 638 SourceRange SR = VD->getSourceRange(); 639 QualType Ty = VD->getType(); 640 if (Ty->isPointerType() || Ty->isReferenceType() || 641 Ty->isMemberPointerType()) { 642 mangleType(Ty, SR, QMM_Drop); 643 manglePointerExtQualifiers( 644 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType()); 645 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) { 646 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true); 647 // Member pointers are suffixed with a back reference to the member 648 // pointer's class name. 649 mangleName(MPT->getClass()->getAsCXXRecordDecl()); 650 } else 651 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false); 652 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) { 653 // Global arrays are funny, too. 654 mangleDecayedArrayType(AT); 655 if (AT->getElementType()->isArrayType()) 656 Out << 'A'; 657 else 658 mangleQualifiers(Ty.getQualifiers(), false); 659 } else { 660 mangleType(Ty, SR, QMM_Drop); 661 mangleQualifiers(Ty.getQualifiers(), false); 662 } 663 } 664 665 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD, 666 const ValueDecl *VD, 667 StringRef Prefix) { 668 // <member-data-pointer> ::= <integer-literal> 669 // ::= $F <number> <number> 670 // ::= $G <number> <number> <number> 671 672 int64_t FieldOffset; 673 int64_t VBTableOffset; 674 MSInheritanceModel IM = RD->getMSInheritanceModel(); 675 if (VD) { 676 FieldOffset = getASTContext().getFieldOffset(VD); 677 assert(FieldOffset % getASTContext().getCharWidth() == 0 && 678 "cannot take address of bitfield"); 679 FieldOffset /= getASTContext().getCharWidth(); 680 681 VBTableOffset = 0; 682 683 if (IM == MSInheritanceModel::Virtual) 684 FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity(); 685 } else { 686 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1; 687 688 VBTableOffset = -1; 689 } 690 691 char Code = '\0'; 692 switch (IM) { 693 case MSInheritanceModel::Single: Code = '0'; break; 694 case MSInheritanceModel::Multiple: Code = '0'; break; 695 case MSInheritanceModel::Virtual: Code = 'F'; break; 696 case MSInheritanceModel::Unspecified: Code = 'G'; break; 697 } 698 699 Out << Prefix << Code; 700 701 mangleNumber(FieldOffset); 702 703 // The C++ standard doesn't allow base-to-derived member pointer conversions 704 // in template parameter contexts, so the vbptr offset of data member pointers 705 // is always zero. 706 if (inheritanceModelHasVBPtrOffsetField(IM)) 707 mangleNumber(0); 708 if (inheritanceModelHasVBTableOffsetField(IM)) 709 mangleNumber(VBTableOffset); 710 } 711 712 void 713 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD, 714 const CXXMethodDecl *MD, 715 StringRef Prefix) { 716 // <member-function-pointer> ::= $1? <name> 717 // ::= $H? <name> <number> 718 // ::= $I? <name> <number> <number> 719 // ::= $J? <name> <number> <number> <number> 720 721 MSInheritanceModel IM = RD->getMSInheritanceModel(); 722 723 char Code = '\0'; 724 switch (IM) { 725 case MSInheritanceModel::Single: Code = '1'; break; 726 case MSInheritanceModel::Multiple: Code = 'H'; break; 727 case MSInheritanceModel::Virtual: Code = 'I'; break; 728 case MSInheritanceModel::Unspecified: Code = 'J'; break; 729 } 730 731 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr 732 // thunk. 733 uint64_t NVOffset = 0; 734 uint64_t VBTableOffset = 0; 735 uint64_t VBPtrOffset = 0; 736 if (MD) { 737 Out << Prefix << Code << '?'; 738 if (MD->isVirtual()) { 739 MicrosoftVTableContext *VTContext = 740 cast<MicrosoftVTableContext>(getASTContext().getVTableContext()); 741 MethodVFTableLocation ML = 742 VTContext->getMethodVFTableLocation(GlobalDecl(MD)); 743 mangleVirtualMemPtrThunk(MD, ML); 744 NVOffset = ML.VFPtrOffset.getQuantity(); 745 VBTableOffset = ML.VBTableIndex * 4; 746 if (ML.VBase) { 747 const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD); 748 VBPtrOffset = Layout.getVBPtrOffset().getQuantity(); 749 } 750 } else { 751 mangleName(MD); 752 mangleFunctionEncoding(MD, /*ShouldMangle=*/true); 753 } 754 755 if (VBTableOffset == 0 && IM == MSInheritanceModel::Virtual) 756 NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity(); 757 } else { 758 // Null single inheritance member functions are encoded as a simple nullptr. 759 if (IM == MSInheritanceModel::Single) { 760 Out << Prefix << "0A@"; 761 return; 762 } 763 if (IM == MSInheritanceModel::Unspecified) 764 VBTableOffset = -1; 765 Out << Prefix << Code; 766 } 767 768 if (inheritanceModelHasNVOffsetField(/*IsMemberFunction=*/true, IM)) 769 mangleNumber(static_cast<uint32_t>(NVOffset)); 770 if (inheritanceModelHasVBPtrOffsetField(IM)) 771 mangleNumber(VBPtrOffset); 772 if (inheritanceModelHasVBTableOffsetField(IM)) 773 mangleNumber(VBTableOffset); 774 } 775 776 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk( 777 const CXXMethodDecl *MD, const MethodVFTableLocation &ML) { 778 // Get the vftable offset. 779 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits( 780 getASTContext().getTargetInfo().getPointerWidth(LangAS::Default)); 781 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity(); 782 783 Out << "?_9"; 784 mangleName(MD->getParent()); 785 Out << "$B"; 786 mangleNumber(OffsetInVFTable); 787 Out << 'A'; 788 mangleCallingConvention(MD->getType()->castAs<FunctionProtoType>()); 789 } 790 791 void MicrosoftCXXNameMangler::mangleName(GlobalDecl GD) { 792 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @ 793 794 // Always start with the unqualified name. 795 mangleUnqualifiedName(GD); 796 797 mangleNestedName(GD); 798 799 // Terminate the whole name with an '@'. 800 Out << '@'; 801 } 802 803 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) { 804 mangleNumber(llvm::APSInt(llvm::APInt(64, Number), /*IsUnsigned*/false)); 805 } 806 807 void MicrosoftCXXNameMangler::mangleNumber(llvm::APSInt Number) { 808 // MSVC never mangles any integer wider than 64 bits. In general it appears 809 // to convert every integer to signed 64 bit before mangling (including 810 // unsigned 64 bit values). Do the same, but preserve bits beyond the bottom 811 // 64. 812 unsigned Width = std::max(Number.getBitWidth(), 64U); 813 llvm::APInt Value = Number.extend(Width); 814 815 // <non-negative integer> ::= A@ # when Number == 0 816 // ::= <decimal digit> # when 1 <= Number <= 10 817 // ::= <hex digit>+ @ # when Number >= 10 818 // 819 // <number> ::= [?] <non-negative integer> 820 821 if (Value.isNegative()) { 822 Value = -Value; 823 Out << '?'; 824 } 825 mangleBits(Value); 826 } 827 828 void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat Number) { 829 using llvm::APFloat; 830 831 switch (APFloat::SemanticsToEnum(Number.getSemantics())) { 832 case APFloat::S_IEEEsingle: Out << 'A'; break; 833 case APFloat::S_IEEEdouble: Out << 'B'; break; 834 835 // The following are all Clang extensions. We try to pick manglings that are 836 // unlikely to conflict with MSVC's scheme. 837 case APFloat::S_IEEEhalf: Out << 'V'; break; 838 case APFloat::S_BFloat: Out << 'W'; break; 839 case APFloat::S_x87DoubleExtended: Out << 'X'; break; 840 case APFloat::S_IEEEquad: Out << 'Y'; break; 841 case APFloat::S_PPCDoubleDouble: Out << 'Z'; break; 842 case APFloat::S_Float8E5M2: 843 case APFloat::S_Float8E4M3FN: 844 llvm_unreachable("Tried to mangle unexpected APFloat semantics"); 845 } 846 847 mangleBits(Number.bitcastToAPInt()); 848 } 849 850 void MicrosoftCXXNameMangler::mangleBits(llvm::APInt Value) { 851 if (Value == 0) 852 Out << "A@"; 853 else if (Value.uge(1) && Value.ule(10)) 854 Out << (Value - 1); 855 else { 856 // Numbers that are not encoded as decimal digits are represented as nibbles 857 // in the range of ASCII characters 'A' to 'P'. 858 // The number 0x123450 would be encoded as 'BCDEFA' 859 llvm::SmallString<32> EncodedNumberBuffer; 860 for (; Value != 0; Value.lshrInPlace(4)) 861 EncodedNumberBuffer.push_back('A' + (Value & 0xf).getZExtValue()); 862 std::reverse(EncodedNumberBuffer.begin(), EncodedNumberBuffer.end()); 863 Out.write(EncodedNumberBuffer.data(), EncodedNumberBuffer.size()); 864 Out << '@'; 865 } 866 } 867 868 static GlobalDecl isTemplate(GlobalDecl GD, 869 const TemplateArgumentList *&TemplateArgs) { 870 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 871 // Check if we have a function template. 872 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 873 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) { 874 TemplateArgs = FD->getTemplateSpecializationArgs(); 875 return GD.getWithDecl(TD); 876 } 877 } 878 879 // Check if we have a class template. 880 if (const ClassTemplateSpecializationDecl *Spec = 881 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 882 TemplateArgs = &Spec->getTemplateArgs(); 883 return GD.getWithDecl(Spec->getSpecializedTemplate()); 884 } 885 886 // Check if we have a variable template. 887 if (const VarTemplateSpecializationDecl *Spec = 888 dyn_cast<VarTemplateSpecializationDecl>(ND)) { 889 TemplateArgs = &Spec->getTemplateArgs(); 890 return GD.getWithDecl(Spec->getSpecializedTemplate()); 891 } 892 893 return GlobalDecl(); 894 } 895 896 void MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD, 897 DeclarationName Name) { 898 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 899 // <unqualified-name> ::= <operator-name> 900 // ::= <ctor-dtor-name> 901 // ::= <source-name> 902 // ::= <template-name> 903 904 // Check if we have a template. 905 const TemplateArgumentList *TemplateArgs = nullptr; 906 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) { 907 // Function templates aren't considered for name back referencing. This 908 // makes sense since function templates aren't likely to occur multiple 909 // times in a symbol. 910 if (isa<FunctionTemplateDecl>(TD.getDecl())) { 911 mangleTemplateInstantiationName(TD, *TemplateArgs); 912 Out << '@'; 913 return; 914 } 915 916 // Here comes the tricky thing: if we need to mangle something like 917 // void foo(A::X<Y>, B::X<Y>), 918 // the X<Y> part is aliased. However, if you need to mangle 919 // void foo(A::X<A::Y>, A::X<B::Y>), 920 // the A::X<> part is not aliased. 921 // That is, from the mangler's perspective we have a structure like this: 922 // namespace[s] -> type[ -> template-parameters] 923 // but from the Clang perspective we have 924 // type [ -> template-parameters] 925 // \-> namespace[s] 926 // What we do is we create a new mangler, mangle the same type (without 927 // a namespace suffix) to a string using the extra mangler and then use 928 // the mangled type name as a key to check the mangling of different types 929 // for aliasing. 930 931 // It's important to key cache reads off ND, not TD -- the same TD can 932 // be used with different TemplateArgs, but ND uniquely identifies 933 // TD / TemplateArg pairs. 934 ArgBackRefMap::iterator Found = TemplateArgBackReferences.find(ND); 935 if (Found == TemplateArgBackReferences.end()) { 936 937 TemplateArgStringMap::iterator Found = TemplateArgStrings.find(ND); 938 if (Found == TemplateArgStrings.end()) { 939 // Mangle full template name into temporary buffer. 940 llvm::SmallString<64> TemplateMangling; 941 llvm::raw_svector_ostream Stream(TemplateMangling); 942 MicrosoftCXXNameMangler Extra(Context, Stream); 943 Extra.mangleTemplateInstantiationName(TD, *TemplateArgs); 944 945 // Use the string backref vector to possibly get a back reference. 946 mangleSourceName(TemplateMangling); 947 948 // Memoize back reference for this type if one exist, else memoize 949 // the mangling itself. 950 BackRefVec::iterator StringFound = 951 llvm::find(NameBackReferences, TemplateMangling); 952 if (StringFound != NameBackReferences.end()) { 953 TemplateArgBackReferences[ND] = 954 StringFound - NameBackReferences.begin(); 955 } else { 956 TemplateArgStrings[ND] = 957 TemplateArgStringStorage.save(TemplateMangling.str()); 958 } 959 } else { 960 Out << Found->second << '@'; // Outputs a StringRef. 961 } 962 } else { 963 Out << Found->second; // Outputs a back reference (an int). 964 } 965 return; 966 } 967 968 switch (Name.getNameKind()) { 969 case DeclarationName::Identifier: { 970 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { 971 bool IsDeviceStub = 972 ND && 973 ((isa<FunctionDecl>(ND) && ND->hasAttr<CUDAGlobalAttr>()) || 974 (isa<FunctionTemplateDecl>(ND) && 975 cast<FunctionTemplateDecl>(ND) 976 ->getTemplatedDecl() 977 ->hasAttr<CUDAGlobalAttr>())) && 978 GD.getKernelReferenceKind() == KernelReferenceKind::Stub; 979 if (IsDeviceStub) 980 mangleSourceName( 981 (llvm::Twine("__device_stub__") + II->getName()).str()); 982 else 983 mangleSourceName(II->getName()); 984 break; 985 } 986 987 // Otherwise, an anonymous entity. We must have a declaration. 988 assert(ND && "mangling empty name without declaration"); 989 990 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 991 if (NS->isAnonymousNamespace()) { 992 Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@'; 993 break; 994 } 995 } 996 997 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) { 998 // Decomposition declarations are considered anonymous, and get 999 // numbered with a $S prefix. 1000 llvm::SmallString<64> Name("$S"); 1001 // Get a unique id for the anonymous struct. 1002 Name += llvm::utostr(Context.getAnonymousStructId(DD) + 1); 1003 mangleSourceName(Name); 1004 break; 1005 } 1006 1007 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1008 // We must have an anonymous union or struct declaration. 1009 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl(); 1010 assert(RD && "expected variable decl to have a record type"); 1011 // Anonymous types with no tag or typedef get the name of their 1012 // declarator mangled in. If they have no declarator, number them with 1013 // a $S prefix. 1014 llvm::SmallString<64> Name("$S"); 1015 // Get a unique id for the anonymous struct. 1016 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1); 1017 mangleSourceName(Name.str()); 1018 break; 1019 } 1020 1021 if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(ND)) { 1022 // Mangle a GUID object as if it were a variable with the corresponding 1023 // mangled name. 1024 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID; 1025 llvm::raw_svector_ostream GUIDOS(GUID); 1026 Context.mangleMSGuidDecl(GD, GUIDOS); 1027 mangleSourceName(GUID); 1028 break; 1029 } 1030 1031 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) { 1032 Out << "?__N"; 1033 mangleTemplateArgValue(TPO->getType().getUnqualifiedType(), 1034 TPO->getValue()); 1035 break; 1036 } 1037 1038 // We must have an anonymous struct. 1039 const TagDecl *TD = cast<TagDecl>(ND); 1040 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { 1041 assert(TD->getDeclContext() == D->getDeclContext() && 1042 "Typedef should not be in another decl context!"); 1043 assert(D->getDeclName().getAsIdentifierInfo() && 1044 "Typedef was not named!"); 1045 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName()); 1046 break; 1047 } 1048 1049 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { 1050 if (Record->isLambda()) { 1051 llvm::SmallString<10> Name("<lambda_"); 1052 1053 Decl *LambdaContextDecl = Record->getLambdaContextDecl(); 1054 unsigned LambdaManglingNumber = Record->getLambdaManglingNumber(); 1055 unsigned LambdaId; 1056 const ParmVarDecl *Parm = 1057 dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl); 1058 const FunctionDecl *Func = 1059 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr; 1060 1061 if (Func) { 1062 unsigned DefaultArgNo = 1063 Func->getNumParams() - Parm->getFunctionScopeIndex(); 1064 Name += llvm::utostr(DefaultArgNo); 1065 Name += "_"; 1066 } 1067 1068 if (LambdaManglingNumber) 1069 LambdaId = LambdaManglingNumber; 1070 else 1071 LambdaId = Context.getLambdaId(Record); 1072 1073 Name += llvm::utostr(LambdaId); 1074 Name += ">"; 1075 1076 mangleSourceName(Name); 1077 1078 // If the context is a variable or a class member and not a parameter, 1079 // it is encoded in a qualified name. 1080 if (LambdaManglingNumber && LambdaContextDecl) { 1081 if ((isa<VarDecl>(LambdaContextDecl) || 1082 isa<FieldDecl>(LambdaContextDecl)) && 1083 !isa<ParmVarDecl>(LambdaContextDecl)) { 1084 mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl)); 1085 } 1086 } 1087 break; 1088 } 1089 } 1090 1091 llvm::SmallString<64> Name; 1092 if (DeclaratorDecl *DD = 1093 Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) { 1094 // Anonymous types without a name for linkage purposes have their 1095 // declarator mangled in if they have one. 1096 Name += "<unnamed-type-"; 1097 Name += DD->getName(); 1098 } else if (TypedefNameDecl *TND = 1099 Context.getASTContext().getTypedefNameForUnnamedTagDecl( 1100 TD)) { 1101 // Anonymous types without a name for linkage purposes have their 1102 // associate typedef mangled in if they have one. 1103 Name += "<unnamed-type-"; 1104 Name += TND->getName(); 1105 } else if (isa<EnumDecl>(TD) && 1106 cast<EnumDecl>(TD)->enumerator_begin() != 1107 cast<EnumDecl>(TD)->enumerator_end()) { 1108 // Anonymous non-empty enums mangle in the first enumerator. 1109 auto *ED = cast<EnumDecl>(TD); 1110 Name += "<unnamed-enum-"; 1111 Name += ED->enumerator_begin()->getName(); 1112 } else { 1113 // Otherwise, number the types using a $S prefix. 1114 Name += "<unnamed-type-$S"; 1115 Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1); 1116 } 1117 Name += ">"; 1118 mangleSourceName(Name.str()); 1119 break; 1120 } 1121 1122 case DeclarationName::ObjCZeroArgSelector: 1123 case DeclarationName::ObjCOneArgSelector: 1124 case DeclarationName::ObjCMultiArgSelector: { 1125 // This is reachable only when constructing an outlined SEH finally 1126 // block. Nothing depends on this mangling and it's used only with 1127 // functinos with internal linkage. 1128 llvm::SmallString<64> Name; 1129 mangleSourceName(Name.str()); 1130 break; 1131 } 1132 1133 case DeclarationName::CXXConstructorName: 1134 if (isStructorDecl(ND)) { 1135 if (StructorType == Ctor_CopyingClosure) { 1136 Out << "?_O"; 1137 return; 1138 } 1139 if (StructorType == Ctor_DefaultClosure) { 1140 Out << "?_F"; 1141 return; 1142 } 1143 } 1144 Out << "?0"; 1145 return; 1146 1147 case DeclarationName::CXXDestructorName: 1148 if (isStructorDecl(ND)) 1149 // If the named decl is the C++ destructor we're mangling, 1150 // use the type we were given. 1151 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType)); 1152 else 1153 // Otherwise, use the base destructor name. This is relevant if a 1154 // class with a destructor is declared within a destructor. 1155 mangleCXXDtorType(Dtor_Base); 1156 break; 1157 1158 case DeclarationName::CXXConversionFunctionName: 1159 // <operator-name> ::= ?B # (cast) 1160 // The target type is encoded as the return type. 1161 Out << "?B"; 1162 break; 1163 1164 case DeclarationName::CXXOperatorName: 1165 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation()); 1166 break; 1167 1168 case DeclarationName::CXXLiteralOperatorName: { 1169 Out << "?__K"; 1170 mangleSourceName(Name.getCXXLiteralIdentifier()->getName()); 1171 break; 1172 } 1173 1174 case DeclarationName::CXXDeductionGuideName: 1175 llvm_unreachable("Can't mangle a deduction guide name!"); 1176 1177 case DeclarationName::CXXUsingDirective: 1178 llvm_unreachable("Can't mangle a using directive name!"); 1179 } 1180 } 1181 1182 // <postfix> ::= <unqualified-name> [<postfix>] 1183 // ::= <substitution> [<postfix>] 1184 void MicrosoftCXXNameMangler::mangleNestedName(GlobalDecl GD) { 1185 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 1186 const DeclContext *DC = getEffectiveDeclContext(ND); 1187 while (!DC->isTranslationUnit()) { 1188 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) { 1189 unsigned Disc; 1190 if (Context.getNextDiscriminator(ND, Disc)) { 1191 Out << '?'; 1192 mangleNumber(Disc); 1193 Out << '?'; 1194 } 1195 } 1196 1197 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) { 1198 auto Discriminate = 1199 [](StringRef Name, const unsigned Discriminator, 1200 const unsigned ParameterDiscriminator) -> std::string { 1201 std::string Buffer; 1202 llvm::raw_string_ostream Stream(Buffer); 1203 Stream << Name; 1204 if (Discriminator) 1205 Stream << '_' << Discriminator; 1206 if (ParameterDiscriminator) 1207 Stream << '_' << ParameterDiscriminator; 1208 return Stream.str(); 1209 }; 1210 1211 unsigned Discriminator = BD->getBlockManglingNumber(); 1212 if (!Discriminator) 1213 Discriminator = Context.getBlockId(BD, /*Local=*/false); 1214 1215 // Mangle the parameter position as a discriminator to deal with unnamed 1216 // parameters. Rather than mangling the unqualified parameter name, 1217 // always use the position to give a uniform mangling. 1218 unsigned ParameterDiscriminator = 0; 1219 if (const auto *MC = BD->getBlockManglingContextDecl()) 1220 if (const auto *P = dyn_cast<ParmVarDecl>(MC)) 1221 if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext())) 1222 ParameterDiscriminator = 1223 F->getNumParams() - P->getFunctionScopeIndex(); 1224 1225 DC = getEffectiveDeclContext(BD); 1226 1227 Out << '?'; 1228 mangleSourceName(Discriminate("_block_invoke", Discriminator, 1229 ParameterDiscriminator)); 1230 // If we have a block mangling context, encode that now. This allows us 1231 // to discriminate between named static data initializers in the same 1232 // scope. This is handled differently from parameters, which use 1233 // positions to discriminate between multiple instances. 1234 if (const auto *MC = BD->getBlockManglingContextDecl()) 1235 if (!isa<ParmVarDecl>(MC)) 1236 if (const auto *ND = dyn_cast<NamedDecl>(MC)) 1237 mangleUnqualifiedName(ND); 1238 // MS ABI and Itanium manglings are in inverted scopes. In the case of a 1239 // RecordDecl, mangle the entire scope hierarchy at this point rather than 1240 // just the unqualified name to get the ordering correct. 1241 if (const auto *RD = dyn_cast<RecordDecl>(DC)) 1242 mangleName(RD); 1243 else 1244 Out << '@'; 1245 // void __cdecl 1246 Out << "YAX"; 1247 // struct __block_literal * 1248 Out << 'P'; 1249 // __ptr64 1250 if (PointersAre64Bit) 1251 Out << 'E'; 1252 Out << 'A'; 1253 mangleArtificialTagType(TTK_Struct, 1254 Discriminate("__block_literal", Discriminator, 1255 ParameterDiscriminator)); 1256 Out << "@Z"; 1257 1258 // If the effective context was a Record, we have fully mangled the 1259 // qualified name and do not need to continue. 1260 if (isa<RecordDecl>(DC)) 1261 break; 1262 continue; 1263 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) { 1264 mangleObjCMethodName(Method); 1265 } else if (isa<NamedDecl>(DC)) { 1266 ND = cast<NamedDecl>(DC); 1267 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 1268 mangle(getGlobalDeclAsDeclContext(FD), "?"); 1269 break; 1270 } else { 1271 mangleUnqualifiedName(ND); 1272 // Lambdas in default arguments conceptually belong to the function the 1273 // parameter corresponds to. 1274 if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) { 1275 DC = LDADC; 1276 continue; 1277 } 1278 } 1279 } 1280 DC = DC->getParent(); 1281 } 1282 } 1283 1284 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 1285 // Microsoft uses the names on the case labels for these dtor variants. Clang 1286 // uses the Itanium terminology internally. Everything in this ABI delegates 1287 // towards the base dtor. 1288 switch (T) { 1289 // <operator-name> ::= ?1 # destructor 1290 case Dtor_Base: Out << "?1"; return; 1291 // <operator-name> ::= ?_D # vbase destructor 1292 case Dtor_Complete: Out << "?_D"; return; 1293 // <operator-name> ::= ?_G # scalar deleting destructor 1294 case Dtor_Deleting: Out << "?_G"; return; 1295 // <operator-name> ::= ?_E # vector deleting destructor 1296 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need 1297 // it. 1298 case Dtor_Comdat: 1299 llvm_unreachable("not expecting a COMDAT"); 1300 } 1301 llvm_unreachable("Unsupported dtor type?"); 1302 } 1303 1304 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, 1305 SourceLocation Loc) { 1306 switch (OO) { 1307 // ?0 # constructor 1308 // ?1 # destructor 1309 // <operator-name> ::= ?2 # new 1310 case OO_New: Out << "?2"; break; 1311 // <operator-name> ::= ?3 # delete 1312 case OO_Delete: Out << "?3"; break; 1313 // <operator-name> ::= ?4 # = 1314 case OO_Equal: Out << "?4"; break; 1315 // <operator-name> ::= ?5 # >> 1316 case OO_GreaterGreater: Out << "?5"; break; 1317 // <operator-name> ::= ?6 # << 1318 case OO_LessLess: Out << "?6"; break; 1319 // <operator-name> ::= ?7 # ! 1320 case OO_Exclaim: Out << "?7"; break; 1321 // <operator-name> ::= ?8 # == 1322 case OO_EqualEqual: Out << "?8"; break; 1323 // <operator-name> ::= ?9 # != 1324 case OO_ExclaimEqual: Out << "?9"; break; 1325 // <operator-name> ::= ?A # [] 1326 case OO_Subscript: Out << "?A"; break; 1327 // ?B # conversion 1328 // <operator-name> ::= ?C # -> 1329 case OO_Arrow: Out << "?C"; break; 1330 // <operator-name> ::= ?D # * 1331 case OO_Star: Out << "?D"; break; 1332 // <operator-name> ::= ?E # ++ 1333 case OO_PlusPlus: Out << "?E"; break; 1334 // <operator-name> ::= ?F # -- 1335 case OO_MinusMinus: Out << "?F"; break; 1336 // <operator-name> ::= ?G # - 1337 case OO_Minus: Out << "?G"; break; 1338 // <operator-name> ::= ?H # + 1339 case OO_Plus: Out << "?H"; break; 1340 // <operator-name> ::= ?I # & 1341 case OO_Amp: Out << "?I"; break; 1342 // <operator-name> ::= ?J # ->* 1343 case OO_ArrowStar: Out << "?J"; break; 1344 // <operator-name> ::= ?K # / 1345 case OO_Slash: Out << "?K"; break; 1346 // <operator-name> ::= ?L # % 1347 case OO_Percent: Out << "?L"; break; 1348 // <operator-name> ::= ?M # < 1349 case OO_Less: Out << "?M"; break; 1350 // <operator-name> ::= ?N # <= 1351 case OO_LessEqual: Out << "?N"; break; 1352 // <operator-name> ::= ?O # > 1353 case OO_Greater: Out << "?O"; break; 1354 // <operator-name> ::= ?P # >= 1355 case OO_GreaterEqual: Out << "?P"; break; 1356 // <operator-name> ::= ?Q # , 1357 case OO_Comma: Out << "?Q"; break; 1358 // <operator-name> ::= ?R # () 1359 case OO_Call: Out << "?R"; break; 1360 // <operator-name> ::= ?S # ~ 1361 case OO_Tilde: Out << "?S"; break; 1362 // <operator-name> ::= ?T # ^ 1363 case OO_Caret: Out << "?T"; break; 1364 // <operator-name> ::= ?U # | 1365 case OO_Pipe: Out << "?U"; break; 1366 // <operator-name> ::= ?V # && 1367 case OO_AmpAmp: Out << "?V"; break; 1368 // <operator-name> ::= ?W # || 1369 case OO_PipePipe: Out << "?W"; break; 1370 // <operator-name> ::= ?X # *= 1371 case OO_StarEqual: Out << "?X"; break; 1372 // <operator-name> ::= ?Y # += 1373 case OO_PlusEqual: Out << "?Y"; break; 1374 // <operator-name> ::= ?Z # -= 1375 case OO_MinusEqual: Out << "?Z"; break; 1376 // <operator-name> ::= ?_0 # /= 1377 case OO_SlashEqual: Out << "?_0"; break; 1378 // <operator-name> ::= ?_1 # %= 1379 case OO_PercentEqual: Out << "?_1"; break; 1380 // <operator-name> ::= ?_2 # >>= 1381 case OO_GreaterGreaterEqual: Out << "?_2"; break; 1382 // <operator-name> ::= ?_3 # <<= 1383 case OO_LessLessEqual: Out << "?_3"; break; 1384 // <operator-name> ::= ?_4 # &= 1385 case OO_AmpEqual: Out << "?_4"; break; 1386 // <operator-name> ::= ?_5 # |= 1387 case OO_PipeEqual: Out << "?_5"; break; 1388 // <operator-name> ::= ?_6 # ^= 1389 case OO_CaretEqual: Out << "?_6"; break; 1390 // ?_7 # vftable 1391 // ?_8 # vbtable 1392 // ?_9 # vcall 1393 // ?_A # typeof 1394 // ?_B # local static guard 1395 // ?_C # string 1396 // ?_D # vbase destructor 1397 // ?_E # vector deleting destructor 1398 // ?_F # default constructor closure 1399 // ?_G # scalar deleting destructor 1400 // ?_H # vector constructor iterator 1401 // ?_I # vector destructor iterator 1402 // ?_J # vector vbase constructor iterator 1403 // ?_K # virtual displacement map 1404 // ?_L # eh vector constructor iterator 1405 // ?_M # eh vector destructor iterator 1406 // ?_N # eh vector vbase constructor iterator 1407 // ?_O # copy constructor closure 1408 // ?_P<name> # udt returning <name> 1409 // ?_Q # <unknown> 1410 // ?_R0 # RTTI Type Descriptor 1411 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d) 1412 // ?_R2 # RTTI Base Class Array 1413 // ?_R3 # RTTI Class Hierarchy Descriptor 1414 // ?_R4 # RTTI Complete Object Locator 1415 // ?_S # local vftable 1416 // ?_T # local vftable constructor closure 1417 // <operator-name> ::= ?_U # new[] 1418 case OO_Array_New: Out << "?_U"; break; 1419 // <operator-name> ::= ?_V # delete[] 1420 case OO_Array_Delete: Out << "?_V"; break; 1421 // <operator-name> ::= ?__L # co_await 1422 case OO_Coawait: Out << "?__L"; break; 1423 // <operator-name> ::= ?__M # <=> 1424 case OO_Spaceship: Out << "?__M"; break; 1425 1426 case OO_Conditional: { 1427 DiagnosticsEngine &Diags = Context.getDiags(); 1428 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1429 "cannot mangle this conditional operator yet"); 1430 Diags.Report(Loc, DiagID); 1431 break; 1432 } 1433 1434 case OO_None: 1435 case NUM_OVERLOADED_OPERATORS: 1436 llvm_unreachable("Not an overloaded operator"); 1437 } 1438 } 1439 1440 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) { 1441 // <source name> ::= <identifier> @ 1442 BackRefVec::iterator Found = llvm::find(NameBackReferences, Name); 1443 if (Found == NameBackReferences.end()) { 1444 if (NameBackReferences.size() < 10) 1445 NameBackReferences.push_back(std::string(Name)); 1446 Out << Name << '@'; 1447 } else { 1448 Out << (Found - NameBackReferences.begin()); 1449 } 1450 } 1451 1452 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 1453 Context.mangleObjCMethodNameAsSourceName(MD, Out); 1454 } 1455 1456 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName( 1457 GlobalDecl GD, const TemplateArgumentList &TemplateArgs) { 1458 // <template-name> ::= <unscoped-template-name> <template-args> 1459 // ::= <substitution> 1460 // Always start with the unqualified name. 1461 1462 // Templates have their own context for back references. 1463 ArgBackRefMap OuterFunArgsContext; 1464 ArgBackRefMap OuterTemplateArgsContext; 1465 BackRefVec OuterTemplateContext; 1466 PassObjectSizeArgsSet OuterPassObjectSizeArgs; 1467 NameBackReferences.swap(OuterTemplateContext); 1468 FunArgBackReferences.swap(OuterFunArgsContext); 1469 TemplateArgBackReferences.swap(OuterTemplateArgsContext); 1470 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs); 1471 1472 mangleUnscopedTemplateName(GD); 1473 mangleTemplateArgs(cast<TemplateDecl>(GD.getDecl()), TemplateArgs); 1474 1475 // Restore the previous back reference contexts. 1476 NameBackReferences.swap(OuterTemplateContext); 1477 FunArgBackReferences.swap(OuterFunArgsContext); 1478 TemplateArgBackReferences.swap(OuterTemplateArgsContext); 1479 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs); 1480 } 1481 1482 void MicrosoftCXXNameMangler::mangleUnscopedTemplateName(GlobalDecl GD) { 1483 // <unscoped-template-name> ::= ?$ <unqualified-name> 1484 Out << "?$"; 1485 mangleUnqualifiedName(GD); 1486 } 1487 1488 void MicrosoftCXXNameMangler::mangleIntegerLiteral( 1489 const llvm::APSInt &Value, const NonTypeTemplateParmDecl *PD, 1490 QualType TemplateArgType) { 1491 // <integer-literal> ::= $0 <number> 1492 Out << "$"; 1493 1494 // Since MSVC 2019, add 'M[<type>]' after '$' for auto template parameter when 1495 // argument is integer. 1496 if (getASTContext().getLangOpts().isCompatibleWithMSVC( 1497 LangOptions::MSVC2019) && 1498 PD && PD->getType()->getTypeClass() == Type::Auto && 1499 !TemplateArgType.isNull()) { 1500 Out << "M"; 1501 mangleType(TemplateArgType, SourceRange(), QMM_Drop); 1502 } 1503 1504 Out << "0"; 1505 1506 mangleNumber(Value); 1507 } 1508 1509 void MicrosoftCXXNameMangler::mangleExpression( 1510 const Expr *E, const NonTypeTemplateParmDecl *PD) { 1511 // See if this is a constant expression. 1512 if (std::optional<llvm::APSInt> Value = 1513 E->getIntegerConstantExpr(Context.getASTContext())) { 1514 mangleIntegerLiteral(*Value, PD, E->getType()); 1515 return; 1516 } 1517 1518 // As bad as this diagnostic is, it's better than crashing. 1519 DiagnosticsEngine &Diags = Context.getDiags(); 1520 unsigned DiagID = Diags.getCustomDiagID( 1521 DiagnosticsEngine::Error, "cannot yet mangle expression type %0"); 1522 Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName() 1523 << E->getSourceRange(); 1524 } 1525 1526 void MicrosoftCXXNameMangler::mangleTemplateArgs( 1527 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) { 1528 // <template-args> ::= <template-arg>+ 1529 const TemplateParameterList *TPL = TD->getTemplateParameters(); 1530 assert(TPL->size() == TemplateArgs.size() && 1531 "size mismatch between args and parms!"); 1532 1533 for (size_t i = 0; i < TemplateArgs.size(); ++i) { 1534 const TemplateArgument &TA = TemplateArgs[i]; 1535 1536 // Separate consecutive packs by $$Z. 1537 if (i > 0 && TA.getKind() == TemplateArgument::Pack && 1538 TemplateArgs[i - 1].getKind() == TemplateArgument::Pack) 1539 Out << "$$Z"; 1540 1541 mangleTemplateArg(TD, TA, TPL->getParam(i)); 1542 } 1543 } 1544 1545 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD, 1546 const TemplateArgument &TA, 1547 const NamedDecl *Parm) { 1548 // <template-arg> ::= <type> 1549 // ::= <integer-literal> 1550 // ::= <member-data-pointer> 1551 // ::= <member-function-pointer> 1552 // ::= $ <constant-value> 1553 // ::= <template-args> 1554 // 1555 // <constant-value> ::= 0 <number> # integer 1556 // ::= 1 <mangled-name> # address of D 1557 // ::= 2 <type> <typed-constant-value>* @ # struct 1558 // ::= 3 <type> <constant-value>* @ # array 1559 // ::= 4 ??? # string 1560 // ::= 5 <constant-value> @ # address of subobject 1561 // ::= 6 <constant-value> <unqualified-name> @ # a.b 1562 // ::= 7 <type> [<unqualified-name> <constant-value>] @ 1563 // # union, with or without an active member 1564 // # pointer to member, symbolically 1565 // ::= 8 <class> <unqualified-name> @ 1566 // ::= A <type> <non-negative integer> # float 1567 // ::= B <type> <non-negative integer> # double 1568 // ::= E <mangled-name> # reference to D 1569 // # pointer to member, by component value 1570 // ::= F <number> <number> 1571 // ::= G <number> <number> <number> 1572 // ::= H <mangled-name> <number> 1573 // ::= I <mangled-name> <number> <number> 1574 // ::= J <mangled-name> <number> <number> <number> 1575 // 1576 // <typed-constant-value> ::= [<type>] <constant-value> 1577 // 1578 // The <type> appears to be included in a <typed-constant-value> only in the 1579 // '0', '1', '8', 'A', 'B', and 'E' cases. 1580 1581 switch (TA.getKind()) { 1582 case TemplateArgument::Null: 1583 llvm_unreachable("Can't mangle null template arguments!"); 1584 case TemplateArgument::TemplateExpansion: 1585 llvm_unreachable("Can't mangle template expansion arguments!"); 1586 case TemplateArgument::Type: { 1587 QualType T = TA.getAsType(); 1588 mangleType(T, SourceRange(), QMM_Escape); 1589 break; 1590 } 1591 case TemplateArgument::Declaration: { 1592 const NamedDecl *ND = TA.getAsDecl(); 1593 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) { 1594 mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext()) 1595 ->getMostRecentNonInjectedDecl(), 1596 cast<ValueDecl>(ND)); 1597 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 1598 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 1599 if (MD && MD->isInstance()) { 1600 mangleMemberFunctionPointer( 1601 MD->getParent()->getMostRecentNonInjectedDecl(), MD); 1602 } else { 1603 Out << "$1?"; 1604 mangleName(FD); 1605 mangleFunctionEncoding(FD, /*ShouldMangle=*/true); 1606 } 1607 } else if (TA.getParamTypeForDecl()->isRecordType()) { 1608 Out << "$"; 1609 auto *TPO = cast<TemplateParamObjectDecl>(ND); 1610 mangleTemplateArgValue(TPO->getType().getUnqualifiedType(), 1611 TPO->getValue()); 1612 } else { 1613 mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?"); 1614 } 1615 break; 1616 } 1617 case TemplateArgument::Integral: { 1618 QualType T = TA.getIntegralType(); 1619 mangleIntegerLiteral(TA.getAsIntegral(), 1620 cast<NonTypeTemplateParmDecl>(Parm), T); 1621 break; 1622 } 1623 case TemplateArgument::NullPtr: { 1624 QualType T = TA.getNullPtrType(); 1625 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) { 1626 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1627 if (MPT->isMemberFunctionPointerType() && 1628 !isa<FunctionTemplateDecl>(TD)) { 1629 mangleMemberFunctionPointer(RD, nullptr); 1630 return; 1631 } 1632 if (MPT->isMemberDataPointer()) { 1633 if (!isa<FunctionTemplateDecl>(TD)) { 1634 mangleMemberDataPointer(RD, nullptr); 1635 return; 1636 } 1637 // nullptr data pointers are always represented with a single field 1638 // which is initialized with either 0 or -1. Why -1? Well, we need to 1639 // distinguish the case where the data member is at offset zero in the 1640 // record. 1641 // However, we are free to use 0 *if* we would use multiple fields for 1642 // non-nullptr member pointers. 1643 if (!RD->nullFieldOffsetIsZero()) { 1644 mangleIntegerLiteral(llvm::APSInt::get(-1), 1645 cast<NonTypeTemplateParmDecl>(Parm), T); 1646 return; 1647 } 1648 } 1649 } 1650 mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), 1651 cast<NonTypeTemplateParmDecl>(Parm), T); 1652 break; 1653 } 1654 case TemplateArgument::Expression: 1655 mangleExpression(TA.getAsExpr(), cast<NonTypeTemplateParmDecl>(Parm)); 1656 break; 1657 case TemplateArgument::Pack: { 1658 ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray(); 1659 if (TemplateArgs.empty()) { 1660 if (isa<TemplateTypeParmDecl>(Parm) || 1661 isa<TemplateTemplateParmDecl>(Parm)) 1662 // MSVC 2015 changed the mangling for empty expanded template packs, 1663 // use the old mangling for link compatibility for old versions. 1664 Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC( 1665 LangOptions::MSVC2015) 1666 ? "$$V" 1667 : "$$$V"); 1668 else if (isa<NonTypeTemplateParmDecl>(Parm)) 1669 Out << "$S"; 1670 else 1671 llvm_unreachable("unexpected template parameter decl!"); 1672 } else { 1673 for (const TemplateArgument &PA : TemplateArgs) 1674 mangleTemplateArg(TD, PA, Parm); 1675 } 1676 break; 1677 } 1678 case TemplateArgument::Template: { 1679 const NamedDecl *ND = 1680 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl(); 1681 if (const auto *TD = dyn_cast<TagDecl>(ND)) { 1682 mangleType(TD); 1683 } else if (isa<TypeAliasDecl>(ND)) { 1684 Out << "$$Y"; 1685 mangleName(ND); 1686 } else { 1687 llvm_unreachable("unexpected template template NamedDecl!"); 1688 } 1689 break; 1690 } 1691 } 1692 } 1693 1694 void MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T, 1695 const APValue &V, 1696 bool WithScalarType) { 1697 switch (V.getKind()) { 1698 case APValue::None: 1699 case APValue::Indeterminate: 1700 // FIXME: MSVC doesn't allow this, so we can't be sure how it should be 1701 // mangled. 1702 if (WithScalarType) 1703 mangleType(T, SourceRange(), QMM_Escape); 1704 Out << '@'; 1705 return; 1706 1707 case APValue::Int: 1708 if (WithScalarType) 1709 mangleType(T, SourceRange(), QMM_Escape); 1710 Out << '0'; 1711 mangleNumber(V.getInt()); 1712 return; 1713 1714 case APValue::Float: 1715 if (WithScalarType) 1716 mangleType(T, SourceRange(), QMM_Escape); 1717 mangleFloat(V.getFloat()); 1718 return; 1719 1720 case APValue::LValue: { 1721 if (WithScalarType) 1722 mangleType(T, SourceRange(), QMM_Escape); 1723 1724 // We don't know how to mangle past-the-end pointers yet. 1725 if (V.isLValueOnePastTheEnd()) 1726 break; 1727 1728 APValue::LValueBase Base = V.getLValueBase(); 1729 if (!V.hasLValuePath() || V.getLValuePath().empty()) { 1730 // Taking the address of a complete object has a special-case mangling. 1731 if (Base.isNull()) { 1732 // MSVC emits 0A@ for null pointers. Generalize this for arbitrary 1733 // integers cast to pointers. 1734 // FIXME: This mangles 0 cast to a pointer the same as a null pointer, 1735 // even in cases where the two are different values. 1736 Out << "0"; 1737 mangleNumber(V.getLValueOffset().getQuantity()); 1738 } else if (!V.hasLValuePath()) { 1739 // FIXME: This can only happen as an extension. Invent a mangling. 1740 break; 1741 } else if (auto *VD = Base.dyn_cast<const ValueDecl*>()) { 1742 Out << (T->isReferenceType() ? "E" : "1"); 1743 mangle(VD); 1744 } else { 1745 break; 1746 } 1747 } else { 1748 unsigned NumAts = 0; 1749 if (T->isPointerType()) { 1750 Out << "5"; 1751 ++NumAts; 1752 } 1753 1754 QualType T = Base.getType(); 1755 for (APValue::LValuePathEntry E : V.getLValuePath()) { 1756 // We don't know how to mangle array subscripting yet. 1757 if (T->isArrayType()) 1758 goto mangling_unknown; 1759 1760 const Decl *D = E.getAsBaseOrMember().getPointer(); 1761 auto *FD = dyn_cast<FieldDecl>(D); 1762 // We don't know how to mangle derived-to-base conversions yet. 1763 if (!FD) 1764 goto mangling_unknown; 1765 1766 Out << "6"; 1767 ++NumAts; 1768 T = FD->getType(); 1769 } 1770 1771 auto *VD = Base.dyn_cast<const ValueDecl*>(); 1772 if (!VD) 1773 break; 1774 Out << "E"; 1775 mangle(VD); 1776 1777 for (APValue::LValuePathEntry E : V.getLValuePath()) { 1778 const Decl *D = E.getAsBaseOrMember().getPointer(); 1779 mangleUnqualifiedName(cast<FieldDecl>(D)); 1780 } 1781 for (unsigned I = 0; I != NumAts; ++I) 1782 Out << '@'; 1783 } 1784 1785 return; 1786 } 1787 1788 case APValue::MemberPointer: { 1789 if (WithScalarType) 1790 mangleType(T, SourceRange(), QMM_Escape); 1791 1792 // FIXME: The below manglings don't include a conversion, so bail if there 1793 // would be one. MSVC mangles the (possibly converted) value of the 1794 // pointer-to-member object as if it were a struct, leading to collisions 1795 // in some cases. 1796 if (!V.getMemberPointerPath().empty()) 1797 break; 1798 1799 const CXXRecordDecl *RD = 1800 T->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl(); 1801 const ValueDecl *D = V.getMemberPointerDecl(); 1802 if (T->isMemberDataPointerType()) 1803 mangleMemberDataPointer(RD, D, ""); 1804 else 1805 mangleMemberFunctionPointer(RD, cast_or_null<CXXMethodDecl>(D), ""); 1806 return; 1807 } 1808 1809 case APValue::Struct: { 1810 Out << '2'; 1811 mangleType(T, SourceRange(), QMM_Escape); 1812 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 1813 assert(RD && "unexpected type for record value"); 1814 1815 unsigned BaseIndex = 0; 1816 for (const CXXBaseSpecifier &B : RD->bases()) 1817 mangleTemplateArgValue(B.getType(), V.getStructBase(BaseIndex++)); 1818 for (const FieldDecl *FD : RD->fields()) 1819 if (!FD->isUnnamedBitfield()) 1820 mangleTemplateArgValue(FD->getType(), 1821 V.getStructField(FD->getFieldIndex()), 1822 /*WithScalarType*/ true); 1823 Out << '@'; 1824 return; 1825 } 1826 1827 case APValue::Union: 1828 Out << '7'; 1829 mangleType(T, SourceRange(), QMM_Escape); 1830 if (const FieldDecl *FD = V.getUnionField()) { 1831 mangleUnqualifiedName(FD); 1832 mangleTemplateArgValue(FD->getType(), V.getUnionValue()); 1833 } 1834 Out << '@'; 1835 return; 1836 1837 case APValue::ComplexInt: 1838 // We mangle complex types as structs, so mangle the value as a struct too. 1839 Out << '2'; 1840 mangleType(T, SourceRange(), QMM_Escape); 1841 Out << '0'; 1842 mangleNumber(V.getComplexIntReal()); 1843 Out << '0'; 1844 mangleNumber(V.getComplexIntImag()); 1845 Out << '@'; 1846 return; 1847 1848 case APValue::ComplexFloat: 1849 Out << '2'; 1850 mangleType(T, SourceRange(), QMM_Escape); 1851 mangleFloat(V.getComplexFloatReal()); 1852 mangleFloat(V.getComplexFloatImag()); 1853 Out << '@'; 1854 return; 1855 1856 case APValue::Array: { 1857 Out << '3'; 1858 QualType ElemT = getASTContext().getAsArrayType(T)->getElementType(); 1859 mangleType(ElemT, SourceRange(), QMM_Escape); 1860 for (unsigned I = 0, N = V.getArraySize(); I != N; ++I) { 1861 const APValue &ElemV = I < V.getArrayInitializedElts() 1862 ? V.getArrayInitializedElt(I) 1863 : V.getArrayFiller(); 1864 mangleTemplateArgValue(ElemT, ElemV); 1865 Out << '@'; 1866 } 1867 Out << '@'; 1868 return; 1869 } 1870 1871 case APValue::Vector: { 1872 // __m128 is mangled as a struct containing an array. We follow this 1873 // approach for all vector types. 1874 Out << '2'; 1875 mangleType(T, SourceRange(), QMM_Escape); 1876 Out << '3'; 1877 QualType ElemT = T->castAs<VectorType>()->getElementType(); 1878 mangleType(ElemT, SourceRange(), QMM_Escape); 1879 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) { 1880 const APValue &ElemV = V.getVectorElt(I); 1881 mangleTemplateArgValue(ElemT, ElemV); 1882 Out << '@'; 1883 } 1884 Out << "@@"; 1885 return; 1886 } 1887 1888 case APValue::AddrLabelDiff: 1889 case APValue::FixedPoint: 1890 break; 1891 } 1892 1893 mangling_unknown: 1894 DiagnosticsEngine &Diags = Context.getDiags(); 1895 unsigned DiagID = Diags.getCustomDiagID( 1896 DiagnosticsEngine::Error, "cannot mangle this template argument yet"); 1897 Diags.Report(DiagID); 1898 } 1899 1900 void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) { 1901 llvm::SmallString<64> TemplateMangling; 1902 llvm::raw_svector_ostream Stream(TemplateMangling); 1903 MicrosoftCXXNameMangler Extra(Context, Stream); 1904 1905 Stream << "?$"; 1906 Extra.mangleSourceName("Protocol"); 1907 Extra.mangleArtificialTagType(TTK_Struct, PD->getName()); 1908 1909 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"}); 1910 } 1911 1912 void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type, 1913 Qualifiers Quals, 1914 SourceRange Range) { 1915 llvm::SmallString<64> TemplateMangling; 1916 llvm::raw_svector_ostream Stream(TemplateMangling); 1917 MicrosoftCXXNameMangler Extra(Context, Stream); 1918 1919 Stream << "?$"; 1920 switch (Quals.getObjCLifetime()) { 1921 case Qualifiers::OCL_None: 1922 case Qualifiers::OCL_ExplicitNone: 1923 break; 1924 case Qualifiers::OCL_Autoreleasing: 1925 Extra.mangleSourceName("Autoreleasing"); 1926 break; 1927 case Qualifiers::OCL_Strong: 1928 Extra.mangleSourceName("Strong"); 1929 break; 1930 case Qualifiers::OCL_Weak: 1931 Extra.mangleSourceName("Weak"); 1932 break; 1933 } 1934 Extra.manglePointerCVQualifiers(Quals); 1935 Extra.manglePointerExtQualifiers(Quals, Type); 1936 Extra.mangleType(Type, Range); 1937 1938 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"}); 1939 } 1940 1941 void MicrosoftCXXNameMangler::mangleObjCKindOfType(const ObjCObjectType *T, 1942 Qualifiers Quals, 1943 SourceRange Range) { 1944 llvm::SmallString<64> TemplateMangling; 1945 llvm::raw_svector_ostream Stream(TemplateMangling); 1946 MicrosoftCXXNameMangler Extra(Context, Stream); 1947 1948 Stream << "?$"; 1949 Extra.mangleSourceName("KindOf"); 1950 Extra.mangleType(QualType(T, 0) 1951 .stripObjCKindOfType(getASTContext()) 1952 ->castAs<ObjCObjectType>(), 1953 Quals, Range); 1954 1955 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"}); 1956 } 1957 1958 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals, 1959 bool IsMember) { 1960 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers> 1961 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only); 1962 // 'I' means __restrict (32/64-bit). 1963 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict 1964 // keyword! 1965 // <base-cvr-qualifiers> ::= A # near 1966 // ::= B # near const 1967 // ::= C # near volatile 1968 // ::= D # near const volatile 1969 // ::= E # far (16-bit) 1970 // ::= F # far const (16-bit) 1971 // ::= G # far volatile (16-bit) 1972 // ::= H # far const volatile (16-bit) 1973 // ::= I # huge (16-bit) 1974 // ::= J # huge const (16-bit) 1975 // ::= K # huge volatile (16-bit) 1976 // ::= L # huge const volatile (16-bit) 1977 // ::= M <basis> # based 1978 // ::= N <basis> # based const 1979 // ::= O <basis> # based volatile 1980 // ::= P <basis> # based const volatile 1981 // ::= Q # near member 1982 // ::= R # near const member 1983 // ::= S # near volatile member 1984 // ::= T # near const volatile member 1985 // ::= U # far member (16-bit) 1986 // ::= V # far const member (16-bit) 1987 // ::= W # far volatile member (16-bit) 1988 // ::= X # far const volatile member (16-bit) 1989 // ::= Y # huge member (16-bit) 1990 // ::= Z # huge const member (16-bit) 1991 // ::= 0 # huge volatile member (16-bit) 1992 // ::= 1 # huge const volatile member (16-bit) 1993 // ::= 2 <basis> # based member 1994 // ::= 3 <basis> # based const member 1995 // ::= 4 <basis> # based volatile member 1996 // ::= 5 <basis> # based const volatile member 1997 // ::= 6 # near function (pointers only) 1998 // ::= 7 # far function (pointers only) 1999 // ::= 8 # near method (pointers only) 2000 // ::= 9 # far method (pointers only) 2001 // ::= _A <basis> # based function (pointers only) 2002 // ::= _B <basis> # based function (far?) (pointers only) 2003 // ::= _C <basis> # based method (pointers only) 2004 // ::= _D <basis> # based method (far?) (pointers only) 2005 // ::= _E # block (Clang) 2006 // <basis> ::= 0 # __based(void) 2007 // ::= 1 # __based(segment)? 2008 // ::= 2 <name> # __based(name) 2009 // ::= 3 # ? 2010 // ::= 4 # ? 2011 // ::= 5 # not really based 2012 bool HasConst = Quals.hasConst(), 2013 HasVolatile = Quals.hasVolatile(); 2014 2015 if (!IsMember) { 2016 if (HasConst && HasVolatile) { 2017 Out << 'D'; 2018 } else if (HasVolatile) { 2019 Out << 'C'; 2020 } else if (HasConst) { 2021 Out << 'B'; 2022 } else { 2023 Out << 'A'; 2024 } 2025 } else { 2026 if (HasConst && HasVolatile) { 2027 Out << 'T'; 2028 } else if (HasVolatile) { 2029 Out << 'S'; 2030 } else if (HasConst) { 2031 Out << 'R'; 2032 } else { 2033 Out << 'Q'; 2034 } 2035 } 2036 2037 // FIXME: For now, just drop all extension qualifiers on the floor. 2038 } 2039 2040 void 2041 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 2042 // <ref-qualifier> ::= G # lvalue reference 2043 // ::= H # rvalue-reference 2044 switch (RefQualifier) { 2045 case RQ_None: 2046 break; 2047 2048 case RQ_LValue: 2049 Out << 'G'; 2050 break; 2051 2052 case RQ_RValue: 2053 Out << 'H'; 2054 break; 2055 } 2056 } 2057 2058 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals, 2059 QualType PointeeType) { 2060 // Check if this is a default 64-bit pointer or has __ptr64 qualifier. 2061 bool is64Bit = PointeeType.isNull() ? PointersAre64Bit : 2062 is64BitPointer(PointeeType.getQualifiers()); 2063 if (is64Bit && (PointeeType.isNull() || !PointeeType->isFunctionType())) 2064 Out << 'E'; 2065 2066 if (Quals.hasRestrict()) 2067 Out << 'I'; 2068 2069 if (Quals.hasUnaligned() || 2070 (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned())) 2071 Out << 'F'; 2072 } 2073 2074 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) { 2075 // <pointer-cv-qualifiers> ::= P # no qualifiers 2076 // ::= Q # const 2077 // ::= R # volatile 2078 // ::= S # const volatile 2079 bool HasConst = Quals.hasConst(), 2080 HasVolatile = Quals.hasVolatile(); 2081 2082 if (HasConst && HasVolatile) { 2083 Out << 'S'; 2084 } else if (HasVolatile) { 2085 Out << 'R'; 2086 } else if (HasConst) { 2087 Out << 'Q'; 2088 } else { 2089 Out << 'P'; 2090 } 2091 } 2092 2093 void MicrosoftCXXNameMangler::mangleFunctionArgumentType(QualType T, 2094 SourceRange Range) { 2095 // MSVC will backreference two canonically equivalent types that have slightly 2096 // different manglings when mangled alone. 2097 2098 // Decayed types do not match up with non-decayed versions of the same type. 2099 // 2100 // e.g. 2101 // void (*x)(void) will not form a backreference with void x(void) 2102 void *TypePtr; 2103 if (const auto *DT = T->getAs<DecayedType>()) { 2104 QualType OriginalType = DT->getOriginalType(); 2105 // All decayed ArrayTypes should be treated identically; as-if they were 2106 // a decayed IncompleteArrayType. 2107 if (const auto *AT = getASTContext().getAsArrayType(OriginalType)) 2108 OriginalType = getASTContext().getIncompleteArrayType( 2109 AT->getElementType(), AT->getSizeModifier(), 2110 AT->getIndexTypeCVRQualifiers()); 2111 2112 TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr(); 2113 // If the original parameter was textually written as an array, 2114 // instead treat the decayed parameter like it's const. 2115 // 2116 // e.g. 2117 // int [] -> int * const 2118 if (OriginalType->isArrayType()) 2119 T = T.withConst(); 2120 } else { 2121 TypePtr = T.getCanonicalType().getAsOpaquePtr(); 2122 } 2123 2124 ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr); 2125 2126 if (Found == FunArgBackReferences.end()) { 2127 size_t OutSizeBefore = Out.tell(); 2128 2129 mangleType(T, Range, QMM_Drop); 2130 2131 // See if it's worth creating a back reference. 2132 // Only types longer than 1 character are considered 2133 // and only 10 back references slots are available: 2134 bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1); 2135 if (LongerThanOneChar && FunArgBackReferences.size() < 10) { 2136 size_t Size = FunArgBackReferences.size(); 2137 FunArgBackReferences[TypePtr] = Size; 2138 } 2139 } else { 2140 Out << Found->second; 2141 } 2142 } 2143 2144 void MicrosoftCXXNameMangler::manglePassObjectSizeArg( 2145 const PassObjectSizeAttr *POSA) { 2146 int Type = POSA->getType(); 2147 bool Dynamic = POSA->isDynamic(); 2148 2149 auto Iter = PassObjectSizeArgs.insert({Type, Dynamic}).first; 2150 auto *TypePtr = (const void *)&*Iter; 2151 ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr); 2152 2153 if (Found == FunArgBackReferences.end()) { 2154 std::string Name = 2155 Dynamic ? "__pass_dynamic_object_size" : "__pass_object_size"; 2156 mangleArtificialTagType(TTK_Enum, Name + llvm::utostr(Type), {"__clang"}); 2157 2158 if (FunArgBackReferences.size() < 10) { 2159 size_t Size = FunArgBackReferences.size(); 2160 FunArgBackReferences[TypePtr] = Size; 2161 } 2162 } else { 2163 Out << Found->second; 2164 } 2165 } 2166 2167 void MicrosoftCXXNameMangler::mangleAddressSpaceType(QualType T, 2168 Qualifiers Quals, 2169 SourceRange Range) { 2170 // Address space is mangled as an unqualified templated type in the __clang 2171 // namespace. The demangled version of this is: 2172 // In the case of a language specific address space: 2173 // __clang::struct _AS[language_addr_space]<Type> 2174 // where: 2175 // <language_addr_space> ::= <OpenCL-addrspace> | <CUDA-addrspace> 2176 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" | 2177 // "private"| "generic" | "device" | "host" ] 2178 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ] 2179 // Note that the above were chosen to match the Itanium mangling for this. 2180 // 2181 // In the case of a non-language specific address space: 2182 // __clang::struct _AS<TargetAS, Type> 2183 assert(Quals.hasAddressSpace() && "Not valid without address space"); 2184 llvm::SmallString<32> ASMangling; 2185 llvm::raw_svector_ostream Stream(ASMangling); 2186 MicrosoftCXXNameMangler Extra(Context, Stream); 2187 Stream << "?$"; 2188 2189 LangAS AS = Quals.getAddressSpace(); 2190 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) { 2191 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS); 2192 Extra.mangleSourceName("_AS"); 2193 Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(TargetAS)); 2194 } else { 2195 switch (AS) { 2196 default: 2197 llvm_unreachable("Not a language specific address space"); 2198 case LangAS::opencl_global: 2199 Extra.mangleSourceName("_ASCLglobal"); 2200 break; 2201 case LangAS::opencl_global_device: 2202 Extra.mangleSourceName("_ASCLdevice"); 2203 break; 2204 case LangAS::opencl_global_host: 2205 Extra.mangleSourceName("_ASCLhost"); 2206 break; 2207 case LangAS::opencl_local: 2208 Extra.mangleSourceName("_ASCLlocal"); 2209 break; 2210 case LangAS::opencl_constant: 2211 Extra.mangleSourceName("_ASCLconstant"); 2212 break; 2213 case LangAS::opencl_private: 2214 Extra.mangleSourceName("_ASCLprivate"); 2215 break; 2216 case LangAS::opencl_generic: 2217 Extra.mangleSourceName("_ASCLgeneric"); 2218 break; 2219 case LangAS::cuda_device: 2220 Extra.mangleSourceName("_ASCUdevice"); 2221 break; 2222 case LangAS::cuda_constant: 2223 Extra.mangleSourceName("_ASCUconstant"); 2224 break; 2225 case LangAS::cuda_shared: 2226 Extra.mangleSourceName("_ASCUshared"); 2227 break; 2228 case LangAS::ptr32_sptr: 2229 case LangAS::ptr32_uptr: 2230 case LangAS::ptr64: 2231 llvm_unreachable("don't mangle ptr address spaces with _AS"); 2232 } 2233 } 2234 2235 Extra.mangleType(T, Range, QMM_Escape); 2236 mangleQualifiers(Qualifiers(), false); 2237 mangleArtificialTagType(TTK_Struct, ASMangling, {"__clang"}); 2238 } 2239 2240 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range, 2241 QualifierMangleMode QMM) { 2242 // Don't use the canonical types. MSVC includes things like 'const' on 2243 // pointer arguments to function pointers that canonicalization strips away. 2244 T = T.getDesugaredType(getASTContext()); 2245 Qualifiers Quals = T.getLocalQualifiers(); 2246 2247 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) { 2248 // If there were any Quals, getAsArrayType() pushed them onto the array 2249 // element type. 2250 if (QMM == QMM_Mangle) 2251 Out << 'A'; 2252 else if (QMM == QMM_Escape || QMM == QMM_Result) 2253 Out << "$$B"; 2254 mangleArrayType(AT); 2255 return; 2256 } 2257 2258 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() || 2259 T->isReferenceType() || T->isBlockPointerType(); 2260 2261 switch (QMM) { 2262 case QMM_Drop: 2263 if (Quals.hasObjCLifetime()) 2264 Quals = Quals.withoutObjCLifetime(); 2265 break; 2266 case QMM_Mangle: 2267 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) { 2268 Out << '6'; 2269 mangleFunctionType(FT); 2270 return; 2271 } 2272 mangleQualifiers(Quals, false); 2273 break; 2274 case QMM_Escape: 2275 if (!IsPointer && Quals) { 2276 Out << "$$C"; 2277 mangleQualifiers(Quals, false); 2278 } 2279 break; 2280 case QMM_Result: 2281 // Presence of __unaligned qualifier shouldn't affect mangling here. 2282 Quals.removeUnaligned(); 2283 if (Quals.hasObjCLifetime()) 2284 Quals = Quals.withoutObjCLifetime(); 2285 if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) { 2286 Out << '?'; 2287 mangleQualifiers(Quals, false); 2288 } 2289 break; 2290 } 2291 2292 const Type *ty = T.getTypePtr(); 2293 2294 switch (ty->getTypeClass()) { 2295 #define ABSTRACT_TYPE(CLASS, PARENT) 2296 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 2297 case Type::CLASS: \ 2298 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 2299 return; 2300 #define TYPE(CLASS, PARENT) \ 2301 case Type::CLASS: \ 2302 mangleType(cast<CLASS##Type>(ty), Quals, Range); \ 2303 break; 2304 #include "clang/AST/TypeNodes.inc" 2305 #undef ABSTRACT_TYPE 2306 #undef NON_CANONICAL_TYPE 2307 #undef TYPE 2308 } 2309 } 2310 2311 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers, 2312 SourceRange Range) { 2313 // <type> ::= <builtin-type> 2314 // <builtin-type> ::= X # void 2315 // ::= C # signed char 2316 // ::= D # char 2317 // ::= E # unsigned char 2318 // ::= F # short 2319 // ::= G # unsigned short (or wchar_t if it's not a builtin) 2320 // ::= H # int 2321 // ::= I # unsigned int 2322 // ::= J # long 2323 // ::= K # unsigned long 2324 // L # <none> 2325 // ::= M # float 2326 // ::= N # double 2327 // ::= O # long double (__float80 is mangled differently) 2328 // ::= _J # long long, __int64 2329 // ::= _K # unsigned long long, __int64 2330 // ::= _L # __int128 2331 // ::= _M # unsigned __int128 2332 // ::= _N # bool 2333 // _O # <array in parameter> 2334 // ::= _Q # char8_t 2335 // ::= _S # char16_t 2336 // ::= _T # __float80 (Intel) 2337 // ::= _U # char32_t 2338 // ::= _W # wchar_t 2339 // ::= _Z # __float80 (Digital Mars) 2340 switch (T->getKind()) { 2341 case BuiltinType::Void: 2342 Out << 'X'; 2343 break; 2344 case BuiltinType::SChar: 2345 Out << 'C'; 2346 break; 2347 case BuiltinType::Char_U: 2348 case BuiltinType::Char_S: 2349 Out << 'D'; 2350 break; 2351 case BuiltinType::UChar: 2352 Out << 'E'; 2353 break; 2354 case BuiltinType::Short: 2355 Out << 'F'; 2356 break; 2357 case BuiltinType::UShort: 2358 Out << 'G'; 2359 break; 2360 case BuiltinType::Int: 2361 Out << 'H'; 2362 break; 2363 case BuiltinType::UInt: 2364 Out << 'I'; 2365 break; 2366 case BuiltinType::Long: 2367 Out << 'J'; 2368 break; 2369 case BuiltinType::ULong: 2370 Out << 'K'; 2371 break; 2372 case BuiltinType::Float: 2373 Out << 'M'; 2374 break; 2375 case BuiltinType::Double: 2376 Out << 'N'; 2377 break; 2378 // TODO: Determine size and mangle accordingly 2379 case BuiltinType::LongDouble: 2380 Out << 'O'; 2381 break; 2382 case BuiltinType::LongLong: 2383 Out << "_J"; 2384 break; 2385 case BuiltinType::ULongLong: 2386 Out << "_K"; 2387 break; 2388 case BuiltinType::Int128: 2389 Out << "_L"; 2390 break; 2391 case BuiltinType::UInt128: 2392 Out << "_M"; 2393 break; 2394 case BuiltinType::Bool: 2395 Out << "_N"; 2396 break; 2397 case BuiltinType::Char8: 2398 Out << "_Q"; 2399 break; 2400 case BuiltinType::Char16: 2401 Out << "_S"; 2402 break; 2403 case BuiltinType::Char32: 2404 Out << "_U"; 2405 break; 2406 case BuiltinType::WChar_S: 2407 case BuiltinType::WChar_U: 2408 Out << "_W"; 2409 break; 2410 2411 #define BUILTIN_TYPE(Id, SingletonId) 2412 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2413 case BuiltinType::Id: 2414 #include "clang/AST/BuiltinTypes.def" 2415 case BuiltinType::Dependent: 2416 llvm_unreachable("placeholder types shouldn't get to name mangling"); 2417 2418 case BuiltinType::ObjCId: 2419 mangleArtificialTagType(TTK_Struct, "objc_object"); 2420 break; 2421 case BuiltinType::ObjCClass: 2422 mangleArtificialTagType(TTK_Struct, "objc_class"); 2423 break; 2424 case BuiltinType::ObjCSel: 2425 mangleArtificialTagType(TTK_Struct, "objc_selector"); 2426 break; 2427 2428 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2429 case BuiltinType::Id: \ 2430 Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \ 2431 break; 2432 #include "clang/Basic/OpenCLImageTypes.def" 2433 case BuiltinType::OCLSampler: 2434 Out << "PA"; 2435 mangleArtificialTagType(TTK_Struct, "ocl_sampler"); 2436 break; 2437 case BuiltinType::OCLEvent: 2438 Out << "PA"; 2439 mangleArtificialTagType(TTK_Struct, "ocl_event"); 2440 break; 2441 case BuiltinType::OCLClkEvent: 2442 Out << "PA"; 2443 mangleArtificialTagType(TTK_Struct, "ocl_clkevent"); 2444 break; 2445 case BuiltinType::OCLQueue: 2446 Out << "PA"; 2447 mangleArtificialTagType(TTK_Struct, "ocl_queue"); 2448 break; 2449 case BuiltinType::OCLReserveID: 2450 Out << "PA"; 2451 mangleArtificialTagType(TTK_Struct, "ocl_reserveid"); 2452 break; 2453 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2454 case BuiltinType::Id: \ 2455 mangleArtificialTagType(TTK_Struct, "ocl_" #ExtType); \ 2456 break; 2457 #include "clang/Basic/OpenCLExtensionTypes.def" 2458 2459 case BuiltinType::NullPtr: 2460 Out << "$$T"; 2461 break; 2462 2463 case BuiltinType::Float16: 2464 mangleArtificialTagType(TTK_Struct, "_Float16", {"__clang"}); 2465 break; 2466 2467 case BuiltinType::Half: 2468 if (!getASTContext().getLangOpts().HLSL) 2469 mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"}); 2470 else if (getASTContext().getLangOpts().NativeHalfType) 2471 Out << "$f16@"; 2472 else 2473 Out << "$halff@"; 2474 break; 2475 2476 case BuiltinType::BFloat16: 2477 mangleArtificialTagType(TTK_Struct, "__bf16", {"__clang"}); 2478 break; 2479 2480 #define SVE_TYPE(Name, Id, SingletonId) \ 2481 case BuiltinType::Id: 2482 #include "clang/Basic/AArch64SVEACLETypes.def" 2483 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2484 case BuiltinType::Id: 2485 #include "clang/Basic/PPCTypes.def" 2486 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 2487 #include "clang/Basic/RISCVVTypes.def" 2488 case BuiltinType::ShortAccum: 2489 case BuiltinType::Accum: 2490 case BuiltinType::LongAccum: 2491 case BuiltinType::UShortAccum: 2492 case BuiltinType::UAccum: 2493 case BuiltinType::ULongAccum: 2494 case BuiltinType::ShortFract: 2495 case BuiltinType::Fract: 2496 case BuiltinType::LongFract: 2497 case BuiltinType::UShortFract: 2498 case BuiltinType::UFract: 2499 case BuiltinType::ULongFract: 2500 case BuiltinType::SatShortAccum: 2501 case BuiltinType::SatAccum: 2502 case BuiltinType::SatLongAccum: 2503 case BuiltinType::SatUShortAccum: 2504 case BuiltinType::SatUAccum: 2505 case BuiltinType::SatULongAccum: 2506 case BuiltinType::SatShortFract: 2507 case BuiltinType::SatFract: 2508 case BuiltinType::SatLongFract: 2509 case BuiltinType::SatUShortFract: 2510 case BuiltinType::SatUFract: 2511 case BuiltinType::SatULongFract: 2512 case BuiltinType::Ibm128: 2513 case BuiltinType::Float128: { 2514 DiagnosticsEngine &Diags = Context.getDiags(); 2515 unsigned DiagID = Diags.getCustomDiagID( 2516 DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet"); 2517 Diags.Report(Range.getBegin(), DiagID) 2518 << T->getName(Context.getASTContext().getPrintingPolicy()) << Range; 2519 break; 2520 } 2521 } 2522 } 2523 2524 // <type> ::= <function-type> 2525 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers, 2526 SourceRange) { 2527 // Structors only appear in decls, so at this point we know it's not a 2528 // structor type. 2529 // FIXME: This may not be lambda-friendly. 2530 if (T->getMethodQuals() || T->getRefQualifier() != RQ_None) { 2531 Out << "$$A8@@"; 2532 mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true); 2533 } else { 2534 Out << "$$A6"; 2535 mangleFunctionType(T); 2536 } 2537 } 2538 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T, 2539 Qualifiers, SourceRange) { 2540 Out << "$$A6"; 2541 mangleFunctionType(T); 2542 } 2543 2544 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T, 2545 const FunctionDecl *D, 2546 bool ForceThisQuals, 2547 bool MangleExceptionSpec) { 2548 // <function-type> ::= <this-cvr-qualifiers> <calling-convention> 2549 // <return-type> <argument-list> <throw-spec> 2550 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T); 2551 2552 SourceRange Range; 2553 if (D) Range = D->getSourceRange(); 2554 2555 bool IsInLambda = false; 2556 bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false; 2557 CallingConv CC = T->getCallConv(); 2558 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) { 2559 if (MD->getParent()->isLambda()) 2560 IsInLambda = true; 2561 if (MD->isInstance()) 2562 HasThisQuals = true; 2563 if (isa<CXXDestructorDecl>(MD)) { 2564 IsStructor = true; 2565 } else if (isa<CXXConstructorDecl>(MD)) { 2566 IsStructor = true; 2567 IsCtorClosure = (StructorType == Ctor_CopyingClosure || 2568 StructorType == Ctor_DefaultClosure) && 2569 isStructorDecl(MD); 2570 if (IsCtorClosure) 2571 CC = getASTContext().getDefaultCallingConvention( 2572 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 2573 } 2574 } 2575 2576 // If this is a C++ instance method, mangle the CVR qualifiers for the 2577 // this pointer. 2578 if (HasThisQuals) { 2579 Qualifiers Quals = Proto->getMethodQuals(); 2580 manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType()); 2581 mangleRefQualifier(Proto->getRefQualifier()); 2582 mangleQualifiers(Quals, /*IsMember=*/false); 2583 } 2584 2585 mangleCallingConvention(CC); 2586 2587 // <return-type> ::= <type> 2588 // ::= @ # structors (they have no declared return type) 2589 if (IsStructor) { 2590 if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) { 2591 // The scalar deleting destructor takes an extra int argument which is not 2592 // reflected in the AST. 2593 if (StructorType == Dtor_Deleting) { 2594 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z"); 2595 return; 2596 } 2597 // The vbase destructor returns void which is not reflected in the AST. 2598 if (StructorType == Dtor_Complete) { 2599 Out << "XXZ"; 2600 return; 2601 } 2602 } 2603 if (IsCtorClosure) { 2604 // Default constructor closure and copy constructor closure both return 2605 // void. 2606 Out << 'X'; 2607 2608 if (StructorType == Ctor_DefaultClosure) { 2609 // Default constructor closure always has no arguments. 2610 Out << 'X'; 2611 } else if (StructorType == Ctor_CopyingClosure) { 2612 // Copy constructor closure always takes an unqualified reference. 2613 mangleFunctionArgumentType(getASTContext().getLValueReferenceType( 2614 Proto->getParamType(0) 2615 ->getAs<LValueReferenceType>() 2616 ->getPointeeType(), 2617 /*SpelledAsLValue=*/true), 2618 Range); 2619 Out << '@'; 2620 } else { 2621 llvm_unreachable("unexpected constructor closure!"); 2622 } 2623 Out << 'Z'; 2624 return; 2625 } 2626 Out << '@'; 2627 } else if (IsInLambda && D && isa<CXXConversionDecl>(D)) { 2628 // The only lambda conversion operators are to function pointers, which 2629 // can differ by their calling convention and are typically deduced. So 2630 // we make sure that this type gets mangled properly. 2631 mangleType(T->getReturnType(), Range, QMM_Result); 2632 } else { 2633 QualType ResultType = T->getReturnType(); 2634 if (IsInLambda && isa<CXXConversionDecl>(D)) { 2635 // The only lambda conversion operators are to function pointers, which 2636 // can differ by their calling convention and are typically deduced. So 2637 // we make sure that this type gets mangled properly. 2638 mangleType(ResultType, Range, QMM_Result); 2639 } else if (const auto *AT = dyn_cast_or_null<AutoType>( 2640 ResultType->getContainedAutoType())) { 2641 Out << '?'; 2642 mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false); 2643 Out << '?'; 2644 assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType && 2645 "shouldn't need to mangle __auto_type!"); 2646 mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>"); 2647 Out << '@'; 2648 } else if (IsInLambda) { 2649 Out << '@'; 2650 } else { 2651 if (ResultType->isVoidType()) 2652 ResultType = ResultType.getUnqualifiedType(); 2653 mangleType(ResultType, Range, QMM_Result); 2654 } 2655 } 2656 2657 // <argument-list> ::= X # void 2658 // ::= <type>+ @ 2659 // ::= <type>* Z # varargs 2660 if (!Proto) { 2661 // Function types without prototypes can arise when mangling a function type 2662 // within an overloadable function in C. We mangle these as the absence of 2663 // any parameter types (not even an empty parameter list). 2664 Out << '@'; 2665 } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 2666 Out << 'X'; 2667 } else { 2668 // Happens for function pointer type arguments for example. 2669 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 2670 mangleFunctionArgumentType(Proto->getParamType(I), Range); 2671 // Mangle each pass_object_size parameter as if it's a parameter of enum 2672 // type passed directly after the parameter with the pass_object_size 2673 // attribute. The aforementioned enum's name is __pass_object_size, and we 2674 // pretend it resides in a top-level namespace called __clang. 2675 // 2676 // FIXME: Is there a defined extension notation for the MS ABI, or is it 2677 // necessary to just cross our fingers and hope this type+namespace 2678 // combination doesn't conflict with anything? 2679 if (D) 2680 if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) 2681 manglePassObjectSizeArg(P); 2682 } 2683 // <builtin-type> ::= Z # ellipsis 2684 if (Proto->isVariadic()) 2685 Out << 'Z'; 2686 else 2687 Out << '@'; 2688 } 2689 2690 if (MangleExceptionSpec && getASTContext().getLangOpts().CPlusPlus17 && 2691 getASTContext().getLangOpts().isCompatibleWithMSVC( 2692 LangOptions::MSVC2017_5)) 2693 mangleThrowSpecification(Proto); 2694 else 2695 Out << 'Z'; 2696 } 2697 2698 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) { 2699 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this' 2700 // # pointer. in 64-bit mode *all* 2701 // # 'this' pointers are 64-bit. 2702 // ::= <global-function> 2703 // <member-function> ::= A # private: near 2704 // ::= B # private: far 2705 // ::= C # private: static near 2706 // ::= D # private: static far 2707 // ::= E # private: virtual near 2708 // ::= F # private: virtual far 2709 // ::= I # protected: near 2710 // ::= J # protected: far 2711 // ::= K # protected: static near 2712 // ::= L # protected: static far 2713 // ::= M # protected: virtual near 2714 // ::= N # protected: virtual far 2715 // ::= Q # public: near 2716 // ::= R # public: far 2717 // ::= S # public: static near 2718 // ::= T # public: static far 2719 // ::= U # public: virtual near 2720 // ::= V # public: virtual far 2721 // <global-function> ::= Y # global near 2722 // ::= Z # global far 2723 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 2724 bool IsVirtual = MD->isVirtual(); 2725 // When mangling vbase destructor variants, ignore whether or not the 2726 // underlying destructor was defined to be virtual. 2727 if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) && 2728 StructorType == Dtor_Complete) { 2729 IsVirtual = false; 2730 } 2731 switch (MD->getAccess()) { 2732 case AS_none: 2733 llvm_unreachable("Unsupported access specifier"); 2734 case AS_private: 2735 if (MD->isStatic()) 2736 Out << 'C'; 2737 else if (IsVirtual) 2738 Out << 'E'; 2739 else 2740 Out << 'A'; 2741 break; 2742 case AS_protected: 2743 if (MD->isStatic()) 2744 Out << 'K'; 2745 else if (IsVirtual) 2746 Out << 'M'; 2747 else 2748 Out << 'I'; 2749 break; 2750 case AS_public: 2751 if (MD->isStatic()) 2752 Out << 'S'; 2753 else if (IsVirtual) 2754 Out << 'U'; 2755 else 2756 Out << 'Q'; 2757 } 2758 } else { 2759 Out << 'Y'; 2760 } 2761 } 2762 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) { 2763 // <calling-convention> ::= A # __cdecl 2764 // ::= B # __export __cdecl 2765 // ::= C # __pascal 2766 // ::= D # __export __pascal 2767 // ::= E # __thiscall 2768 // ::= F # __export __thiscall 2769 // ::= G # __stdcall 2770 // ::= H # __export __stdcall 2771 // ::= I # __fastcall 2772 // ::= J # __export __fastcall 2773 // ::= Q # __vectorcall 2774 // ::= S # __attribute__((__swiftcall__)) // Clang-only 2775 // ::= T # __attribute__((__swiftasynccall__)) 2776 // // Clang-only 2777 // ::= w # __regcall 2778 // The 'export' calling conventions are from a bygone era 2779 // (*cough*Win16*cough*) when functions were declared for export with 2780 // that keyword. (It didn't actually export them, it just made them so 2781 // that they could be in a DLL and somebody from another module could call 2782 // them.) 2783 2784 switch (CC) { 2785 default: 2786 llvm_unreachable("Unsupported CC for mangling"); 2787 case CC_Win64: 2788 case CC_X86_64SysV: 2789 case CC_C: Out << 'A'; break; 2790 case CC_X86Pascal: Out << 'C'; break; 2791 case CC_X86ThisCall: Out << 'E'; break; 2792 case CC_X86StdCall: Out << 'G'; break; 2793 case CC_X86FastCall: Out << 'I'; break; 2794 case CC_X86VectorCall: Out << 'Q'; break; 2795 case CC_Swift: Out << 'S'; break; 2796 case CC_SwiftAsync: Out << 'W'; break; 2797 case CC_PreserveMost: Out << 'U'; break; 2798 case CC_X86RegCall: Out << 'w'; break; 2799 } 2800 } 2801 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) { 2802 mangleCallingConvention(T->getCallConv()); 2803 } 2804 2805 void MicrosoftCXXNameMangler::mangleThrowSpecification( 2806 const FunctionProtoType *FT) { 2807 // <throw-spec> ::= Z # (default) 2808 // ::= _E # noexcept 2809 if (FT->canThrow()) 2810 Out << 'Z'; 2811 else 2812 Out << "_E"; 2813 } 2814 2815 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T, 2816 Qualifiers, SourceRange Range) { 2817 // Probably should be mangled as a template instantiation; need to see what 2818 // VC does first. 2819 DiagnosticsEngine &Diags = Context.getDiags(); 2820 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2821 "cannot mangle this unresolved dependent type yet"); 2822 Diags.Report(Range.getBegin(), DiagID) 2823 << Range; 2824 } 2825 2826 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type> 2827 // <union-type> ::= T <name> 2828 // <struct-type> ::= U <name> 2829 // <class-type> ::= V <name> 2830 // <enum-type> ::= W4 <name> 2831 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) { 2832 switch (TTK) { 2833 case TTK_Union: 2834 Out << 'T'; 2835 break; 2836 case TTK_Struct: 2837 case TTK_Interface: 2838 Out << 'U'; 2839 break; 2840 case TTK_Class: 2841 Out << 'V'; 2842 break; 2843 case TTK_Enum: 2844 Out << "W4"; 2845 break; 2846 } 2847 } 2848 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers, 2849 SourceRange) { 2850 mangleType(cast<TagType>(T)->getDecl()); 2851 } 2852 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers, 2853 SourceRange) { 2854 mangleType(cast<TagType>(T)->getDecl()); 2855 } 2856 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) { 2857 mangleTagTypeKind(TD->getTagKind()); 2858 mangleName(TD); 2859 } 2860 2861 // If you add a call to this, consider updating isArtificialTagType() too. 2862 void MicrosoftCXXNameMangler::mangleArtificialTagType( 2863 TagTypeKind TK, StringRef UnqualifiedName, 2864 ArrayRef<StringRef> NestedNames) { 2865 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @ 2866 mangleTagTypeKind(TK); 2867 2868 // Always start with the unqualified name. 2869 mangleSourceName(UnqualifiedName); 2870 2871 for (StringRef N : llvm::reverse(NestedNames)) 2872 mangleSourceName(N); 2873 2874 // Terminate the whole name with an '@'. 2875 Out << '@'; 2876 } 2877 2878 // <type> ::= <array-type> 2879 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> 2880 // [Y <dimension-count> <dimension>+] 2881 // <element-type> # as global, E is never required 2882 // It's supposed to be the other way around, but for some strange reason, it 2883 // isn't. Today this behavior is retained for the sole purpose of backwards 2884 // compatibility. 2885 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) { 2886 // This isn't a recursive mangling, so now we have to do it all in this 2887 // one call. 2888 manglePointerCVQualifiers(T->getElementType().getQualifiers()); 2889 mangleType(T->getElementType(), SourceRange()); 2890 } 2891 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers, 2892 SourceRange) { 2893 llvm_unreachable("Should have been special cased"); 2894 } 2895 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers, 2896 SourceRange) { 2897 llvm_unreachable("Should have been special cased"); 2898 } 2899 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T, 2900 Qualifiers, SourceRange) { 2901 llvm_unreachable("Should have been special cased"); 2902 } 2903 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T, 2904 Qualifiers, SourceRange) { 2905 llvm_unreachable("Should have been special cased"); 2906 } 2907 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) { 2908 QualType ElementTy(T, 0); 2909 SmallVector<llvm::APInt, 3> Dimensions; 2910 for (;;) { 2911 if (ElementTy->isConstantArrayType()) { 2912 const ConstantArrayType *CAT = 2913 getASTContext().getAsConstantArrayType(ElementTy); 2914 Dimensions.push_back(CAT->getSize()); 2915 ElementTy = CAT->getElementType(); 2916 } else if (ElementTy->isIncompleteArrayType()) { 2917 const IncompleteArrayType *IAT = 2918 getASTContext().getAsIncompleteArrayType(ElementTy); 2919 Dimensions.push_back(llvm::APInt(32, 0)); 2920 ElementTy = IAT->getElementType(); 2921 } else if (ElementTy->isVariableArrayType()) { 2922 const VariableArrayType *VAT = 2923 getASTContext().getAsVariableArrayType(ElementTy); 2924 Dimensions.push_back(llvm::APInt(32, 0)); 2925 ElementTy = VAT->getElementType(); 2926 } else if (ElementTy->isDependentSizedArrayType()) { 2927 // The dependent expression has to be folded into a constant (TODO). 2928 const DependentSizedArrayType *DSAT = 2929 getASTContext().getAsDependentSizedArrayType(ElementTy); 2930 DiagnosticsEngine &Diags = Context.getDiags(); 2931 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2932 "cannot mangle this dependent-length array yet"); 2933 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID) 2934 << DSAT->getBracketsRange(); 2935 return; 2936 } else { 2937 break; 2938 } 2939 } 2940 Out << 'Y'; 2941 // <dimension-count> ::= <number> # number of extra dimensions 2942 mangleNumber(Dimensions.size()); 2943 for (const llvm::APInt &Dimension : Dimensions) 2944 mangleNumber(Dimension.getLimitedValue()); 2945 mangleType(ElementTy, SourceRange(), QMM_Escape); 2946 } 2947 2948 // <type> ::= <pointer-to-member-type> 2949 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> 2950 // <class name> <type> 2951 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, 2952 Qualifiers Quals, SourceRange Range) { 2953 QualType PointeeType = T->getPointeeType(); 2954 manglePointerCVQualifiers(Quals); 2955 manglePointerExtQualifiers(Quals, PointeeType); 2956 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) { 2957 Out << '8'; 2958 mangleName(T->getClass()->castAs<RecordType>()->getDecl()); 2959 mangleFunctionType(FPT, nullptr, true); 2960 } else { 2961 mangleQualifiers(PointeeType.getQualifiers(), true); 2962 mangleName(T->getClass()->castAs<RecordType>()->getDecl()); 2963 mangleType(PointeeType, Range, QMM_Drop); 2964 } 2965 } 2966 2967 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T, 2968 Qualifiers, SourceRange Range) { 2969 DiagnosticsEngine &Diags = Context.getDiags(); 2970 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2971 "cannot mangle this template type parameter type yet"); 2972 Diags.Report(Range.getBegin(), DiagID) 2973 << Range; 2974 } 2975 2976 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T, 2977 Qualifiers, SourceRange Range) { 2978 DiagnosticsEngine &Diags = Context.getDiags(); 2979 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2980 "cannot mangle this substituted parameter pack yet"); 2981 Diags.Report(Range.getBegin(), DiagID) 2982 << Range; 2983 } 2984 2985 // <type> ::= <pointer-type> 2986 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type> 2987 // # the E is required for 64-bit non-static pointers 2988 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals, 2989 SourceRange Range) { 2990 QualType PointeeType = T->getPointeeType(); 2991 manglePointerCVQualifiers(Quals); 2992 manglePointerExtQualifiers(Quals, PointeeType); 2993 2994 // For pointer size address spaces, go down the same type mangling path as 2995 // non address space types. 2996 LangAS AddrSpace = PointeeType.getQualifiers().getAddressSpace(); 2997 if (isPtrSizeAddressSpace(AddrSpace) || AddrSpace == LangAS::Default) 2998 mangleType(PointeeType, Range); 2999 else 3000 mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range); 3001 } 3002 3003 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T, 3004 Qualifiers Quals, SourceRange Range) { 3005 QualType PointeeType = T->getPointeeType(); 3006 switch (Quals.getObjCLifetime()) { 3007 case Qualifiers::OCL_None: 3008 case Qualifiers::OCL_ExplicitNone: 3009 break; 3010 case Qualifiers::OCL_Autoreleasing: 3011 case Qualifiers::OCL_Strong: 3012 case Qualifiers::OCL_Weak: 3013 return mangleObjCLifetime(PointeeType, Quals, Range); 3014 } 3015 manglePointerCVQualifiers(Quals); 3016 manglePointerExtQualifiers(Quals, PointeeType); 3017 mangleType(PointeeType, Range); 3018 } 3019 3020 // <type> ::= <reference-type> 3021 // <reference-type> ::= A E? <cvr-qualifiers> <type> 3022 // # the E is required for 64-bit non-static lvalue references 3023 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T, 3024 Qualifiers Quals, SourceRange Range) { 3025 QualType PointeeType = T->getPointeeType(); 3026 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!"); 3027 Out << 'A'; 3028 manglePointerExtQualifiers(Quals, PointeeType); 3029 mangleType(PointeeType, Range); 3030 } 3031 3032 // <type> ::= <r-value-reference-type> 3033 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type> 3034 // # the E is required for 64-bit non-static rvalue references 3035 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T, 3036 Qualifiers Quals, SourceRange Range) { 3037 QualType PointeeType = T->getPointeeType(); 3038 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!"); 3039 Out << "$$Q"; 3040 manglePointerExtQualifiers(Quals, PointeeType); 3041 mangleType(PointeeType, Range); 3042 } 3043 3044 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers, 3045 SourceRange Range) { 3046 QualType ElementType = T->getElementType(); 3047 3048 llvm::SmallString<64> TemplateMangling; 3049 llvm::raw_svector_ostream Stream(TemplateMangling); 3050 MicrosoftCXXNameMangler Extra(Context, Stream); 3051 Stream << "?$"; 3052 Extra.mangleSourceName("_Complex"); 3053 Extra.mangleType(ElementType, Range, QMM_Escape); 3054 3055 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"}); 3056 } 3057 3058 // Returns true for types that mangleArtificialTagType() gets called for with 3059 // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's 3060 // mangling matters. 3061 // (It doesn't matter for Objective-C types and the like that cl.exe doesn't 3062 // support.) 3063 bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const { 3064 const Type *ty = T.getTypePtr(); 3065 switch (ty->getTypeClass()) { 3066 default: 3067 return false; 3068 3069 case Type::Vector: { 3070 // For ABI compatibility only __m64, __m128(id), and __m256(id) matter, 3071 // but since mangleType(VectorType*) always calls mangleArtificialTagType() 3072 // just always return true (the other vector types are clang-only). 3073 return true; 3074 } 3075 } 3076 } 3077 3078 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals, 3079 SourceRange Range) { 3080 QualType EltTy = T->getElementType(); 3081 const BuiltinType *ET = EltTy->getAs<BuiltinType>(); 3082 const BitIntType *BitIntTy = EltTy->getAs<BitIntType>(); 3083 assert((ET || BitIntTy) && 3084 "vectors with non-builtin/_BitInt elements are unsupported"); 3085 uint64_t Width = getASTContext().getTypeSize(T); 3086 // Pattern match exactly the typedefs in our intrinsic headers. Anything that 3087 // doesn't match the Intel types uses a custom mangling below. 3088 size_t OutSizeBefore = Out.tell(); 3089 if (!isa<ExtVectorType>(T)) { 3090 if (getASTContext().getTargetInfo().getTriple().isX86() && ET) { 3091 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) { 3092 mangleArtificialTagType(TTK_Union, "__m64"); 3093 } else if (Width >= 128) { 3094 if (ET->getKind() == BuiltinType::Float) 3095 mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width)); 3096 else if (ET->getKind() == BuiltinType::LongLong) 3097 mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i'); 3098 else if (ET->getKind() == BuiltinType::Double) 3099 mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd'); 3100 } 3101 } 3102 } 3103 3104 bool IsBuiltin = Out.tell() != OutSizeBefore; 3105 if (!IsBuiltin) { 3106 // The MS ABI doesn't have a special mangling for vector types, so we define 3107 // our own mangling to handle uses of __vector_size__ on user-specified 3108 // types, and for extensions like __v4sf. 3109 3110 llvm::SmallString<64> TemplateMangling; 3111 llvm::raw_svector_ostream Stream(TemplateMangling); 3112 MicrosoftCXXNameMangler Extra(Context, Stream); 3113 Stream << "?$"; 3114 Extra.mangleSourceName("__vector"); 3115 Extra.mangleType(QualType(ET ? static_cast<const Type *>(ET) : BitIntTy, 0), 3116 Range, QMM_Escape); 3117 Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements())); 3118 3119 mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"}); 3120 } 3121 } 3122 3123 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T, 3124 Qualifiers Quals, SourceRange Range) { 3125 mangleType(static_cast<const VectorType *>(T), Quals, Range); 3126 } 3127 3128 void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T, 3129 Qualifiers, SourceRange Range) { 3130 DiagnosticsEngine &Diags = Context.getDiags(); 3131 unsigned DiagID = Diags.getCustomDiagID( 3132 DiagnosticsEngine::Error, 3133 "cannot mangle this dependent-sized vector type yet"); 3134 Diags.Report(Range.getBegin(), DiagID) << Range; 3135 } 3136 3137 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T, 3138 Qualifiers, SourceRange Range) { 3139 DiagnosticsEngine &Diags = Context.getDiags(); 3140 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3141 "cannot mangle this dependent-sized extended vector type yet"); 3142 Diags.Report(Range.getBegin(), DiagID) 3143 << Range; 3144 } 3145 3146 void MicrosoftCXXNameMangler::mangleType(const ConstantMatrixType *T, 3147 Qualifiers quals, SourceRange Range) { 3148 DiagnosticsEngine &Diags = Context.getDiags(); 3149 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3150 "Cannot mangle this matrix type yet"); 3151 Diags.Report(Range.getBegin(), DiagID) << Range; 3152 } 3153 3154 void MicrosoftCXXNameMangler::mangleType(const DependentSizedMatrixType *T, 3155 Qualifiers quals, SourceRange Range) { 3156 DiagnosticsEngine &Diags = Context.getDiags(); 3157 unsigned DiagID = Diags.getCustomDiagID( 3158 DiagnosticsEngine::Error, 3159 "Cannot mangle this dependent-sized matrix type yet"); 3160 Diags.Report(Range.getBegin(), DiagID) << Range; 3161 } 3162 3163 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T, 3164 Qualifiers, SourceRange Range) { 3165 DiagnosticsEngine &Diags = Context.getDiags(); 3166 unsigned DiagID = Diags.getCustomDiagID( 3167 DiagnosticsEngine::Error, 3168 "cannot mangle this dependent address space type yet"); 3169 Diags.Report(Range.getBegin(), DiagID) << Range; 3170 } 3171 3172 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers, 3173 SourceRange) { 3174 // ObjC interfaces have structs underlying them. 3175 mangleTagTypeKind(TTK_Struct); 3176 mangleName(T->getDecl()); 3177 } 3178 3179 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, 3180 Qualifiers Quals, SourceRange Range) { 3181 if (T->isKindOfType()) 3182 return mangleObjCKindOfType(T, Quals, Range); 3183 3184 if (T->qual_empty() && !T->isSpecialized()) 3185 return mangleType(T->getBaseType(), Range, QMM_Drop); 3186 3187 ArgBackRefMap OuterFunArgsContext; 3188 ArgBackRefMap OuterTemplateArgsContext; 3189 BackRefVec OuterTemplateContext; 3190 3191 FunArgBackReferences.swap(OuterFunArgsContext); 3192 TemplateArgBackReferences.swap(OuterTemplateArgsContext); 3193 NameBackReferences.swap(OuterTemplateContext); 3194 3195 mangleTagTypeKind(TTK_Struct); 3196 3197 Out << "?$"; 3198 if (T->isObjCId()) 3199 mangleSourceName("objc_object"); 3200 else if (T->isObjCClass()) 3201 mangleSourceName("objc_class"); 3202 else 3203 mangleSourceName(T->getInterface()->getName()); 3204 3205 for (const auto &Q : T->quals()) 3206 mangleObjCProtocol(Q); 3207 3208 if (T->isSpecialized()) 3209 for (const auto &TA : T->getTypeArgs()) 3210 mangleType(TA, Range, QMM_Drop); 3211 3212 Out << '@'; 3213 3214 Out << '@'; 3215 3216 FunArgBackReferences.swap(OuterFunArgsContext); 3217 TemplateArgBackReferences.swap(OuterTemplateArgsContext); 3218 NameBackReferences.swap(OuterTemplateContext); 3219 } 3220 3221 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T, 3222 Qualifiers Quals, SourceRange Range) { 3223 QualType PointeeType = T->getPointeeType(); 3224 manglePointerCVQualifiers(Quals); 3225 manglePointerExtQualifiers(Quals, PointeeType); 3226 3227 Out << "_E"; 3228 3229 mangleFunctionType(PointeeType->castAs<FunctionProtoType>()); 3230 } 3231 3232 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *, 3233 Qualifiers, SourceRange) { 3234 llvm_unreachable("Cannot mangle injected class name type."); 3235 } 3236 3237 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T, 3238 Qualifiers, SourceRange Range) { 3239 DiagnosticsEngine &Diags = Context.getDiags(); 3240 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3241 "cannot mangle this template specialization type yet"); 3242 Diags.Report(Range.getBegin(), DiagID) 3243 << Range; 3244 } 3245 3246 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers, 3247 SourceRange Range) { 3248 DiagnosticsEngine &Diags = Context.getDiags(); 3249 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3250 "cannot mangle this dependent name type yet"); 3251 Diags.Report(Range.getBegin(), DiagID) 3252 << Range; 3253 } 3254 3255 void MicrosoftCXXNameMangler::mangleType( 3256 const DependentTemplateSpecializationType *T, Qualifiers, 3257 SourceRange Range) { 3258 DiagnosticsEngine &Diags = Context.getDiags(); 3259 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3260 "cannot mangle this dependent template specialization type yet"); 3261 Diags.Report(Range.getBegin(), DiagID) 3262 << Range; 3263 } 3264 3265 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers, 3266 SourceRange Range) { 3267 DiagnosticsEngine &Diags = Context.getDiags(); 3268 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3269 "cannot mangle this pack expansion yet"); 3270 Diags.Report(Range.getBegin(), DiagID) 3271 << Range; 3272 } 3273 3274 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers, 3275 SourceRange Range) { 3276 DiagnosticsEngine &Diags = Context.getDiags(); 3277 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3278 "cannot mangle this typeof(type) yet"); 3279 Diags.Report(Range.getBegin(), DiagID) 3280 << Range; 3281 } 3282 3283 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers, 3284 SourceRange Range) { 3285 DiagnosticsEngine &Diags = Context.getDiags(); 3286 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3287 "cannot mangle this typeof(expression) yet"); 3288 Diags.Report(Range.getBegin(), DiagID) 3289 << Range; 3290 } 3291 3292 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers, 3293 SourceRange Range) { 3294 DiagnosticsEngine &Diags = Context.getDiags(); 3295 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3296 "cannot mangle this decltype() yet"); 3297 Diags.Report(Range.getBegin(), DiagID) 3298 << Range; 3299 } 3300 3301 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T, 3302 Qualifiers, SourceRange Range) { 3303 DiagnosticsEngine &Diags = Context.getDiags(); 3304 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3305 "cannot mangle this unary transform type yet"); 3306 Diags.Report(Range.getBegin(), DiagID) 3307 << Range; 3308 } 3309 3310 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers, 3311 SourceRange Range) { 3312 assert(T->getDeducedType().isNull() && "expecting a dependent type!"); 3313 3314 DiagnosticsEngine &Diags = Context.getDiags(); 3315 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3316 "cannot mangle this 'auto' type yet"); 3317 Diags.Report(Range.getBegin(), DiagID) 3318 << Range; 3319 } 3320 3321 void MicrosoftCXXNameMangler::mangleType( 3322 const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) { 3323 assert(T->getDeducedType().isNull() && "expecting a dependent type!"); 3324 3325 DiagnosticsEngine &Diags = Context.getDiags(); 3326 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3327 "cannot mangle this deduced class template specialization type yet"); 3328 Diags.Report(Range.getBegin(), DiagID) 3329 << Range; 3330 } 3331 3332 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers, 3333 SourceRange Range) { 3334 QualType ValueType = T->getValueType(); 3335 3336 llvm::SmallString<64> TemplateMangling; 3337 llvm::raw_svector_ostream Stream(TemplateMangling); 3338 MicrosoftCXXNameMangler Extra(Context, Stream); 3339 Stream << "?$"; 3340 Extra.mangleSourceName("_Atomic"); 3341 Extra.mangleType(ValueType, Range, QMM_Escape); 3342 3343 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"}); 3344 } 3345 3346 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers, 3347 SourceRange Range) { 3348 QualType ElementType = T->getElementType(); 3349 3350 llvm::SmallString<64> TemplateMangling; 3351 llvm::raw_svector_ostream Stream(TemplateMangling); 3352 MicrosoftCXXNameMangler Extra(Context, Stream); 3353 Stream << "?$"; 3354 Extra.mangleSourceName("ocl_pipe"); 3355 Extra.mangleType(ElementType, Range, QMM_Escape); 3356 Extra.mangleIntegerLiteral(llvm::APSInt::get(T->isReadOnly())); 3357 3358 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"}); 3359 } 3360 3361 void MicrosoftMangleContextImpl::mangleCXXName(GlobalDecl GD, 3362 raw_ostream &Out) { 3363 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 3364 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 3365 getASTContext().getSourceManager(), 3366 "Mangling declaration"); 3367 3368 msvc_hashing_ostream MHO(Out); 3369 3370 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) { 3371 auto Type = GD.getCtorType(); 3372 MicrosoftCXXNameMangler mangler(*this, MHO, CD, Type); 3373 return mangler.mangle(GD); 3374 } 3375 3376 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) { 3377 auto Type = GD.getDtorType(); 3378 MicrosoftCXXNameMangler mangler(*this, MHO, DD, Type); 3379 return mangler.mangle(GD); 3380 } 3381 3382 MicrosoftCXXNameMangler Mangler(*this, MHO); 3383 return Mangler.mangle(GD); 3384 } 3385 3386 void MicrosoftCXXNameMangler::mangleType(const BitIntType *T, Qualifiers, 3387 SourceRange Range) { 3388 llvm::SmallString<64> TemplateMangling; 3389 llvm::raw_svector_ostream Stream(TemplateMangling); 3390 MicrosoftCXXNameMangler Extra(Context, Stream); 3391 Stream << "?$"; 3392 if (T->isUnsigned()) 3393 Extra.mangleSourceName("_UBitInt"); 3394 else 3395 Extra.mangleSourceName("_BitInt"); 3396 Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumBits())); 3397 3398 mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"}); 3399 } 3400 3401 void MicrosoftCXXNameMangler::mangleType(const DependentBitIntType *T, 3402 Qualifiers, SourceRange Range) { 3403 DiagnosticsEngine &Diags = Context.getDiags(); 3404 unsigned DiagID = Diags.getCustomDiagID( 3405 DiagnosticsEngine::Error, "cannot mangle this DependentBitInt type yet"); 3406 Diags.Report(Range.getBegin(), DiagID) << Range; 3407 } 3408 3409 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> | 3410 // <virtual-adjustment> 3411 // <no-adjustment> ::= A # private near 3412 // ::= B # private far 3413 // ::= I # protected near 3414 // ::= J # protected far 3415 // ::= Q # public near 3416 // ::= R # public far 3417 // <static-adjustment> ::= G <static-offset> # private near 3418 // ::= H <static-offset> # private far 3419 // ::= O <static-offset> # protected near 3420 // ::= P <static-offset> # protected far 3421 // ::= W <static-offset> # public near 3422 // ::= X <static-offset> # public far 3423 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near 3424 // ::= $1 <virtual-shift> <static-offset> # private far 3425 // ::= $2 <virtual-shift> <static-offset> # protected near 3426 // ::= $3 <virtual-shift> <static-offset> # protected far 3427 // ::= $4 <virtual-shift> <static-offset> # public near 3428 // ::= $5 <virtual-shift> <static-offset> # public far 3429 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift> 3430 // <vtordisp-shift> ::= <offset-to-vtordisp> 3431 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset> 3432 // <offset-to-vtordisp> 3433 static void mangleThunkThisAdjustment(AccessSpecifier AS, 3434 const ThisAdjustment &Adjustment, 3435 MicrosoftCXXNameMangler &Mangler, 3436 raw_ostream &Out) { 3437 if (!Adjustment.Virtual.isEmpty()) { 3438 Out << '$'; 3439 char AccessSpec; 3440 switch (AS) { 3441 case AS_none: 3442 llvm_unreachable("Unsupported access specifier"); 3443 case AS_private: 3444 AccessSpec = '0'; 3445 break; 3446 case AS_protected: 3447 AccessSpec = '2'; 3448 break; 3449 case AS_public: 3450 AccessSpec = '4'; 3451 } 3452 if (Adjustment.Virtual.Microsoft.VBPtrOffset) { 3453 Out << 'R' << AccessSpec; 3454 Mangler.mangleNumber( 3455 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset)); 3456 Mangler.mangleNumber( 3457 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset)); 3458 Mangler.mangleNumber( 3459 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset)); 3460 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual)); 3461 } else { 3462 Out << AccessSpec; 3463 Mangler.mangleNumber( 3464 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset)); 3465 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual)); 3466 } 3467 } else if (Adjustment.NonVirtual != 0) { 3468 switch (AS) { 3469 case AS_none: 3470 llvm_unreachable("Unsupported access specifier"); 3471 case AS_private: 3472 Out << 'G'; 3473 break; 3474 case AS_protected: 3475 Out << 'O'; 3476 break; 3477 case AS_public: 3478 Out << 'W'; 3479 } 3480 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual)); 3481 } else { 3482 switch (AS) { 3483 case AS_none: 3484 llvm_unreachable("Unsupported access specifier"); 3485 case AS_private: 3486 Out << 'A'; 3487 break; 3488 case AS_protected: 3489 Out << 'I'; 3490 break; 3491 case AS_public: 3492 Out << 'Q'; 3493 } 3494 } 3495 } 3496 3497 void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk( 3498 const CXXMethodDecl *MD, const MethodVFTableLocation &ML, 3499 raw_ostream &Out) { 3500 msvc_hashing_ostream MHO(Out); 3501 MicrosoftCXXNameMangler Mangler(*this, MHO); 3502 Mangler.getStream() << '?'; 3503 Mangler.mangleVirtualMemPtrThunk(MD, ML); 3504 } 3505 3506 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 3507 const ThunkInfo &Thunk, 3508 raw_ostream &Out) { 3509 msvc_hashing_ostream MHO(Out); 3510 MicrosoftCXXNameMangler Mangler(*this, MHO); 3511 Mangler.getStream() << '?'; 3512 Mangler.mangleName(MD); 3513 3514 // Usually the thunk uses the access specifier of the new method, but if this 3515 // is a covariant return thunk, then MSVC always uses the public access 3516 // specifier, and we do the same. 3517 AccessSpecifier AS = Thunk.Return.isEmpty() ? MD->getAccess() : AS_public; 3518 mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO); 3519 3520 if (!Thunk.Return.isEmpty()) 3521 assert(Thunk.Method != nullptr && 3522 "Thunk info should hold the overridee decl"); 3523 3524 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD; 3525 Mangler.mangleFunctionType( 3526 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD); 3527 } 3528 3529 void MicrosoftMangleContextImpl::mangleCXXDtorThunk( 3530 const CXXDestructorDecl *DD, CXXDtorType Type, 3531 const ThisAdjustment &Adjustment, raw_ostream &Out) { 3532 // FIXME: Actually, the dtor thunk should be emitted for vector deleting 3533 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor 3534 // mangling manually until we support both deleting dtor types. 3535 assert(Type == Dtor_Deleting); 3536 msvc_hashing_ostream MHO(Out); 3537 MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type); 3538 Mangler.getStream() << "??_E"; 3539 Mangler.mangleName(DD->getParent()); 3540 mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO); 3541 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD); 3542 } 3543 3544 void MicrosoftMangleContextImpl::mangleCXXVFTable( 3545 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath, 3546 raw_ostream &Out) { 3547 // <mangled-name> ::= ?_7 <class-name> <storage-class> 3548 // <cvr-qualifiers> [<name>] @ 3549 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class> 3550 // is always '6' for vftables. 3551 msvc_hashing_ostream MHO(Out); 3552 MicrosoftCXXNameMangler Mangler(*this, MHO); 3553 if (Derived->hasAttr<DLLImportAttr>()) 3554 Mangler.getStream() << "??_S"; 3555 else 3556 Mangler.getStream() << "??_7"; 3557 Mangler.mangleName(Derived); 3558 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const. 3559 for (const CXXRecordDecl *RD : BasePath) 3560 Mangler.mangleName(RD); 3561 Mangler.getStream() << '@'; 3562 } 3563 3564 void MicrosoftMangleContextImpl::mangleCXXVBTable( 3565 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath, 3566 raw_ostream &Out) { 3567 // <mangled-name> ::= ?_8 <class-name> <storage-class> 3568 // <cvr-qualifiers> [<name>] @ 3569 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class> 3570 // is always '7' for vbtables. 3571 msvc_hashing_ostream MHO(Out); 3572 MicrosoftCXXNameMangler Mangler(*this, MHO); 3573 Mangler.getStream() << "??_8"; 3574 Mangler.mangleName(Derived); 3575 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const. 3576 for (const CXXRecordDecl *RD : BasePath) 3577 Mangler.mangleName(RD); 3578 Mangler.getStream() << '@'; 3579 } 3580 3581 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) { 3582 msvc_hashing_ostream MHO(Out); 3583 MicrosoftCXXNameMangler Mangler(*this, MHO); 3584 Mangler.getStream() << "??_R0"; 3585 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result); 3586 Mangler.getStream() << "@8"; 3587 } 3588 3589 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T, 3590 raw_ostream &Out) { 3591 MicrosoftCXXNameMangler Mangler(*this, Out); 3592 Mangler.getStream() << '.'; 3593 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result); 3594 } 3595 3596 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap( 3597 const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) { 3598 msvc_hashing_ostream MHO(Out); 3599 MicrosoftCXXNameMangler Mangler(*this, MHO); 3600 Mangler.getStream() << "??_K"; 3601 Mangler.mangleName(SrcRD); 3602 Mangler.getStream() << "$C"; 3603 Mangler.mangleName(DstRD); 3604 } 3605 3606 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst, 3607 bool IsVolatile, 3608 bool IsUnaligned, 3609 uint32_t NumEntries, 3610 raw_ostream &Out) { 3611 msvc_hashing_ostream MHO(Out); 3612 MicrosoftCXXNameMangler Mangler(*this, MHO); 3613 Mangler.getStream() << "_TI"; 3614 if (IsConst) 3615 Mangler.getStream() << 'C'; 3616 if (IsVolatile) 3617 Mangler.getStream() << 'V'; 3618 if (IsUnaligned) 3619 Mangler.getStream() << 'U'; 3620 Mangler.getStream() << NumEntries; 3621 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result); 3622 } 3623 3624 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray( 3625 QualType T, uint32_t NumEntries, raw_ostream &Out) { 3626 msvc_hashing_ostream MHO(Out); 3627 MicrosoftCXXNameMangler Mangler(*this, MHO); 3628 Mangler.getStream() << "_CTA"; 3629 Mangler.getStream() << NumEntries; 3630 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result); 3631 } 3632 3633 void MicrosoftMangleContextImpl::mangleCXXCatchableType( 3634 QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size, 3635 uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex, 3636 raw_ostream &Out) { 3637 MicrosoftCXXNameMangler Mangler(*this, Out); 3638 Mangler.getStream() << "_CT"; 3639 3640 llvm::SmallString<64> RTTIMangling; 3641 { 3642 llvm::raw_svector_ostream Stream(RTTIMangling); 3643 msvc_hashing_ostream MHO(Stream); 3644 mangleCXXRTTI(T, MHO); 3645 } 3646 Mangler.getStream() << RTTIMangling; 3647 3648 // VS2015 and VS2017.1 omit the copy-constructor in the mangled name but 3649 // both older and newer versions include it. 3650 // FIXME: It is known that the Ctor is present in 2013, and in 2017.7 3651 // (_MSC_VER 1914) and newer, and that it's omitted in 2015 and 2017.4 3652 // (_MSC_VER 1911), but it's unknown when exactly it reappeared (1914? 3653 // Or 1912, 1913 already?). 3654 bool OmitCopyCtor = getASTContext().getLangOpts().isCompatibleWithMSVC( 3655 LangOptions::MSVC2015) && 3656 !getASTContext().getLangOpts().isCompatibleWithMSVC( 3657 LangOptions::MSVC2017_7); 3658 llvm::SmallString<64> CopyCtorMangling; 3659 if (!OmitCopyCtor && CD) { 3660 llvm::raw_svector_ostream Stream(CopyCtorMangling); 3661 msvc_hashing_ostream MHO(Stream); 3662 mangleCXXName(GlobalDecl(CD, CT), MHO); 3663 } 3664 Mangler.getStream() << CopyCtorMangling; 3665 3666 Mangler.getStream() << Size; 3667 if (VBPtrOffset == -1) { 3668 if (NVOffset) { 3669 Mangler.getStream() << NVOffset; 3670 } 3671 } else { 3672 Mangler.getStream() << NVOffset; 3673 Mangler.getStream() << VBPtrOffset; 3674 Mangler.getStream() << VBIndex; 3675 } 3676 } 3677 3678 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor( 3679 const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset, 3680 uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) { 3681 msvc_hashing_ostream MHO(Out); 3682 MicrosoftCXXNameMangler Mangler(*this, MHO); 3683 Mangler.getStream() << "??_R1"; 3684 Mangler.mangleNumber(NVOffset); 3685 Mangler.mangleNumber(VBPtrOffset); 3686 Mangler.mangleNumber(VBTableOffset); 3687 Mangler.mangleNumber(Flags); 3688 Mangler.mangleName(Derived); 3689 Mangler.getStream() << "8"; 3690 } 3691 3692 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray( 3693 const CXXRecordDecl *Derived, raw_ostream &Out) { 3694 msvc_hashing_ostream MHO(Out); 3695 MicrosoftCXXNameMangler Mangler(*this, MHO); 3696 Mangler.getStream() << "??_R2"; 3697 Mangler.mangleName(Derived); 3698 Mangler.getStream() << "8"; 3699 } 3700 3701 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor( 3702 const CXXRecordDecl *Derived, raw_ostream &Out) { 3703 msvc_hashing_ostream MHO(Out); 3704 MicrosoftCXXNameMangler Mangler(*this, MHO); 3705 Mangler.getStream() << "??_R3"; 3706 Mangler.mangleName(Derived); 3707 Mangler.getStream() << "8"; 3708 } 3709 3710 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator( 3711 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath, 3712 raw_ostream &Out) { 3713 // <mangled-name> ::= ?_R4 <class-name> <storage-class> 3714 // <cvr-qualifiers> [<name>] @ 3715 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class> 3716 // is always '6' for vftables. 3717 llvm::SmallString<64> VFTableMangling; 3718 llvm::raw_svector_ostream Stream(VFTableMangling); 3719 mangleCXXVFTable(Derived, BasePath, Stream); 3720 3721 if (VFTableMangling.startswith("??@")) { 3722 assert(VFTableMangling.endswith("@")); 3723 Out << VFTableMangling << "??_R4@"; 3724 return; 3725 } 3726 3727 assert(VFTableMangling.startswith("??_7") || 3728 VFTableMangling.startswith("??_S")); 3729 3730 Out << "??_R4" << VFTableMangling.str().drop_front(4); 3731 } 3732 3733 void MicrosoftMangleContextImpl::mangleSEHFilterExpression( 3734 GlobalDecl EnclosingDecl, raw_ostream &Out) { 3735 msvc_hashing_ostream MHO(Out); 3736 MicrosoftCXXNameMangler Mangler(*this, MHO); 3737 // The function body is in the same comdat as the function with the handler, 3738 // so the numbering here doesn't have to be the same across TUs. 3739 // 3740 // <mangled-name> ::= ?filt$ <filter-number> @0 3741 Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@"; 3742 Mangler.mangleName(EnclosingDecl); 3743 } 3744 3745 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock( 3746 GlobalDecl EnclosingDecl, raw_ostream &Out) { 3747 msvc_hashing_ostream MHO(Out); 3748 MicrosoftCXXNameMangler Mangler(*this, MHO); 3749 // The function body is in the same comdat as the function with the handler, 3750 // so the numbering here doesn't have to be the same across TUs. 3751 // 3752 // <mangled-name> ::= ?fin$ <filter-number> @0 3753 Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@"; 3754 Mangler.mangleName(EnclosingDecl); 3755 } 3756 3757 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) { 3758 // This is just a made up unique string for the purposes of tbaa. undname 3759 // does *not* know how to demangle it. 3760 MicrosoftCXXNameMangler Mangler(*this, Out); 3761 Mangler.getStream() << '?'; 3762 Mangler.mangleType(T, SourceRange()); 3763 } 3764 3765 void MicrosoftMangleContextImpl::mangleReferenceTemporary( 3766 const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) { 3767 msvc_hashing_ostream MHO(Out); 3768 MicrosoftCXXNameMangler Mangler(*this, MHO); 3769 3770 Mangler.getStream() << "?$RT" << ManglingNumber << '@'; 3771 Mangler.mangle(VD, ""); 3772 } 3773 3774 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable( 3775 const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) { 3776 msvc_hashing_ostream MHO(Out); 3777 MicrosoftCXXNameMangler Mangler(*this, MHO); 3778 3779 Mangler.getStream() << "?$TSS" << GuardNum << '@'; 3780 Mangler.mangleNestedName(VD); 3781 Mangler.getStream() << "@4HA"; 3782 } 3783 3784 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD, 3785 raw_ostream &Out) { 3786 // <guard-name> ::= ?_B <postfix> @5 <scope-depth> 3787 // ::= ?__J <postfix> @5 <scope-depth> 3788 // ::= ?$S <guard-num> @ <postfix> @4IA 3789 3790 // The first mangling is what MSVC uses to guard static locals in inline 3791 // functions. It uses a different mangling in external functions to support 3792 // guarding more than 32 variables. MSVC rejects inline functions with more 3793 // than 32 static locals. We don't fully implement the second mangling 3794 // because those guards are not externally visible, and instead use LLVM's 3795 // default renaming when creating a new guard variable. 3796 msvc_hashing_ostream MHO(Out); 3797 MicrosoftCXXNameMangler Mangler(*this, MHO); 3798 3799 bool Visible = VD->isExternallyVisible(); 3800 if (Visible) { 3801 Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B"); 3802 } else { 3803 Mangler.getStream() << "?$S1@"; 3804 } 3805 unsigned ScopeDepth = 0; 3806 if (Visible && !getNextDiscriminator(VD, ScopeDepth)) 3807 // If we do not have a discriminator and are emitting a guard variable for 3808 // use at global scope, then mangling the nested name will not be enough to 3809 // remove ambiguities. 3810 Mangler.mangle(VD, ""); 3811 else 3812 Mangler.mangleNestedName(VD); 3813 Mangler.getStream() << (Visible ? "@5" : "@4IA"); 3814 if (ScopeDepth) 3815 Mangler.mangleNumber(ScopeDepth); 3816 } 3817 3818 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D, 3819 char CharCode, 3820 raw_ostream &Out) { 3821 msvc_hashing_ostream MHO(Out); 3822 MicrosoftCXXNameMangler Mangler(*this, MHO); 3823 Mangler.getStream() << "??__" << CharCode; 3824 if (D->isStaticDataMember()) { 3825 Mangler.getStream() << '?'; 3826 Mangler.mangleName(D); 3827 Mangler.mangleVariableEncoding(D); 3828 Mangler.getStream() << "@@"; 3829 } else { 3830 Mangler.mangleName(D); 3831 } 3832 // This is the function class mangling. These stubs are global, non-variadic, 3833 // cdecl functions that return void and take no args. 3834 Mangler.getStream() << "YAXXZ"; 3835 } 3836 3837 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D, 3838 raw_ostream &Out) { 3839 // <initializer-name> ::= ?__E <name> YAXXZ 3840 mangleInitFiniStub(D, 'E', Out); 3841 } 3842 3843 void 3844 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 3845 raw_ostream &Out) { 3846 // <destructor-name> ::= ?__F <name> YAXXZ 3847 mangleInitFiniStub(D, 'F', Out); 3848 } 3849 3850 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL, 3851 raw_ostream &Out) { 3852 // <char-type> ::= 0 # char, char16_t, char32_t 3853 // # (little endian char data in mangling) 3854 // ::= 1 # wchar_t (big endian char data in mangling) 3855 // 3856 // <literal-length> ::= <non-negative integer> # the length of the literal 3857 // 3858 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including 3859 // # trailing null bytes 3860 // 3861 // <encoded-string> ::= <simple character> # uninteresting character 3862 // ::= '?$' <hex digit> <hex digit> # these two nibbles 3863 // # encode the byte for the 3864 // # character 3865 // ::= '?' [a-z] # \xe1 - \xfa 3866 // ::= '?' [A-Z] # \xc1 - \xda 3867 // ::= '?' [0-9] # [,/\:. \n\t'-] 3868 // 3869 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc> 3870 // <encoded-string> '@' 3871 MicrosoftCXXNameMangler Mangler(*this, Out); 3872 Mangler.getStream() << "??_C@_"; 3873 3874 // The actual string length might be different from that of the string literal 3875 // in cases like: 3876 // char foo[3] = "foobar"; 3877 // char bar[42] = "foobar"; 3878 // Where it is truncated or zero-padded to fit the array. This is the length 3879 // used for mangling, and any trailing null-bytes also need to be mangled. 3880 unsigned StringLength = getASTContext() 3881 .getAsConstantArrayType(SL->getType()) 3882 ->getSize() 3883 .getZExtValue(); 3884 unsigned StringByteLength = StringLength * SL->getCharByteWidth(); 3885 3886 // <char-type>: The "kind" of string literal is encoded into the mangled name. 3887 if (SL->isWide()) 3888 Mangler.getStream() << '1'; 3889 else 3890 Mangler.getStream() << '0'; 3891 3892 // <literal-length>: The next part of the mangled name consists of the length 3893 // of the string in bytes. 3894 Mangler.mangleNumber(StringByteLength); 3895 3896 auto GetLittleEndianByte = [&SL](unsigned Index) { 3897 unsigned CharByteWidth = SL->getCharByteWidth(); 3898 if (Index / CharByteWidth >= SL->getLength()) 3899 return static_cast<char>(0); 3900 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth); 3901 unsigned OffsetInCodeUnit = Index % CharByteWidth; 3902 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff); 3903 }; 3904 3905 auto GetBigEndianByte = [&SL](unsigned Index) { 3906 unsigned CharByteWidth = SL->getCharByteWidth(); 3907 if (Index / CharByteWidth >= SL->getLength()) 3908 return static_cast<char>(0); 3909 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth); 3910 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth); 3911 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff); 3912 }; 3913 3914 // CRC all the bytes of the StringLiteral. 3915 llvm::JamCRC JC; 3916 for (unsigned I = 0, E = StringByteLength; I != E; ++I) 3917 JC.update(GetLittleEndianByte(I)); 3918 3919 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling 3920 // scheme. 3921 Mangler.mangleNumber(JC.getCRC()); 3922 3923 // <encoded-string>: The mangled name also contains the first 32 bytes 3924 // (including null-terminator bytes) of the encoded StringLiteral. 3925 // Each character is encoded by splitting them into bytes and then encoding 3926 // the constituent bytes. 3927 auto MangleByte = [&Mangler](char Byte) { 3928 // There are five different manglings for characters: 3929 // - [a-zA-Z0-9_$]: A one-to-one mapping. 3930 // - ?[a-z]: The range from \xe1 to \xfa. 3931 // - ?[A-Z]: The range from \xc1 to \xda. 3932 // - ?[0-9]: The set of [,/\:. \n\t'-]. 3933 // - ?$XX: A fallback which maps nibbles. 3934 if (isAsciiIdentifierContinue(Byte, /*AllowDollar=*/true)) { 3935 Mangler.getStream() << Byte; 3936 } else if (isLetter(Byte & 0x7f)) { 3937 Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f); 3938 } else { 3939 const char SpecialChars[] = {',', '/', '\\', ':', '.', 3940 ' ', '\n', '\t', '\'', '-'}; 3941 const char *Pos = llvm::find(SpecialChars, Byte); 3942 if (Pos != std::end(SpecialChars)) { 3943 Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars)); 3944 } else { 3945 Mangler.getStream() << "?$"; 3946 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf)); 3947 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf)); 3948 } 3949 } 3950 }; 3951 3952 // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead. 3953 unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U; 3954 unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength); 3955 for (unsigned I = 0; I != NumBytesToMangle; ++I) { 3956 if (SL->isWide()) 3957 MangleByte(GetBigEndianByte(I)); 3958 else 3959 MangleByte(GetLittleEndianByte(I)); 3960 } 3961 3962 Mangler.getStream() << '@'; 3963 } 3964 3965 MicrosoftMangleContext *MicrosoftMangleContext::create(ASTContext &Context, 3966 DiagnosticsEngine &Diags, 3967 bool IsAux) { 3968 return new MicrosoftMangleContextImpl(Context, Diags, IsAux); 3969 } 3970