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