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