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