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