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