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