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