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