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