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