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