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