LCOV - code coverage report
Current view: top level - lib/CodeGen/AsmPrinter - CodeViewDebug.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1241 1276 97.3 %
Date: 2018-10-20 13:21:21 Functions: 81 83 97.6 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
       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 file contains support for writing Microsoft CodeView debug info.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "CodeViewDebug.h"
      15             : #include "DwarfExpression.h"
      16             : #include "llvm/ADT/APSInt.h"
      17             : #include "llvm/ADT/ArrayRef.h"
      18             : #include "llvm/ADT/DenseMap.h"
      19             : #include "llvm/ADT/DenseSet.h"
      20             : #include "llvm/ADT/MapVector.h"
      21             : #include "llvm/ADT/None.h"
      22             : #include "llvm/ADT/Optional.h"
      23             : #include "llvm/ADT/STLExtras.h"
      24             : #include "llvm/ADT/SmallString.h"
      25             : #include "llvm/ADT/SmallVector.h"
      26             : #include "llvm/ADT/StringRef.h"
      27             : #include "llvm/ADT/TinyPtrVector.h"
      28             : #include "llvm/ADT/Triple.h"
      29             : #include "llvm/ADT/Twine.h"
      30             : #include "llvm/BinaryFormat/COFF.h"
      31             : #include "llvm/BinaryFormat/Dwarf.h"
      32             : #include "llvm/CodeGen/AsmPrinter.h"
      33             : #include "llvm/CodeGen/LexicalScopes.h"
      34             : #include "llvm/CodeGen/MachineFrameInfo.h"
      35             : #include "llvm/CodeGen/MachineFunction.h"
      36             : #include "llvm/CodeGen/MachineInstr.h"
      37             : #include "llvm/CodeGen/MachineModuleInfo.h"
      38             : #include "llvm/CodeGen/MachineOperand.h"
      39             : #include "llvm/CodeGen/TargetFrameLowering.h"
      40             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      41             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      42             : #include "llvm/Config/llvm-config.h"
      43             : #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
      44             : #include "llvm/DebugInfo/CodeView/CodeView.h"
      45             : #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
      46             : #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
      47             : #include "llvm/DebugInfo/CodeView/Line.h"
      48             : #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
      49             : #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
      50             : #include "llvm/DebugInfo/CodeView/TypeIndex.h"
      51             : #include "llvm/DebugInfo/CodeView/TypeRecord.h"
      52             : #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
      53             : #include "llvm/IR/Constants.h"
      54             : #include "llvm/IR/DataLayout.h"
      55             : #include "llvm/IR/DebugInfoMetadata.h"
      56             : #include "llvm/IR/DebugLoc.h"
      57             : #include "llvm/IR/Function.h"
      58             : #include "llvm/IR/GlobalValue.h"
      59             : #include "llvm/IR/GlobalVariable.h"
      60             : #include "llvm/IR/Metadata.h"
      61             : #include "llvm/IR/Module.h"
      62             : #include "llvm/MC/MCAsmInfo.h"
      63             : #include "llvm/MC/MCContext.h"
      64             : #include "llvm/MC/MCSectionCOFF.h"
      65             : #include "llvm/MC/MCStreamer.h"
      66             : #include "llvm/MC/MCSymbol.h"
      67             : #include "llvm/Support/BinaryByteStream.h"
      68             : #include "llvm/Support/BinaryStreamReader.h"
      69             : #include "llvm/Support/Casting.h"
      70             : #include "llvm/Support/CommandLine.h"
      71             : #include "llvm/Support/Compiler.h"
      72             : #include "llvm/Support/Endian.h"
      73             : #include "llvm/Support/Error.h"
      74             : #include "llvm/Support/ErrorHandling.h"
      75             : #include "llvm/Support/FormatVariadic.h"
      76             : #include "llvm/Support/Path.h"
      77             : #include "llvm/Support/SMLoc.h"
      78             : #include "llvm/Support/ScopedPrinter.h"
      79             : #include "llvm/Target/TargetLoweringObjectFile.h"
      80             : #include "llvm/Target/TargetMachine.h"
      81             : #include <algorithm>
      82             : #include <cassert>
      83             : #include <cctype>
      84             : #include <cstddef>
      85             : #include <cstdint>
      86             : #include <iterator>
      87             : #include <limits>
      88             : #include <string>
      89             : #include <utility>
      90             : #include <vector>
      91             : 
      92             : using namespace llvm;
      93             : using namespace llvm::codeview;
      94             : 
      95             : static cl::opt<bool> EmitDebugGlobalHashes("emit-codeview-ghash-section",
      96             :                                            cl::ReallyHidden, cl::init(false));
      97             : 
      98         131 : static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
      99         131 :   switch (Type) {
     100             :   case Triple::ArchType::x86:
     101             :     return CPUType::Pentium3;
     102          64 :   case Triple::ArchType::x86_64:
     103          64 :     return CPUType::X64;
     104           1 :   case Triple::ArchType::thumb:
     105           1 :     return CPUType::Thumb;
     106           1 :   case Triple::ArchType::aarch64:
     107           1 :     return CPUType::ARM64;
     108           0 :   default:
     109           0 :     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
     110             :   }
     111             : }
     112             : 
     113         132 : CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
     114         396 :     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
     115             :   // If module doesn't have named metadata anchors or COFF debug section
     116             :   // is not available, skip any debug info related stuff.
     117         264 :   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
     118         131 :       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
     119           1 :     Asm = nullptr;
     120           1 :     return;
     121             :   }
     122             :   // Tell MMI that we have debug info.
     123         131 :   MMI->setDebugInfoAvailability(true);
     124             : 
     125         131 :   TheCPU =
     126         393 :       mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
     127             : }
     128             : 
     129         430 : StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
     130         430 :   std::string &Filepath = FileToFilepathMap[File];
     131         430 :   if (!Filepath.empty())
     132         292 :     return Filepath;
     133             : 
     134         138 :   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
     135             : 
     136             :   // If this is a Unix-style path, just use it as is. Don't try to canonicalize
     137             :   // it textually because one of the path components could be a symlink.
     138             :   if (Dir.startswith("/") || Filename.startswith("/")) {
     139          14 :     if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
     140           5 :       return Filename;
     141           9 :     Filepath = Dir;
     142          18 :     if (Dir.back() != '/')
     143             :       Filepath += '/';
     144             :     Filepath += Filename;
     145           9 :     return Filepath;
     146             :   }
     147             : 
     148             :   // Clang emits directory and relative filename info into the IR, but CodeView
     149             :   // operates on full paths.  We could change Clang to emit full paths too, but
     150             :   // that would increase the IR size and probably not needed for other users.
     151             :   // For now, just concatenate and canonicalize the path here.
     152         124 :   if (Filename.find(':') == 1)
     153           4 :     Filepath = Filename;
     154             :   else
     155         244 :     Filepath = (Dir + "\\" + Filename).str();
     156             : 
     157             :   // Canonicalize the path.  We have to do it textually because we may no longer
     158             :   // have access the file in the filesystem.
     159             :   // First, replace all slashes with backslashes.
     160             :   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
     161             : 
     162             :   // Remove all "\.\" with "\".
     163             :   size_t Cursor = 0;
     164         130 :   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
     165           3 :     Filepath.erase(Cursor, 2);
     166             : 
     167             :   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
     168             :   // path should be well-formatted, e.g. start with a drive letter, etc.
     169             :   Cursor = 0;
     170         134 :   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
     171             :     // Something's wrong if the path starts with "\..\", abort.
     172           5 :     if (Cursor == 0)
     173             :       break;
     174             : 
     175           5 :     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
     176           5 :     if (PrevSlash == std::string::npos)
     177             :       // Something's wrong, abort.
     178             :       break;
     179             : 
     180           5 :     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
     181             :     // The next ".." might be following the one we've just erased.
     182             :     Cursor = PrevSlash;
     183             :   }
     184             : 
     185             :   // Remove all duplicate backslashes.
     186             :   Cursor = 0;
     187         188 :   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
     188          32 :     Filepath.erase(Cursor, 1);
     189             : 
     190         124 :   return Filepath;
     191             : }
     192             : 
     193         320 : unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
     194         320 :   StringRef FullPath = getFullFilepath(F);
     195         320 :   unsigned NextId = FileIdMap.size() + 1;
     196         320 :   auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
     197         320 :   if (Insertion.second) {
     198             :     // We have to compute the full filepath and emit a .cv_file directive.
     199         122 :     ArrayRef<uint8_t> ChecksumAsBytes;
     200             :     FileChecksumKind CSKind = FileChecksumKind::None;
     201         122 :     if (F->getChecksum()) {
     202          63 :       std::string Checksum = fromHex(F->getChecksum()->Value);
     203          63 :       void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
     204          63 :       memcpy(CKMem, Checksum.data(), Checksum.size());
     205          63 :       ChecksumAsBytes = ArrayRef<uint8_t>(
     206             :           reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
     207          63 :       switch (F->getChecksum()->Kind) {
     208          63 :       case DIFile::CSK_MD5:  CSKind = FileChecksumKind::MD5; break;
     209           0 :       case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
     210             :       }
     211             :     }
     212         244 :     bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
     213         122 :                                           static_cast<unsigned>(CSKind));
     214             :     (void)Success;
     215             :     assert(Success && ".cv_file directive failed");
     216             :   }
     217         320 :   return Insertion.first->second;
     218             : }
     219             : 
     220             : CodeViewDebug::InlineSite &
     221         108 : CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
     222             :                              const DISubprogram *Inlinee) {
     223         216 :   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
     224         108 :   InlineSite *Site = &SiteInsertion.first->second;
     225         108 :   if (SiteInsertion.second) {
     226          24 :     unsigned ParentFuncId = CurFn->FuncId;
     227             :     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
     228           6 :       ParentFuncId =
     229           6 :           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
     230             :               .SiteFuncId;
     231             : 
     232          24 :     Site->SiteFuncId = NextFuncId++;
     233          48 :     OS.EmitCVInlineSiteIdDirective(
     234             :         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
     235          24 :         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
     236          24 :     Site->Inlinee = Inlinee;
     237          24 :     InlinedSubprograms.insert(Inlinee);
     238          24 :     getFuncIdForSubprogram(Inlinee);
     239             :   }
     240         108 :   return *Site;
     241             : }
     242             : 
     243         637 : static StringRef getPrettyScopeName(const DIScope *Scope) {
     244         637 :   StringRef ScopeName = Scope->getName();
     245         637 :   if (!ScopeName.empty())
     246         429 :     return ScopeName;
     247             : 
     248         208 :   switch (Scope->getTag()) {
     249             :   case dwarf::DW_TAG_enumeration_type:
     250             :   case dwarf::DW_TAG_class_type:
     251             :   case dwarf::DW_TAG_structure_type:
     252             :   case dwarf::DW_TAG_union_type:
     253          10 :     return "<unnamed-tag>";
     254             :   case dwarf::DW_TAG_namespace:
     255           0 :     return "`anonymous namespace'";
     256             :   }
     257             : 
     258         198 :   return StringRef();
     259             : }
     260             : 
     261         553 : static const DISubprogram *getQualifiedNameComponents(
     262             :     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
     263             :   const DISubprogram *ClosestSubprogram = nullptr;
     264         859 :   while (Scope != nullptr) {
     265         306 :     if (ClosestSubprogram == nullptr)
     266             :       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
     267         306 :     StringRef ScopeName = getPrettyScopeName(Scope);
     268         306 :     if (!ScopeName.empty())
     269         108 :       QualifiedNameComponents.push_back(ScopeName);
     270         573 :     Scope = Scope->getScope().resolve();
     271             :   }
     272         553 :   return ClosestSubprogram;
     273             : }
     274             : 
     275         553 : static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
     276             :                                     StringRef TypeName) {
     277             :   std::string FullyQualifiedName;
     278             :   for (StringRef QualifiedNameComponent :
     279         661 :        llvm::reverse(QualifiedNameComponents)) {
     280         108 :     FullyQualifiedName.append(QualifiedNameComponent);
     281         108 :     FullyQualifiedName.append("::");
     282             :   }
     283         553 :   FullyQualifiedName.append(TypeName);
     284         553 :   return FullyQualifiedName;
     285             : }
     286             : 
     287         444 : static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
     288             :   SmallVector<StringRef, 5> QualifiedNameComponents;
     289         444 :   getQualifiedNameComponents(Scope, QualifiedNameComponents);
     290         444 :   return getQualifiedName(QualifiedNameComponents, Name);
     291             : }
     292             : 
     293             : struct CodeViewDebug::TypeLoweringScope {
     294         848 :   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
     295         208 :   ~TypeLoweringScope() {
     296             :     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
     297             :     // inner TypeLoweringScopes don't attempt to emit deferred types.
     298         104 :     if (CVD.TypeEmissionLevel == 1)
     299         342 :       CVD.emitDeferredCompleteTypes();
     300         738 :     --CVD.TypeEmissionLevel;
     301         104 :   }
     302             :   CodeViewDebug &CVD;
     303             : };
     304             : 
     305         222 : static std::string getFullyQualifiedName(const DIScope *Ty) {
     306         222 :   const DIScope *Scope = Ty->getScope().resolve();
     307         222 :   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
     308             : }
     309             : 
     310         210 : TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
     311             :   // No scope means global scope and that uses the zero index.
     312         210 :   if (!Scope || isa<DIFile>(Scope))
     313         207 :     return TypeIndex();
     314             : 
     315             :   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
     316             : 
     317             :   // Check if we've already translated this scope.
     318           6 :   auto I = TypeIndices.find({Scope, nullptr});
     319           3 :   if (I != TypeIndices.end())
     320           1 :     return I->second;
     321             : 
     322             :   // Build the fully qualified name of the scope.
     323           2 :   std::string ScopeName = getFullyQualifiedName(Scope);
     324           2 :   StringIdRecord SID(TypeIndex(), ScopeName);
     325           4 :   auto TI = TypeTable.writeLeafType(SID);
     326           2 :   return recordTypeIndexForDINode(Scope, TI);
     327             : }
     328             : 
     329         255 : TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
     330             :   assert(SP);
     331             : 
     332             :   // Check if we've already translated this subprogram.
     333         510 :   auto I = TypeIndices.find({SP, nullptr});
     334         255 :   if (I != TypeIndices.end())
     335           2 :     return I->second;
     336             : 
     337             :   // The display name includes function template arguments. Drop them to match
     338             :   // MSVC.
     339         253 :   StringRef DisplayName = SP->getName().split('<').first;
     340             : 
     341             :   const DIScope *Scope = SP->getScope().resolve();
     342             :   TypeIndex TI;
     343          46 :   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
     344             :     // If the scope is a DICompositeType, then this must be a method. Member
     345             :     // function types take some special handling, and require access to the
     346             :     // subprogram.
     347          86 :     TypeIndex ClassType = getTypeIndex(Class);
     348             :     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
     349          42 :                                DisplayName);
     350          84 :     TI = TypeTable.writeLeafType(MFuncId);
     351             :   } else {
     352             :     // Otherwise, this must be a free function.
     353         210 :     TypeIndex ParentScope = getScopeIndex(Scope);
     354         210 :     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
     355         420 :     TI = TypeTable.writeLeafType(FuncId);
     356             :   }
     357             : 
     358         252 :   return recordTypeIndexForDINode(SP, TI);
     359             : }
     360             : 
     361             : static bool isTrivial(const DICompositeType *DCTy) {
     362          98 :   return ((DCTy->getFlags() & DINode::FlagTrivial) == DINode::FlagTrivial);
     363             : }
     364             : 
     365             : static FunctionOptions
     366         253 : getFunctionOptions(const DISubroutineType *Ty,
     367             :                    const DICompositeType *ClassTy = nullptr,
     368             :                    StringRef SPName = StringRef("")) {
     369             :   FunctionOptions FO = FunctionOptions::None;
     370             :   const DIType *ReturnTy = nullptr;
     371         253 :   if (auto TypeArray = Ty->getTypeArray()) {
     372         253 :     if (TypeArray.size())
     373             :       ReturnTy = TypeArray[0].resolve();
     374             :   }
     375             : 
     376             :   if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
     377          13 :     if (!isTrivial(ReturnDCTy))
     378             :       FO |= FunctionOptions::CxxReturnUdt;
     379             :   }
     380             : 
     381             :   // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
     382         253 :   if (ClassTy && !isTrivial(ClassTy) && SPName == ClassTy->getName()) {
     383             :     FO |= FunctionOptions::Constructor;
     384             : 
     385             :   // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
     386             : 
     387             :   }
     388         253 :   return FO;
     389             : }
     390             : 
     391         109 : TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
     392             :                                                const DICompositeType *Class) {
     393             :   // Always use the method declaration as the key for the function type. The
     394             :   // method declaration contains the this adjustment.
     395             :   if (SP->getDeclaration())
     396             :     SP = SP->getDeclaration();
     397             :   assert(!SP->getDeclaration() && "should use declaration as key");
     398             : 
     399             :   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
     400             :   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
     401         218 :   auto I = TypeIndices.find({SP, Class});
     402         109 :   if (I != TypeIndices.end())
     403          24 :     return I->second;
     404             : 
     405             :   // Make sure complete type info for the class is emitted *after* the member
     406             :   // function type, as the complete class type is likely to reference this
     407             :   // member function type.
     408             :   TypeLoweringScope S(*this);
     409         170 :   const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
     410             : 
     411          85 :   FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
     412             :   TypeIndex TI = lowerTypeMemberFunction(
     413          85 :       SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
     414          84 :   return recordTypeIndexForDINode(SP, TI, Class);
     415             : }
     416             : 
     417           0 : TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
     418             :                                                   TypeIndex TI,
     419             :                                                   const DIType *ClassTy) {
     420           0 :   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
     421             :   (void)InsertResult;
     422             :   assert(InsertResult.second && "DINode was already assigned a type index");
     423         338 :   return TI;
     424             : }
     425             : 
     426          61 : unsigned CodeViewDebug::getPointerSizeInBytes() {
     427          61 :   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
     428             : }
     429             : 
     430         312 : void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
     431             :                                         const LexicalScope *LS) {
     432         312 :   if (const DILocation *InlinedAt = LS->getInlinedAt()) {
     433             :     // This variable was inlined. Associate it with the InlineSite.
     434           8 :     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
     435           8 :     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
     436           8 :     Site.InlinedLocals.emplace_back(Var);
     437             :   } else {
     438             :     // This variable goes into the corresponding lexical scope.
     439         304 :     ScopeVariables[LS].emplace_back(Var);
     440             :   }
     441         312 : }
     442             : 
     443          53 : static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
     444             :                                const DILocation *Loc) {
     445             :   auto B = Locs.begin(), E = Locs.end();
     446          53 :   if (std::find(B, E, Loc) == E)
     447          24 :     Locs.push_back(Loc);
     448          53 : }
     449             : 
     450        2035 : void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
     451             :                                         const MachineFunction *MF) {
     452             :   // Skip this instruction if it has the same location as the previous one.
     453        2035 :   if (!DL || DL == PrevInstLoc)
     454        1161 :     return;
     455             : 
     456         874 :   const DIScope *Scope = DL.get()->getScope();
     457         874 :   if (!Scope)
     458             :     return;
     459             : 
     460             :   // Skip this line if it is longer than the maximum we can record.
     461         874 :   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
     462        1748 :   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
     463             :       LI.isNeverStepInto())
     464             :     return;
     465             : 
     466         874 :   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
     467         874 :   if (CI.getStartColumn() != DL.getCol())
     468             :     return;
     469             : 
     470         874 :   if (!CurFn->HaveLineInfo)
     471         233 :     CurFn->HaveLineInfo = true;
     472             :   unsigned FileId = 0;
     473        1515 :   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
     474         624 :     FileId = CurFn->LastFileId;
     475             :   else
     476         250 :     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
     477             :   PrevInstLoc = DL;
     478             : 
     479         874 :   unsigned FuncId = CurFn->FuncId;
     480             :   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
     481          41 :     const DILocation *Loc = DL.get();
     482             : 
     483             :     // If this location was actually inlined from somewhere else, give it the ID
     484             :     // of the inline call site.
     485          41 :     FuncId =
     486          41 :         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
     487             : 
     488             :     // Ensure we have links in the tree of inline call sites.
     489             :     bool FirstLoc = true;
     490             :     while ((SiteLoc = Loc->getInlinedAt())) {
     491             :       InlineSite &Site =
     492          53 :           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
     493          53 :       if (!FirstLoc)
     494          12 :         addLocIfNotPresent(Site.ChildSites, Loc);
     495             :       FirstLoc = false;
     496             :       Loc = SiteLoc;
     497             :     }
     498          41 :     addLocIfNotPresent(CurFn->ChildSites, Loc);
     499             :   }
     500             : 
     501         874 :   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
     502             :                         /*PrologueEnd=*/false, /*IsStmt=*/false,
     503         874 :                         DL->getFilename(), SMLoc());
     504             : }
     505             : 
     506         306 : void CodeViewDebug::emitCodeViewMagicVersion() {
     507         306 :   OS.EmitValueToAlignment(4);
     508         612 :   OS.AddComment("Debug section magic");
     509         306 :   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
     510         306 : }
     511             : 
     512         132 : void CodeViewDebug::endModule() {
     513         132 :   if (!Asm || !MMI->hasDebugInfo())
     514             :     return;
     515             : 
     516             :   assert(Asm != nullptr);
     517             : 
     518             :   // The COFF .debug$S section consists of several subsections, each starting
     519             :   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
     520             :   // of the payload followed by the payload itself.  The subsections are 4-byte
     521             :   // aligned.
     522             : 
     523             :   // Use the generic .debug$S section, and make a subsection for all the inlined
     524             :   // subprograms.
     525         131 :   switchToDebugSectionForSymbol(nullptr);
     526             : 
     527         131 :   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
     528         131 :   emitCompilerInformation();
     529         131 :   endCVSubsection(CompilerInfo);
     530             : 
     531         131 :   emitInlineeLinesSubsection();
     532             : 
     533             :   // Emit per-function debug information.
     534         365 :   for (auto &P : FnDebugInfo)
     535         470 :     if (!P.first->isDeclarationForLinker())
     536         235 :       emitDebugInfoForFunction(P.first, *P.second);
     537             : 
     538             :   // Emit global variable debug information.
     539             :   setCurrentSubprogram(nullptr);
     540         130 :   emitDebugInfoForGlobals();
     541             : 
     542             :   // Emit retained types.
     543         130 :   emitDebugInfoForRetainedTypes();
     544             : 
     545             :   // Switch back to the generic .debug$S section after potentially processing
     546             :   // comdat symbol sections.
     547         130 :   switchToDebugSectionForSymbol(nullptr);
     548             : 
     549             :   // Emit UDT records for any types used by global variables.
     550         130 :   if (!GlobalUDTs.empty()) {
     551          49 :     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
     552          49 :     emitDebugInfoForUDTs(GlobalUDTs);
     553          49 :     endCVSubsection(SymbolsEnd);
     554             :   }
     555             : 
     556             :   // This subsection holds a file index to offset in string table table.
     557         260 :   OS.AddComment("File index to string table offset subsection");
     558         130 :   OS.EmitCVFileChecksumsDirective();
     559             : 
     560             :   // This subsection holds the string table.
     561         260 :   OS.AddComment("String table");
     562         130 :   OS.EmitCVStringTableDirective();
     563             : 
     564             :   // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
     565             :   // subsection in the generic .debug$S section at the end. There is no
     566             :   // particular reason for this ordering other than to match MSVC.
     567         130 :   emitBuildInfo();
     568             : 
     569             :   // Emit type information and hashes last, so that any types we translate while
     570             :   // emitting function info are included.
     571         130 :   emitTypeInformation();
     572             : 
     573         130 :   if (EmitDebugGlobalHashes)
     574           2 :     emitTypeGlobalHashes();
     575             : 
     576         130 :   clear();
     577             : }
     578             : 
     579         862 : static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
     580             :     unsigned MaxFixedRecordLength = 0xF00) {
     581             :   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
     582             :   // after a fixed length portion of the record. The fixed length portion should
     583             :   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
     584             :   // overall record size is less than the maximum allowed.
     585             :   SmallString<32> NullTerminatedString(
     586         862 :       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
     587         862 :   NullTerminatedString.push_back('\0');
     588        1724 :   OS.EmitBytes(NullTerminatedString);
     589         862 : }
     590             : 
     591         130 : void CodeViewDebug::emitTypeInformation() {
     592         130 :   if (TypeTable.empty())
     593           0 :     return;
     594             : 
     595             :   // Start the .debug$T or .debug$P section with 0x4.
     596         130 :   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
     597         130 :   emitCodeViewMagicVersion();
     598             : 
     599             :   SmallString<8> CommentPrefix;
     600         130 :   if (OS.isVerboseAsm()) {
     601          63 :     CommentPrefix += '\t';
     602          63 :     CommentPrefix += Asm->MAI->getCommentString();
     603          63 :     CommentPrefix += ' ';
     604             :   }
     605             : 
     606         260 :   TypeTableCollection Table(TypeTable.records());
     607         130 :   Optional<TypeIndex> B = Table.getFirst();
     608        1851 :   while (B) {
     609             :     // This will fail if the record data is invalid.
     610        1721 :     CVType Record = Table.getType(*B);
     611             : 
     612        1721 :     if (OS.isVerboseAsm()) {
     613             :       // Emit a block comment describing the type record for readability.
     614             :       SmallString<512> CommentBlock;
     615             :       raw_svector_ostream CommentOS(CommentBlock);
     616             :       ScopedPrinter SP(CommentOS);
     617             :       SP.setPrefix(CommentPrefix);
     618             :       TypeDumpVisitor TDV(Table, &SP, false);
     619             : 
     620         562 :       Error E = codeview::visitTypeRecord(Record, *B, TDV);
     621         562 :       if (E) {
     622           0 :         logAllUnhandledErrors(std::move(E), errs(), "error: ");
     623           0 :         llvm_unreachable("produced malformed type record");
     624             :       }
     625             :       // emitRawComment will insert its own tab and comment string before
     626             :       // the first line, so strip off our first one. It also prints its own
     627             :       // newline.
     628         562 :       OS.emitRawComment(
     629        3372 :           CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
     630             :     }
     631        3442 :     OS.EmitBinaryData(Record.str_data());
     632        3442 :     B = Table.getNext(*B);
     633             :   }
     634             : }
     635             : 
     636           2 : void CodeViewDebug::emitTypeGlobalHashes() {
     637           2 :   if (TypeTable.empty())
     638           0 :     return;
     639             : 
     640             :   // Start the .debug$H section with the version and hash algorithm, currently
     641             :   // hardcoded to version 0, SHA1.
     642           2 :   OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
     643             : 
     644           2 :   OS.EmitValueToAlignment(4);
     645           4 :   OS.AddComment("Magic");
     646           2 :   OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
     647           4 :   OS.AddComment("Section Version");
     648           2 :   OS.EmitIntValue(0, 2);
     649           4 :   OS.AddComment("Hash Algorithm");
     650           2 :   OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
     651             : 
     652             :   TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
     653          40 :   for (const auto &GHR : TypeTable.hashes()) {
     654          38 :     if (OS.isVerboseAsm()) {
     655             :       // Emit an EOL-comment describing which TypeIndex this hash corresponds
     656             :       // to, as well as the stringified SHA1 hash.
     657             :       SmallString<32> Comment;
     658             :       raw_svector_ostream CommentOS(Comment);
     659          19 :       CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
     660          38 :       OS.AddComment(Comment);
     661             :       ++TI;
     662             :     }
     663             :     assert(GHR.Hash.size() == 8);
     664             :     StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
     665             :                 GHR.Hash.size());
     666          38 :     OS.EmitBinaryData(S);
     667             :   }
     668             : }
     669             : 
     670             : static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
     671             :   switch (DWLang) {
     672             :   case dwarf::DW_LANG_C:
     673             :   case dwarf::DW_LANG_C89:
     674             :   case dwarf::DW_LANG_C99:
     675             :   case dwarf::DW_LANG_C11:
     676             :   case dwarf::DW_LANG_ObjC:
     677             :     return SourceLanguage::C;
     678             :   case dwarf::DW_LANG_C_plus_plus:
     679             :   case dwarf::DW_LANG_C_plus_plus_03:
     680             :   case dwarf::DW_LANG_C_plus_plus_11:
     681             :   case dwarf::DW_LANG_C_plus_plus_14:
     682             :     return SourceLanguage::Cpp;
     683             :   case dwarf::DW_LANG_Fortran77:
     684             :   case dwarf::DW_LANG_Fortran90:
     685             :   case dwarf::DW_LANG_Fortran03:
     686             :   case dwarf::DW_LANG_Fortran08:
     687             :     return SourceLanguage::Fortran;
     688             :   case dwarf::DW_LANG_Pascal83:
     689             :     return SourceLanguage::Pascal;
     690             :   case dwarf::DW_LANG_Cobol74:
     691             :   case dwarf::DW_LANG_Cobol85:
     692             :     return SourceLanguage::Cobol;
     693             :   case dwarf::DW_LANG_Java:
     694             :     return SourceLanguage::Java;
     695             :   case dwarf::DW_LANG_D:
     696             :     return SourceLanguage::D;
     697             :   default:
     698             :     // There's no CodeView representation for this language, and CV doesn't
     699             :     // have an "unknown" option for the language field, so we'll use MASM,
     700             :     // as it's very low level.
     701             :     return SourceLanguage::Masm;
     702             :   }
     703             : }
     704             : 
     705             : namespace {
     706             : struct Version {
     707             :   int Part[4];
     708             : };
     709             : } // end anonymous namespace
     710             : 
     711             : // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
     712             : // the version number.
     713         131 : static Version parseVersion(StringRef Name) {
     714         131 :   Version V = {{0}};
     715             :   int N = 0;
     716        2517 :   for (const char C : Name) {
     717        2512 :     if (isdigit(C)) {
     718         356 :       V.Part[N] *= 10;
     719         356 :       V.Part[N] += C - '0';
     720        2156 :     } else if (C == '.') {
     721         230 :       ++N;
     722         230 :       if (N >= 4)
     723           0 :         return V;
     724        1926 :     } else if (N > 0)
     725         126 :       return V;
     726             :   }
     727           5 :   return V;
     728             : }
     729             : 
     730         131 : void CodeViewDebug::emitCompilerInformation() {
     731         131 :   MCContext &Context = MMI->getContext();
     732         131 :   MCSymbol *CompilerBegin = Context.createTempSymbol(),
     733         131 :            *CompilerEnd = Context.createTempSymbol();
     734         262 :   OS.AddComment("Record length");
     735         131 :   OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
     736         131 :   OS.EmitLabel(CompilerBegin);
     737         262 :   OS.AddComment("Record kind: S_COMPILE3");
     738         131 :   OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
     739             :   uint32_t Flags = 0;
     740             : 
     741         262 :   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
     742             :   const MDNode *Node = *CUs->operands().begin();
     743             :   const auto *CU = cast<DICompileUnit>(Node);
     744             : 
     745             :   // The low byte of the flags indicates the source language.
     746         131 :   Flags = MapDWLangToCVLang(CU->getSourceLanguage());
     747             :   // TODO:  Figure out which other flags need to be set.
     748             : 
     749         262 :   OS.AddComment("Flags and language");
     750         131 :   OS.EmitIntValue(Flags, 4);
     751             : 
     752         262 :   OS.AddComment("CPUType");
     753         131 :   OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
     754             : 
     755         131 :   StringRef CompilerVersion = CU->getProducer();
     756         131 :   Version FrontVer = parseVersion(CompilerVersion);
     757         262 :   OS.AddComment("Frontend version");
     758         655 :   for (int N = 0; N < 4; ++N)
     759         524 :     OS.EmitIntValue(FrontVer.Part[N], 2);
     760             : 
     761             :   // Some Microsoft tools, like Binscope, expect a backend version number of at
     762             :   // least 8.something, so we'll coerce the LLVM version into a form that
     763             :   // guarantees it'll be big enough without really lying about the version.
     764         131 :   int Major = 1000 * LLVM_VERSION_MAJOR +
     765             :               10 * LLVM_VERSION_MINOR +
     766             :               LLVM_VERSION_PATCH;
     767             :   // Clamp it for builds that use unusually large version numbers.
     768             :   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
     769         131 :   Version BackVer = {{ Major, 0, 0, 0 }};
     770         262 :   OS.AddComment("Backend version");
     771         655 :   for (int N = 0; N < 4; ++N)
     772         524 :     OS.EmitIntValue(BackVer.Part[N], 2);
     773             : 
     774         262 :   OS.AddComment("Null-terminated compiler version string");
     775         131 :   emitNullTerminatedSymbolName(OS, CompilerVersion);
     776             : 
     777         131 :   OS.EmitLabel(CompilerEnd);
     778         131 : }
     779             : 
     780         260 : static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
     781             :                                     StringRef S) {
     782         260 :   StringIdRecord SIR(TypeIndex(0x0), S);
     783         260 :   return TypeTable.writeLeafType(SIR);
     784             : }
     785             : 
     786         130 : void CodeViewDebug::emitBuildInfo() {
     787             :   // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
     788             :   // build info. The known prefix is:
     789             :   // - Absolute path of current directory
     790             :   // - Compiler path
     791             :   // - Main source file path, relative to CWD or absolute
     792             :   // - Type server PDB file
     793             :   // - Canonical compiler command line
     794             :   // If frontend and backend compilation are separated (think llc or LTO), it's
     795             :   // not clear if the compiler path should refer to the executable for the
     796             :   // frontend or the backend. Leave it blank for now.
     797         780 :   TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
     798         260 :   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
     799             :   const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
     800             :   const auto *CU = cast<DICompileUnit>(Node);
     801             :   const DIFile *MainSourceFile = CU->getFile();
     802             :   BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
     803         130 :       getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
     804             :   BuildInfoArgs[BuildInfoRecord::SourceFile] =
     805         130 :       getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
     806             :   // FIXME: Path to compiler and command line. PDB is intentionally blank unless
     807             :   // we implement /Zi type servers.
     808             :   BuildInfoRecord BIR(BuildInfoArgs);
     809         130 :   TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
     810             : 
     811             :   // Make a new .debug$S subsection for the S_BUILDINFO record, which points
     812             :   // from the module symbols into the type stream.
     813         130 :   MCSymbol *BuildInfoEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
     814         260 :   OS.AddComment("Record length");
     815         130 :   OS.EmitIntValue(6, 2);
     816         260 :   OS.AddComment("Record kind: S_BUILDINFO");
     817         130 :   OS.EmitIntValue(unsigned(SymbolKind::S_BUILDINFO), 2);
     818         260 :   OS.AddComment("LF_BUILDINFO index");
     819         260 :   OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
     820         130 :   endCVSubsection(BuildInfoEnd);
     821         130 : }
     822             : 
     823         131 : void CodeViewDebug::emitInlineeLinesSubsection() {
     824         131 :   if (InlinedSubprograms.empty())
     825             :     return;
     826             : 
     827          24 :   OS.AddComment("Inlinee lines subsection");
     828          12 :   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
     829             : 
     830             :   // We emit the checksum info for files.  This is used by debuggers to
     831             :   // determine if a pdb matches the source before loading it.  Visual Studio,
     832             :   // for instance, will display a warning that the breakpoints are not valid if
     833             :   // the pdb does not match the source.
     834          24 :   OS.AddComment("Inlinee lines signature");
     835          12 :   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
     836             : 
     837          34 :   for (const DISubprogram *SP : InlinedSubprograms) {
     838             :     assert(TypeIndices.count({SP, nullptr}));
     839          22 :     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
     840             : 
     841          22 :     OS.AddBlankLine();
     842          22 :     unsigned FileId = maybeRecordFile(SP->getFile());
     843          44 :     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
     844          44 :                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
     845          22 :     OS.AddBlankLine();
     846          44 :     OS.AddComment("Type index of inlined function");
     847          44 :     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
     848          44 :     OS.AddComment("Offset into filechecksum table");
     849          22 :     OS.EmitCVFileChecksumOffsetDirective(FileId);
     850          44 :     OS.AddComment("Starting line number");
     851          22 :     OS.EmitIntValue(SP->getLine(), 4);
     852             :   }
     853             : 
     854          12 :   endCVSubsection(InlineEnd);
     855             : }
     856             : 
     857          24 : void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
     858             :                                         const DILocation *InlinedAt,
     859             :                                         const InlineSite &Site) {
     860          48 :   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
     861          48 :            *InlineEnd = MMI->getContext().createTempSymbol();
     862             : 
     863             :   assert(TypeIndices.count({Site.Inlinee, nullptr}));
     864          48 :   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
     865             : 
     866             :   // SymbolRecord
     867          48 :   OS.AddComment("Record length");
     868          24 :   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
     869          24 :   OS.EmitLabel(InlineBegin);
     870          48 :   OS.AddComment("Record kind: S_INLINESITE");
     871          24 :   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
     872             : 
     873          48 :   OS.AddComment("PtrParent");
     874          24 :   OS.EmitIntValue(0, 4);
     875          48 :   OS.AddComment("PtrEnd");
     876          24 :   OS.EmitIntValue(0, 4);
     877          48 :   OS.AddComment("Inlinee type index");
     878          48 :   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
     879             : 
     880          48 :   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
     881          24 :   unsigned StartLineNum = Site.Inlinee->getLine();
     882             : 
     883          48 :   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
     884          24 :                                     FI.Begin, FI.End);
     885             : 
     886          24 :   OS.EmitLabel(InlineEnd);
     887             : 
     888          24 :   emitLocalVariableList(FI, Site.InlinedLocals);
     889             : 
     890             :   // Recurse on child inlined call sites before closing the scope.
     891          30 :   for (const DILocation *ChildSite : Site.ChildSites) {
     892             :     auto I = FI.InlineSites.find(ChildSite);
     893             :     assert(I != FI.InlineSites.end() &&
     894             :            "child site not in function inline site map");
     895           6 :     emitInlinedCallSite(FI, ChildSite, I->second);
     896             :   }
     897             : 
     898             :   // Close the scope.
     899          48 :   OS.AddComment("Record length");
     900          24 :   OS.EmitIntValue(2, 2);                                  // RecordLength
     901          48 :   OS.AddComment("Record kind: S_INLINESITE_END");
     902          24 :   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
     903          24 : }
     904             : 
     905         630 : void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
     906             :   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
     907             :   // comdat key. A section may be comdat because of -ffunction-sections or
     908             :   // because it is comdat in the IR.
     909             :   MCSectionCOFF *GVSec =
     910         630 :       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
     911         238 :   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
     912             : 
     913         630 :   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
     914         630 :       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
     915         630 :   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
     916             : 
     917         630 :   OS.SwitchSection(DebugSec);
     918             : 
     919             :   // Emit the magic version number if this is the first time we've switched to
     920             :   // this section.
     921         630 :   if (ComdatDebugSections.insert(DebugSec).second)
     922         176 :     emitCodeViewMagicVersion();
     923         630 : }
     924             : 
     925             : // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
     926             : // The only supported thunk ordinal is currently the standard type.
     927           4 : void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
     928             :                                           FunctionInfo &FI,
     929             :                                           const MCSymbol *Fn) {
     930           4 :   std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
     931             :   const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
     932             : 
     933           4 :   OS.AddComment("Symbol subsection for " + Twine(FuncName));
     934           4 :   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
     935             : 
     936             :   // Emit S_THUNK32
     937           8 :   MCSymbol *ThunkRecordBegin = MMI->getContext().createTempSymbol(),
     938           8 :            *ThunkRecordEnd   = MMI->getContext().createTempSymbol();
     939           8 :   OS.AddComment("Record length");
     940           4 :   OS.emitAbsoluteSymbolDiff(ThunkRecordEnd, ThunkRecordBegin, 2);
     941           4 :   OS.EmitLabel(ThunkRecordBegin);
     942           8 :   OS.AddComment("Record kind: S_THUNK32");
     943           4 :   OS.EmitIntValue(unsigned(SymbolKind::S_THUNK32), 2);
     944           8 :   OS.AddComment("PtrParent");
     945           4 :   OS.EmitIntValue(0, 4);
     946           8 :   OS.AddComment("PtrEnd");
     947           4 :   OS.EmitIntValue(0, 4);
     948           8 :   OS.AddComment("PtrNext");
     949           4 :   OS.EmitIntValue(0, 4);
     950           8 :   OS.AddComment("Thunk section relative address");
     951           4 :   OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
     952           8 :   OS.AddComment("Thunk section index");
     953           4 :   OS.EmitCOFFSectionIndex(Fn);
     954           8 :   OS.AddComment("Code size");
     955           4 :   OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
     956           8 :   OS.AddComment("Ordinal");
     957           4 :   OS.EmitIntValue(unsigned(ordinal), 1);
     958           8 :   OS.AddComment("Function name");
     959           4 :   emitNullTerminatedSymbolName(OS, FuncName);
     960             :   // Additional fields specific to the thunk ordinal would go here.
     961           4 :   OS.EmitLabel(ThunkRecordEnd);
     962             : 
     963             :   // Local variables/inlined routines are purposely omitted here.  The point of
     964             :   // marking this as a thunk is so Visual Studio will NOT stop in this routine.
     965             : 
     966             :   // Emit S_PROC_ID_END
     967             :   const unsigned RecordLengthForSymbolEnd = 2;
     968           8 :   OS.AddComment("Record length");
     969           4 :   OS.EmitIntValue(RecordLengthForSymbolEnd, 2);
     970           8 :   OS.AddComment("Record kind: S_PROC_ID_END");
     971           4 :   OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
     972             : 
     973           4 :   endCVSubsection(SymbolsEnd);
     974           4 : }
     975             : 
     976         235 : void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
     977             :                                              FunctionInfo &FI) {
     978             :   // For each function there is a separate subsection which holds the PC to
     979             :   // file:line table.
     980         235 :   const MCSymbol *Fn = Asm->getSymbol(GV);
     981             :   assert(Fn);
     982             : 
     983             :   // Switch to the to a comdat section, if appropriate.
     984         235 :   switchToDebugSectionForSymbol(Fn);
     985             : 
     986             :   std::string FuncName;
     987         235 :   auto *SP = GV->getSubprogram();
     988             :   assert(SP);
     989             :   setCurrentSubprogram(SP);
     990             : 
     991         235 :   if (SP->isThunk()) {
     992           4 :     emitDebugInfoForThunk(GV, FI, Fn);
     993             :     return;
     994             :   }
     995             : 
     996             :   // If we have a display name, build the fully qualified name by walking the
     997             :   // chain of scopes.
     998         231 :   if (!SP->getName().empty())
     999             :     FuncName =
    1000         444 :         getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
    1001             : 
    1002             :   // If our DISubprogram name is empty, use the mangled name.
    1003         231 :   if (FuncName.empty())
    1004          27 :     FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
    1005             : 
    1006             :   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
    1007         693 :   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
    1008         119 :     OS.EmitCVFPOData(Fn);
    1009             : 
    1010             :   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
    1011         231 :   OS.AddComment("Symbol subsection for " + Twine(FuncName));
    1012         231 :   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
    1013             :   {
    1014         462 :     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
    1015         462 :              *ProcRecordEnd = MMI->getContext().createTempSymbol();
    1016         462 :     OS.AddComment("Record length");
    1017         231 :     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
    1018         231 :     OS.EmitLabel(ProcRecordBegin);
    1019             : 
    1020             :     if (GV->hasLocalLinkage()) {
    1021          42 :       OS.AddComment("Record kind: S_LPROC32_ID");
    1022          21 :       OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
    1023             :     } else {
    1024         420 :       OS.AddComment("Record kind: S_GPROC32_ID");
    1025         210 :       OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
    1026             :     }
    1027             : 
    1028             :     // These fields are filled in by tools like CVPACK which run after the fact.
    1029         462 :     OS.AddComment("PtrParent");
    1030         231 :     OS.EmitIntValue(0, 4);
    1031         462 :     OS.AddComment("PtrEnd");
    1032         231 :     OS.EmitIntValue(0, 4);
    1033         462 :     OS.AddComment("PtrNext");
    1034         231 :     OS.EmitIntValue(0, 4);
    1035             :     // This is the important bit that tells the debugger where the function
    1036             :     // code is located and what's its size:
    1037         462 :     OS.AddComment("Code size");
    1038         231 :     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
    1039         462 :     OS.AddComment("Offset after prologue");
    1040         231 :     OS.EmitIntValue(0, 4);
    1041         462 :     OS.AddComment("Offset before epilogue");
    1042         231 :     OS.EmitIntValue(0, 4);
    1043         462 :     OS.AddComment("Function type index");
    1044         231 :     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
    1045         460 :     OS.AddComment("Function section relative address");
    1046         230 :     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
    1047         460 :     OS.AddComment("Function section index");
    1048         230 :     OS.EmitCOFFSectionIndex(Fn);
    1049         460 :     OS.AddComment("Flags");
    1050         230 :     OS.EmitIntValue(0, 1);
    1051             :     // Emit the function display name as a null-terminated string.
    1052         460 :     OS.AddComment("Function name");
    1053             :     // Truncate the name so we won't overflow the record length field.
    1054         230 :     emitNullTerminatedSymbolName(OS, FuncName);
    1055         230 :     OS.EmitLabel(ProcRecordEnd);
    1056             : 
    1057         460 :     MCSymbol *FrameProcBegin = MMI->getContext().createTempSymbol(),
    1058         460 :              *FrameProcEnd = MMI->getContext().createTempSymbol();
    1059         460 :     OS.AddComment("Record length");
    1060         230 :     OS.emitAbsoluteSymbolDiff(FrameProcEnd, FrameProcBegin, 2);
    1061         230 :     OS.EmitLabel(FrameProcBegin);
    1062         460 :     OS.AddComment("Record kind: S_FRAMEPROC");
    1063         230 :     OS.EmitIntValue(unsigned(SymbolKind::S_FRAMEPROC), 2);
    1064             :     // Subtract out the CSR size since MSVC excludes that and we include it.
    1065         460 :     OS.AddComment("FrameSize");
    1066         230 :     OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
    1067         460 :     OS.AddComment("Padding");
    1068         230 :     OS.EmitIntValue(0, 4);
    1069         460 :     OS.AddComment("Offset of padding");
    1070         230 :     OS.EmitIntValue(0, 4);
    1071         460 :     OS.AddComment("Bytes of callee saved registers");
    1072         230 :     OS.EmitIntValue(FI.CSRSize, 4);
    1073         460 :     OS.AddComment("Exception handler offset");
    1074         230 :     OS.EmitIntValue(0, 4);
    1075         460 :     OS.AddComment("Exception handler section");
    1076         230 :     OS.EmitIntValue(0, 2);
    1077         460 :     OS.AddComment("Flags (defines frame register)");
    1078         230 :     OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
    1079         230 :     OS.EmitLabel(FrameProcEnd);
    1080             : 
    1081         230 :     emitLocalVariableList(FI, FI.Locals);
    1082             :     emitLexicalBlockList(FI.ChildBlocks, FI);
    1083             : 
    1084             :     // Emit inlined call site information. Only emit functions inlined directly
    1085             :     // into the parent function. We'll emit the other sites recursively as part
    1086             :     // of their parent inline site.
    1087         248 :     for (const DILocation *InlinedAt : FI.ChildSites) {
    1088             :       auto I = FI.InlineSites.find(InlinedAt);
    1089             :       assert(I != FI.InlineSites.end() &&
    1090             :              "child site not in function inline site map");
    1091          18 :       emitInlinedCallSite(FI, InlinedAt, I->second);
    1092             :     }
    1093             : 
    1094         231 :     for (auto Annot : FI.Annotations) {
    1095             :       MCSymbol *Label = Annot.first;
    1096             :       MDTuple *Strs = cast<MDTuple>(Annot.second);
    1097           2 :       MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
    1098           2 :                *AnnotEnd = MMI->getContext().createTempSymbol();
    1099           2 :       OS.AddComment("Record length");
    1100           1 :       OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
    1101           1 :       OS.EmitLabel(AnnotBegin);
    1102           2 :       OS.AddComment("Record kind: S_ANNOTATION");
    1103           1 :       OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
    1104           1 :       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
    1105             :       // FIXME: Make sure we don't overflow the max record size.
    1106           1 :       OS.EmitCOFFSectionIndex(Label);
    1107           1 :       OS.EmitIntValue(Strs->getNumOperands(), 2);
    1108           3 :       for (Metadata *MD : Strs->operands()) {
    1109             :         // MDStrings are null terminated, so we can do EmitBytes and get the
    1110             :         // nice .asciz directive.
    1111           2 :         StringRef Str = cast<MDString>(MD)->getString();
    1112             :         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
    1113           6 :         OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
    1114             :       }
    1115           1 :       OS.EmitLabel(AnnotEnd);
    1116             :     }
    1117             : 
    1118             :     if (SP != nullptr)
    1119         230 :       emitDebugInfoForUDTs(LocalUDTs);
    1120             : 
    1121             :     // We're done with this function.
    1122         460 :     OS.AddComment("Record length");
    1123         230 :     OS.EmitIntValue(0x0002, 2);
    1124         460 :     OS.AddComment("Record kind: S_PROC_ID_END");
    1125         230 :     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
    1126             :   }
    1127         230 :   endCVSubsection(SymbolsEnd);
    1128             : 
    1129             :   // We have an assembler directive that takes care of the whole line table.
    1130         230 :   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
    1131             : }
    1132             : 
    1133             : CodeViewDebug::LocalVarDefRange
    1134           0 : CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
    1135             :   LocalVarDefRange DR;
    1136         222 :   DR.InMemory = -1;
    1137         222 :   DR.DataOffset = Offset;
    1138             :   assert(DR.DataOffset == Offset && "truncation");
    1139         222 :   DR.IsSubfield = 0;
    1140         222 :   DR.StructOffset = 0;
    1141         222 :   DR.CVRegister = CVRegister;
    1142           0 :   return DR;
    1143             : }
    1144             : 
    1145         235 : void CodeViewDebug::collectVariableInfoFromMFTable(
    1146             :     DenseSet<InlinedEntity> &Processed) {
    1147         235 :   const MachineFunction &MF = *Asm->MF;
    1148         235 :   const TargetSubtargetInfo &TSI = MF.getSubtarget();
    1149         235 :   const TargetFrameLowering *TFI = TSI.getFrameLowering();
    1150         235 :   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
    1151             : 
    1152         459 :   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
    1153         224 :     if (!VI.Var)
    1154           2 :       continue;
    1155             :     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
    1156             :            "Expected inlined-at fields to agree");
    1157             : 
    1158         224 :     Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
    1159         224 :     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
    1160             : 
    1161             :     // If variable scope is not found then skip this variable.
    1162         224 :     if (!Scope)
    1163             :       continue;
    1164             : 
    1165             :     // If the variable has an attached offset expression, extract it.
    1166             :     // FIXME: Try to handle DW_OP_deref as well.
    1167         222 :     int64_t ExprOffset = 0;
    1168         222 :     if (VI.Expr)
    1169         222 :       if (!VI.Expr->extractIfOffset(ExprOffset))
    1170             :         continue;
    1171             : 
    1172             :     // Get the frame register used and the offset.
    1173         222 :     unsigned FrameReg = 0;
    1174         222 :     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
    1175         222 :     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
    1176             : 
    1177             :     // Calculate the label ranges.
    1178             :     LocalVarDefRange DefRange =
    1179         222 :         createDefRangeMem(CVReg, FrameOffset + ExprOffset);
    1180         445 :     for (const InsnRange &Range : Scope->getRanges()) {
    1181         223 :       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
    1182         223 :       const MCSymbol *End = getLabelAfterInsn(Range.second);
    1183         223 :       End = End ? End : Asm->getFunctionEnd();
    1184         223 :       DefRange.Ranges.emplace_back(Begin, End);
    1185             :     }
    1186             : 
    1187             :     LocalVariable Var;
    1188         222 :     Var.DIVar = VI.Var;
    1189         222 :     Var.DefRanges.emplace_back(std::move(DefRange));
    1190         222 :     recordLocalVariable(std::move(Var), Scope);
    1191             :   }
    1192         235 : }
    1193             : 
    1194             : static bool canUseReferenceType(const DbgVariableLocation &Loc) {
    1195           4 :   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
    1196             : }
    1197             : 
    1198             : static bool needsReferenceType(const DbgVariableLocation &Loc) {
    1199         130 :   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
    1200             : }
    1201             : 
    1202          94 : void CodeViewDebug::calculateRanges(
    1203             :     LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
    1204          94 :   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
    1205             : 
    1206             :   // Calculate the definition ranges.
    1207         235 :   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
    1208             :     const InsnRange &Range = *I;
    1209         145 :     const MachineInstr *DVInst = Range.first;
    1210             :     assert(DVInst->isDebugValue() && "Invalid History entry");
    1211             :     // FIXME: Find a way to represent constant variables, since they are
    1212             :     // relatively common.
    1213             :     Optional<DbgVariableLocation> Location =
    1214         145 :         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
    1215         145 :     if (!Location)
    1216             :       continue;
    1217             : 
    1218             :     // CodeView can only express variables in register and variables in memory
    1219             :     // at a constant offset from a register. However, for variables passed
    1220             :     // indirectly by pointer, it is common for that pointer to be spilled to a
    1221             :     // stack location. For the special case of one offseted load followed by a
    1222             :     // zero offset load (a pointer spilled to the stack), we change the type of
    1223             :     // the local variable from a value type to a reference type. This tricks the
    1224             :     // debugger into doing the load for us.
    1225         134 :     if (Var.UseReferenceType) {
    1226             :       // We're using a reference type. Drop the last zero offset load.
    1227             :       if (canUseReferenceType(*Location))
    1228             :         Location->LoadChain.pop_back();
    1229             :       else
    1230             :         continue;
    1231             :     } else if (needsReferenceType(*Location)) {
    1232             :       // This location can't be expressed without switching to a reference type.
    1233             :       // Start over using that.
    1234           4 :       Var.UseReferenceType = true;
    1235           4 :       Var.DefRanges.clear();
    1236           4 :       calculateRanges(Var, Ranges);
    1237             :       return;
    1238             :     }
    1239             : 
    1240             :     // We can only handle a register or an offseted load of a register.
    1241         130 :     if (Location->Register == 0 || Location->LoadChain.size() > 1)
    1242             :       continue;
    1243             :     {
    1244             :       LocalVarDefRange DR;
    1245         128 :       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
    1246         128 :       DR.InMemory = !Location->LoadChain.empty();
    1247         128 :       DR.DataOffset =
    1248          27 :           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
    1249         128 :       if (Location->FragmentInfo) {
    1250          16 :         DR.IsSubfield = true;
    1251          16 :         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
    1252             :       } else {
    1253         112 :         DR.IsSubfield = false;
    1254         112 :         DR.StructOffset = 0;
    1255             :       }
    1256             : 
    1257         128 :       if (Var.DefRanges.empty() ||
    1258          42 :           Var.DefRanges.back().isDifferentLocation(DR)) {
    1259         102 :         Var.DefRanges.emplace_back(std::move(DR));
    1260             :       }
    1261             :     }
    1262             : 
    1263             :     // Compute the label range.
    1264         128 :     const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
    1265         128 :     const MCSymbol *End = getLabelAfterInsn(Range.second);
    1266         128 :     if (!End) {
    1267             :       // This range is valid until the next overlapping bitpiece. In the
    1268             :       // common case, ranges will not be bitpieces, so they will overlap.
    1269             :       auto J = std::next(I);
    1270          29 :       const DIExpression *DIExpr = DVInst->getDebugExpression();
    1271          51 :       while (J != E &&
    1272          16 :              !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
    1273           6 :         ++J;
    1274          29 :       if (J != E)
    1275          10 :         End = getLabelBeforeInsn(J->first);
    1276             :       else
    1277          19 :         End = Asm->getFunctionEnd();
    1278             :     }
    1279             : 
    1280             :     // If the last range end is our begin, just extend the last range.
    1281             :     // Otherwise make a new range.
    1282             :     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
    1283         128 :         Var.DefRanges.back().Ranges;
    1284         128 :     if (!R.empty() && R.back().second == Begin)
    1285          23 :       R.back().second = End;
    1286             :     else
    1287         105 :       R.emplace_back(Begin, End);
    1288             : 
    1289             :     // FIXME: Do more range combining.
    1290             :   }
    1291             : }
    1292             : 
    1293         235 : void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
    1294             :   DenseSet<InlinedEntity> Processed;
    1295             :   // Grab the variable info that was squirreled away in the MMI side-table.
    1296         235 :   collectVariableInfoFromMFTable(Processed);
    1297             : 
    1298         329 :   for (const auto &I : DbgValues) {
    1299          94 :     InlinedEntity IV = I.first;
    1300             :     if (Processed.count(IV))
    1301           4 :       continue;
    1302          90 :     const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
    1303          90 :     const DILocation *InlinedAt = IV.second;
    1304             : 
    1305             :     // Instruction ranges, specifying where IV is accessible.
    1306          90 :     const auto &Ranges = I.second;
    1307             : 
    1308             :     LexicalScope *Scope = nullptr;
    1309          90 :     if (InlinedAt)
    1310             :       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
    1311             :     else
    1312          86 :       Scope = LScopes.findLexicalScope(DIVar->getScope());
    1313             :     // If variable scope is not found then skip this variable.
    1314             :     if (!Scope)
    1315           0 :       continue;
    1316             : 
    1317             :     LocalVariable Var;
    1318          90 :     Var.DIVar = DIVar;
    1319             : 
    1320          90 :     calculateRanges(Var, Ranges);
    1321          90 :     recordLocalVariable(std::move(Var), Scope);
    1322             :   }
    1323         235 : }
    1324             : 
    1325         235 : void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
    1326         235 :   const TargetSubtargetInfo &TSI = MF->getSubtarget();
    1327         235 :   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
    1328         235 :   const MachineFrameInfo &MFI = MF->getFrameInfo();
    1329         235 :   const Function &GV = MF->getFunction();
    1330         470 :   auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
    1331             :   assert(Insertion.second && "function already has info");
    1332         235 :   CurFn = Insertion.first->second.get();
    1333         235 :   CurFn->FuncId = NextFuncId++;
    1334         235 :   CurFn->Begin = Asm->getFunctionBegin();
    1335             : 
    1336             :   // The S_FRAMEPROC record reports the stack size, and how many bytes of
    1337             :   // callee-saved registers were used. For targets that don't use a PUSH
    1338             :   // instruction (AArch64), this will be zero.
    1339         235 :   CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
    1340         235 :   CurFn->FrameSize = MFI.getStackSize();
    1341         235 :   CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
    1342             : 
    1343             :   // For this function S_FRAMEPROC record, figure out which codeview register
    1344             :   // will be the frame pointer.
    1345         235 :   CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
    1346         235 :   CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
    1347         235 :   if (CurFn->FrameSize > 0) {
    1348         179 :     if (!TSI.getFrameLowering()->hasFP(*MF)) {
    1349         126 :       CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
    1350         126 :       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
    1351             :     } else {
    1352             :       // If there is an FP, parameters are always relative to it.
    1353          53 :       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
    1354          53 :       if (CurFn->HasStackRealignment) {
    1355             :         // If the stack needs realignment, locals are relative to SP or VFRAME.
    1356           5 :         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
    1357             :       } else {
    1358             :         // Otherwise, locals are relative to EBP, and we probably have VLAs or
    1359             :         // other stack adjustments.
    1360          48 :         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
    1361             :       }
    1362             :     }
    1363             :   }
    1364             : 
    1365             :   // Compute other frame procedure options.
    1366             :   FrameProcedureOptions FPO = FrameProcedureOptions::None;
    1367         235 :   if (MFI.hasVarSizedObjects())
    1368             :     FPO |= FrameProcedureOptions::HasAlloca;
    1369         235 :   if (MF->exposesReturnsTwice())
    1370             :     FPO |= FrameProcedureOptions::HasSetJmp;
    1371             :   // FIXME: Set HasLongJmp if we ever track that info.
    1372         235 :   if (MF->hasInlineAsm())
    1373             :     FPO |= FrameProcedureOptions::HasInlineAssembly;
    1374         235 :   if (GV.hasPersonalityFn()) {
    1375           4 :     if (isAsynchronousEHPersonality(
    1376           4 :             classifyEHPersonality(GV.getPersonalityFn())))
    1377             :       FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
    1378             :     else
    1379             :       FPO |= FrameProcedureOptions::HasExceptionHandling;
    1380             :   }
    1381         235 :   if (GV.hasFnAttribute(Attribute::InlineHint))
    1382             :     FPO |= FrameProcedureOptions::MarkedInline;
    1383         235 :   if (GV.hasFnAttribute(Attribute::Naked))
    1384             :     FPO |= FrameProcedureOptions::Naked;
    1385         235 :   if (MFI.hasStackProtectorIndex())
    1386             :     FPO |= FrameProcedureOptions::SecurityChecks;
    1387         235 :   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
    1388         235 :   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
    1389         423 :   if (Asm->TM.getOptLevel() != CodeGenOpt::None && !GV.optForSize() &&
    1390             :       !GV.hasFnAttribute(Attribute::OptimizeNone))
    1391             :     FPO |= FrameProcedureOptions::OptimizedForSpeed;
    1392             :   // FIXME: Set GuardCfg when it is implemented.
    1393         235 :   CurFn->FrameProcOpts = FPO;
    1394             : 
    1395         235 :   OS.EmitCVFuncIdDirective(CurFn->FuncId);
    1396             : 
    1397             :   // Find the end of the function prolog.  First known non-DBG_VALUE and
    1398             :   // non-frame setup location marks the beginning of the function body.
    1399             :   // FIXME: is there a simpler a way to do this? Can we just search
    1400             :   // for the first instruction of the function, not the last of the prolog?
    1401         235 :   DebugLoc PrologEndLoc;
    1402             :   bool EmptyPrologue = true;
    1403         564 :   for (const auto &MBB : *MF) {
    1404        1856 :     for (const auto &MI : MBB) {
    1405        1470 :       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
    1406             :           MI.getDebugLoc()) {
    1407             :         PrologEndLoc = MI.getDebugLoc();
    1408             :         break;
    1409             :       } else if (!MI.isMetaInstruction()) {
    1410             :         EmptyPrologue = false;
    1411             :       }
    1412             :     }
    1413             :   }
    1414             : 
    1415             :   // Record beginning of function if we have a non-empty prologue.
    1416         235 :   if (PrologEndLoc && !EmptyPrologue) {
    1417         186 :     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
    1418         186 :     maybeRecordLocation(FnStartDL, MF);
    1419             :   }
    1420         235 : }
    1421             : 
    1422         114 : static bool shouldEmitUdt(const DIType *T) {
    1423         114 :   if (!T)
    1424             :     return false;
    1425             : 
    1426             :   // MSVC does not emit UDTs for typedefs that are scoped to classes.
    1427         114 :   if (T->getTag() == dwarf::DW_TAG_typedef) {
    1428             :     if (DIScope *Scope = T->getScope().resolve()) {
    1429           5 :       switch (Scope->getTag()) {
    1430             :       case dwarf::DW_TAG_structure_type:
    1431             :       case dwarf::DW_TAG_class_type:
    1432             :       case dwarf::DW_TAG_union_type:
    1433             :         return false;
    1434             :       }
    1435             :     }
    1436             :   }
    1437             : 
    1438             :   while (true) {
    1439         125 :     if (!T || T->isForwardDecl())
    1440             :       return false;
    1441             : 
    1442             :     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
    1443             :     if (!DT)
    1444             :       return true;
    1445             :     T = DT->getBaseType().resolve();
    1446             :   }
    1447             :   return true;
    1448             : }
    1449             : 
    1450         120 : void CodeViewDebug::addToUDTs(const DIType *Ty) {
    1451             :   // Don't record empty UDTs.
    1452         120 :   if (Ty->getName().empty())
    1453          11 :     return;
    1454         114 :   if (!shouldEmitUdt(Ty))
    1455             :     return;
    1456             : 
    1457             :   SmallVector<StringRef, 5> QualifiedNameComponents;
    1458         109 :   const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
    1459             :       Ty->getScope().resolve(), QualifiedNameComponents);
    1460             : 
    1461             :   std::string FullyQualifiedName =
    1462         109 :       getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
    1463             : 
    1464         109 :   if (ClosestSubprogram == nullptr) {
    1465         103 :     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
    1466           6 :   } else if (ClosestSubprogram == CurrentSubprogram) {
    1467           6 :     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
    1468             :   }
    1469             : 
    1470             :   // TODO: What if the ClosestSubprogram is neither null or the current
    1471             :   // subprogram?  Currently, the UDT just gets dropped on the floor.
    1472             :   //
    1473             :   // The current behavior is not desirable.  To get maximal fidelity, we would
    1474             :   // need to perform all type translation before beginning emission of .debug$S
    1475             :   // and then make LocalUDTs a member of FunctionInfo
    1476             : }
    1477             : 
    1478         657 : TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
    1479             :   // Generic dispatch for lowering an unknown type.
    1480        1314 :   switch (Ty->getTag()) {
    1481             :   case dwarf::DW_TAG_array_type:
    1482          17 :     return lowerTypeArray(cast<DICompositeType>(Ty));
    1483             :   case dwarf::DW_TAG_typedef:
    1484          16 :     return lowerTypeAlias(cast<DIDerivedType>(Ty));
    1485             :   case dwarf::DW_TAG_base_type:
    1486         131 :     return lowerTypeBasic(cast<DIBasicType>(Ty));
    1487             :   case dwarf::DW_TAG_pointer_type:
    1488             :     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
    1489           9 :       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
    1490             :     LLVM_FALLTHROUGH;
    1491             :   case dwarf::DW_TAG_reference_type:
    1492             :   case dwarf::DW_TAG_rvalue_reference_type:
    1493         142 :     return lowerTypePointer(cast<DIDerivedType>(Ty));
    1494             :   case dwarf::DW_TAG_ptr_to_member_type:
    1495          15 :     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
    1496             :   case dwarf::DW_TAG_restrict_type:
    1497             :   case dwarf::DW_TAG_const_type:
    1498             :   case dwarf::DW_TAG_volatile_type:
    1499             :   // TODO: add support for DW_TAG_atomic_type here
    1500          28 :     return lowerTypeModifier(cast<DIDerivedType>(Ty));
    1501         177 :   case dwarf::DW_TAG_subroutine_type:
    1502         177 :     if (ClassTy) {
    1503             :       // The member function type of a member function pointer has no
    1504             :       // ThisAdjustment.
    1505             :       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
    1506             :                                      /*ThisAdjustment=*/0,
    1507           9 :                                      /*IsStaticMethod=*/false);
    1508             :     }
    1509         168 :     return lowerTypeFunction(cast<DISubroutineType>(Ty));
    1510             :   case dwarf::DW_TAG_enumeration_type:
    1511           8 :     return lowerTypeEnum(cast<DICompositeType>(Ty));
    1512             :   case dwarf::DW_TAG_class_type:
    1513             :   case dwarf::DW_TAG_structure_type:
    1514         106 :     return lowerTypeClass(cast<DICompositeType>(Ty));
    1515             :   case dwarf::DW_TAG_union_type:
    1516           8 :     return lowerTypeUnion(cast<DICompositeType>(Ty));
    1517             :   case dwarf::DW_TAG_unspecified_type:
    1518             :     return TypeIndex::None();
    1519             :   default:
    1520             :     // Use the null type index.
    1521           0 :     return TypeIndex();
    1522             :   }
    1523             : }
    1524             : 
    1525          16 : TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
    1526          16 :   DITypeRef UnderlyingTypeRef = Ty->getBaseType();
    1527          16 :   TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
    1528             :   StringRef TypeName = Ty->getName();
    1529             : 
    1530          16 :   addToUDTs(Ty);
    1531             : 
    1532          16 :   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
    1533             :       TypeName == "HRESULT")
    1534           0 :     return TypeIndex(SimpleTypeKind::HResult);
    1535          16 :   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
    1536             :       TypeName == "wchar_t")
    1537           0 :     return TypeIndex(SimpleTypeKind::WideCharacter);
    1538             : 
    1539          16 :   return UnderlyingTypeIndex;
    1540             : }
    1541             : 
    1542          17 : TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
    1543          17 :   DITypeRef ElementTypeRef = Ty->getBaseType();
    1544          17 :   TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
    1545             :   // IndexType is size_t, which depends on the bitness of the target.
    1546          17 :   TypeIndex IndexType = getPointerSizeInBytes() == 8
    1547             :                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
    1548          17 :                             : TypeIndex(SimpleTypeKind::UInt32Long);
    1549             : 
    1550          17 :   uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
    1551             : 
    1552             :   // Add subranges to array type.
    1553             :   DINodeArray Elements = Ty->getElements();
    1554          36 :   for (int i = Elements.size() - 1; i >= 0; --i) {
    1555          19 :     const DINode *Element = Elements[i];
    1556             :     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
    1557             : 
    1558             :     const DISubrange *Subrange = cast<DISubrange>(Element);
    1559             :     assert(Subrange->getLowerBound() == 0 &&
    1560             :            "codeview doesn't support subranges with lower bounds");
    1561             :     int64_t Count = -1;
    1562          19 :     if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
    1563             :       Count = CI->getSExtValue();
    1564             : 
    1565             :     // Forward declarations of arrays without a size and VLAs use a count of -1.
    1566             :     // Emit a count of zero in these cases to match what MSVC does for arrays
    1567             :     // without a size. MSVC doesn't support VLAs, so it's not clear what we
    1568             :     // should do for them even if we could distinguish them.
    1569          19 :     if (Count == -1)
    1570             :       Count = 0;
    1571             : 
    1572             :     // Update the element size and element type index for subsequent subranges.
    1573          19 :     ElementSize *= Count;
    1574             : 
    1575             :     // If this is the outermost array, use the size from the array. It will be
    1576             :     // more accurate if we had a VLA or an incomplete element type size.
    1577             :     uint64_t ArraySize =
    1578          19 :         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
    1579             : 
    1580          19 :     StringRef Name = (i == 0) ? Ty->getName() : "";
    1581          19 :     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
    1582          38 :     ElementTypeIndex = TypeTable.writeLeafType(AR);
    1583             :   }
    1584             : 
    1585          17 :   return ElementTypeIndex;
    1586             : }
    1587             : 
    1588         131 : TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
    1589             :   TypeIndex Index;
    1590             :   dwarf::TypeKind Kind;
    1591             :   uint32_t ByteSize;
    1592             : 
    1593         131 :   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
    1594         131 :   ByteSize = Ty->getSizeInBits() / 8;
    1595             : 
    1596             :   SimpleTypeKind STK = SimpleTypeKind::None;
    1597         131 :   switch (Kind) {
    1598             :   case dwarf::DW_ATE_address:
    1599             :     // FIXME: Translate
    1600             :     break;
    1601           3 :   case dwarf::DW_ATE_boolean:
    1602             :     switch (ByteSize) {
    1603             :     case 1:  STK = SimpleTypeKind::Boolean8;   break;
    1604             :     case 2:  STK = SimpleTypeKind::Boolean16;  break;
    1605             :     case 4:  STK = SimpleTypeKind::Boolean32;  break;
    1606             :     case 8:  STK = SimpleTypeKind::Boolean64;  break;
    1607             :     case 16: STK = SimpleTypeKind::Boolean128; break;
    1608             :     }
    1609             :     break;
    1610           0 :   case dwarf::DW_ATE_complex_float:
    1611             :     switch (ByteSize) {
    1612             :     case 2:  STK = SimpleTypeKind::Complex16;  break;
    1613             :     case 4:  STK = SimpleTypeKind::Complex32;  break;
    1614             :     case 8:  STK = SimpleTypeKind::Complex64;  break;
    1615             :     case 10: STK = SimpleTypeKind::Complex80;  break;
    1616             :     case 16: STK = SimpleTypeKind::Complex128; break;
    1617             :     }
    1618             :     break;
    1619          12 :   case dwarf::DW_ATE_float:
    1620             :     switch (ByteSize) {
    1621             :     case 2:  STK = SimpleTypeKind::Float16;  break;
    1622             :     case 4:  STK = SimpleTypeKind::Float32;  break;
    1623             :     case 6:  STK = SimpleTypeKind::Float48;  break;
    1624             :     case 8:  STK = SimpleTypeKind::Float64;  break;
    1625             :     case 10: STK = SimpleTypeKind::Float80;  break;
    1626             :     case 16: STK = SimpleTypeKind::Float128; break;
    1627             :     }
    1628             :     break;
    1629          90 :   case dwarf::DW_ATE_signed:
    1630             :     switch (ByteSize) {
    1631             :     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
    1632             :     case 2:  STK = SimpleTypeKind::Int16Short;      break;
    1633             :     case 4:  STK = SimpleTypeKind::Int32;           break;
    1634             :     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
    1635             :     case 16: STK = SimpleTypeKind::Int128Oct;       break;
    1636             :     }
    1637             :     break;
    1638           9 :   case dwarf::DW_ATE_unsigned:
    1639             :     switch (ByteSize) {
    1640             :     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
    1641             :     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
    1642             :     case 4:  STK = SimpleTypeKind::UInt32;            break;
    1643             :     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
    1644             :     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
    1645             :     }
    1646             :     break;
    1647           2 :   case dwarf::DW_ATE_UTF:
    1648             :     switch (ByteSize) {
    1649             :     case 2: STK = SimpleTypeKind::Character16; break;
    1650             :     case 4: STK = SimpleTypeKind::Character32; break;
    1651             :     }
    1652             :     break;
    1653          12 :   case dwarf::DW_ATE_signed_char:
    1654          12 :     if (ByteSize == 1)
    1655             :       STK = SimpleTypeKind::SignedCharacter;
    1656             :     break;
    1657           3 :   case dwarf::DW_ATE_unsigned_char:
    1658           3 :     if (ByteSize == 1)
    1659             :       STK = SimpleTypeKind::UnsignedCharacter;
    1660             :     break;
    1661             :   default:
    1662             :     break;
    1663             :   }
    1664             : 
    1665             :   // Apply some fixups based on the source-level type name.
    1666             :   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
    1667             :     STK = SimpleTypeKind::Int32Long;
    1668         126 :   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
    1669             :     STK = SimpleTypeKind::UInt32Long;
    1670         129 :   if (STK == SimpleTypeKind::UInt16Short &&
    1671             :       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
    1672             :     STK = SimpleTypeKind::WideCharacter;
    1673         262 :   if ((STK == SimpleTypeKind::SignedCharacter ||
    1674         131 :        STK == SimpleTypeKind::UnsignedCharacter) &&
    1675             :       Ty->getName() == "char")
    1676             :     STK = SimpleTypeKind::NarrowCharacter;
    1677             : 
    1678         131 :   return TypeIndex(STK);
    1679             : }
    1680             : 
    1681         147 : TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
    1682             :                                           PointerOptions PO) {
    1683         294 :   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
    1684             : 
    1685             :   // Pointers to simple types without any options can use SimpleTypeMode, rather
    1686             :   // than having a dedicated pointer type record.
    1687          21 :   if (PointeeTI.isSimple() && PO == PointerOptions::None &&
    1688         147 :       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
    1689          13 :       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
    1690          13 :     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
    1691          13 :                               ? SimpleTypeMode::NearPointer64
    1692             :                               : SimpleTypeMode::NearPointer32;
    1693          13 :     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
    1694             :   }
    1695             : 
    1696             :   PointerKind PK =
    1697         134 :       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
    1698             :   PointerMode PM = PointerMode::Pointer;
    1699         268 :   switch (Ty->getTag()) {
    1700           0 :   default: llvm_unreachable("not a pointer tag type");
    1701             :   case dwarf::DW_TAG_pointer_type:
    1702             :     PM = PointerMode::Pointer;
    1703             :     break;
    1704          13 :   case dwarf::DW_TAG_reference_type:
    1705             :     PM = PointerMode::LValueReference;
    1706          13 :     break;
    1707           0 :   case dwarf::DW_TAG_rvalue_reference_type:
    1708             :     PM = PointerMode::RValueReference;
    1709           0 :     break;
    1710             :   }
    1711             : 
    1712         134 :   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
    1713         134 :   return TypeTable.writeLeafType(PR);
    1714             : }
    1715             : 
    1716             : static PointerToMemberRepresentation
    1717          16 : translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
    1718             :   // SizeInBytes being zero generally implies that the member pointer type was
    1719             :   // incomplete, which can happen if it is part of a function prototype. In this
    1720             :   // case, use the unknown model instead of the general model.
    1721          16 :   if (IsPMF) {
    1722           9 :     switch (Flags & DINode::FlagPtrToMemberRep) {
    1723           3 :     case 0:
    1724           3 :       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
    1725           3 :                               : PointerToMemberRepresentation::GeneralFunction;
    1726             :     case DINode::FlagSingleInheritance:
    1727             :       return PointerToMemberRepresentation::SingleInheritanceFunction;
    1728           1 :     case DINode::FlagMultipleInheritance:
    1729           1 :       return PointerToMemberRepresentation::MultipleInheritanceFunction;
    1730           1 :     case DINode::FlagVirtualInheritance:
    1731           1 :       return PointerToMemberRepresentation::VirtualInheritanceFunction;
    1732             :     }
    1733             :   } else {
    1734           7 :     switch (Flags & DINode::FlagPtrToMemberRep) {
    1735           3 :     case 0:
    1736           3 :       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
    1737           3 :                               : PointerToMemberRepresentation::GeneralData;
    1738             :     case DINode::FlagSingleInheritance:
    1739             :       return PointerToMemberRepresentation::SingleInheritanceData;
    1740           1 :     case DINode::FlagMultipleInheritance:
    1741           1 :       return PointerToMemberRepresentation::MultipleInheritanceData;
    1742           1 :     case DINode::FlagVirtualInheritance:
    1743           1 :       return PointerToMemberRepresentation::VirtualInheritanceData;
    1744             :     }
    1745             :   }
    1746           0 :   llvm_unreachable("invalid ptr to member representation");
    1747             : }
    1748             : 
    1749          16 : TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
    1750             :                                                 PointerOptions PO) {
    1751             :   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
    1752          32 :   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
    1753          16 :   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
    1754          16 :   PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
    1755             :                                                 : PointerKind::Near32;
    1756             :   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
    1757          16 :   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
    1758             :                          : PointerMode::PointerToDataMember;
    1759             : 
    1760             :   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
    1761          16 :   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
    1762             :   MemberPointerInfo MPI(
    1763          32 :       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
    1764          16 :   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
    1765          16 :   return TypeTable.writeLeafType(PR);
    1766             : }
    1767             : 
    1768             : /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
    1769             : /// have a translation, use the NearC convention.
    1770             : static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
    1771             :   switch (DwarfCC) {
    1772             :   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
    1773             :   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
    1774             :   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
    1775             :   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
    1776             :   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
    1777             :   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
    1778             :   }
    1779             :   return CallingConvention::NearC;
    1780             : }
    1781             : 
    1782          28 : TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
    1783             :   ModifierOptions Mods = ModifierOptions::None;
    1784             :   PointerOptions PO = PointerOptions::None;
    1785             :   bool IsModifier = true;
    1786             :   const DIType *BaseTy = Ty;
    1787          86 :   while (IsModifier && BaseTy) {
    1788             :     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
    1789         116 :     switch (BaseTy->getTag()) {
    1790             :     case dwarf::DW_TAG_const_type:
    1791             :       Mods |= ModifierOptions::Const;
    1792             :       PO |= PointerOptions::Const;
    1793             :       break;
    1794             :     case dwarf::DW_TAG_volatile_type:
    1795             :       Mods |= ModifierOptions::Volatile;
    1796             :       PO |= PointerOptions::Volatile;
    1797             :       break;
    1798             :     case dwarf::DW_TAG_restrict_type:
    1799             :       // Only pointer types be marked with __restrict. There is no known flag
    1800             :       // for __restrict in LF_MODIFIER records.
    1801             :       PO |= PointerOptions::Restrict;
    1802             :       break;
    1803             :     default:
    1804             :       IsModifier = false;
    1805             :       break;
    1806             :     }
    1807          58 :     if (IsModifier)
    1808             :       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
    1809             :   }
    1810             : 
    1811             :   // Check if the inner type will use an LF_POINTER record. If so, the
    1812             :   // qualifiers will go in the LF_POINTER record. This comes up for types like
    1813             :   // 'int *const' and 'int *__restrict', not the more common cases like 'const
    1814             :   // char *'.
    1815          28 :   if (BaseTy) {
    1816          54 :     switch (BaseTy->getTag()) {
    1817           5 :     case dwarf::DW_TAG_pointer_type:
    1818             :     case dwarf::DW_TAG_reference_type:
    1819             :     case dwarf::DW_TAG_rvalue_reference_type:
    1820           5 :       return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
    1821           1 :     case dwarf::DW_TAG_ptr_to_member_type:
    1822           1 :       return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
    1823             :     default:
    1824             :       break;
    1825             :     }
    1826             :   }
    1827             : 
    1828          44 :   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
    1829             : 
    1830             :   // Return the base type index if there aren't any modifiers. For example, the
    1831             :   // metadata could contain restrict wrappers around non-pointer types.
    1832          22 :   if (Mods == ModifierOptions::None)
    1833           1 :     return ModifiedTI;
    1834             : 
    1835          21 :   ModifierRecord MR(ModifiedTI, Mods);
    1836          21 :   return TypeTable.writeLeafType(MR);
    1837             : }
    1838             : 
    1839         168 : TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
    1840             :   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
    1841         425 :   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
    1842         257 :     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
    1843             : 
    1844             :   // MSVC uses type none for variadic argument.
    1845         336 :   if (ReturnAndArgTypeIndices.size() > 1 &&
    1846         168 :       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
    1847           1 :     ReturnAndArgTypeIndices.back() = TypeIndex::None();
    1848             :   }
    1849         168 :   TypeIndex ReturnTypeIndex = TypeIndex::Void();
    1850             :   ArrayRef<TypeIndex> ArgTypeIndices = None;
    1851         168 :   if (!ReturnAndArgTypeIndices.empty()) {
    1852             :     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
    1853         154 :     ReturnTypeIndex = ReturnAndArgTypesRef.front();
    1854             :     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
    1855             :   }
    1856             : 
    1857             :   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
    1858         168 :   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
    1859             : 
    1860         168 :   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
    1861             : 
    1862         168 :   FunctionOptions FO = getFunctionOptions(Ty);
    1863             :   ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
    1864         336 :                             ArgListIndex);
    1865         168 :   return TypeTable.writeLeafType(Procedure);
    1866             : }
    1867             : 
    1868          94 : TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
    1869             :                                                  const DIType *ClassTy,
    1870             :                                                  int ThisAdjustment,
    1871             :                                                  bool IsStaticMethod,
    1872             :                                                  FunctionOptions FO) {
    1873             :   // Lower the containing class type.
    1874         188 :   TypeIndex ClassType = getTypeIndex(ClassTy);
    1875             : 
    1876             :   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
    1877         295 :   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
    1878         202 :     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
    1879             : 
    1880             :   // MSVC uses type none for variadic argument.
    1881         186 :   if (ReturnAndArgTypeIndices.size() > 1 &&
    1882          93 :       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
    1883           1 :     ReturnAndArgTypeIndices.back() = TypeIndex::None();
    1884             :   }
    1885          93 :   TypeIndex ReturnTypeIndex = TypeIndex::Void();
    1886             :   ArrayRef<TypeIndex> ArgTypeIndices = None;
    1887          93 :   if (!ReturnAndArgTypeIndices.empty()) {
    1888             :     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
    1889          93 :     ReturnTypeIndex = ReturnAndArgTypesRef.front();
    1890             :     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
    1891             :   }
    1892             :   TypeIndex ThisTypeIndex;
    1893          93 :   if (!IsStaticMethod && !ArgTypeIndices.empty()) {
    1894          91 :     ThisTypeIndex = ArgTypeIndices.front();
    1895             :     ArgTypeIndices = ArgTypeIndices.drop_front();
    1896             :   }
    1897             : 
    1898             :   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
    1899          93 :   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
    1900             : 
    1901          93 :   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
    1902             : 
    1903             :   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
    1904         186 :                            ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
    1905          93 :   return TypeTable.writeLeafType(MFR);
    1906             : }
    1907             : 
    1908           9 : TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
    1909             :   unsigned VSlotCount =
    1910           9 :       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
    1911           9 :   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
    1912             : 
    1913             :   VFTableShapeRecord VFTSR(Slots);
    1914           9 :   return TypeTable.writeLeafType(VFTSR);
    1915             : }
    1916             : 
    1917             : static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
    1918         209 :   switch (Flags & DINode::FlagAccessibility) {
    1919             :   case DINode::FlagPrivate:   return MemberAccess::Private;
    1920          18 :   case DINode::FlagPublic:    return MemberAccess::Public;
    1921           2 :   case DINode::FlagProtected: return MemberAccess::Protected;
    1922         188 :   case 0:
    1923             :     // If there was no explicit access control, provide the default for the tag.
    1924         188 :     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
    1925             :                                                  : MemberAccess::Public;
    1926             :   }
    1927           0 :   llvm_unreachable("access flags are exclusive");
    1928             : }
    1929             : 
    1930             : static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
    1931          66 :   if (SP->isArtificial())
    1932             :     return MethodOptions::CompilerGenerated;
    1933             : 
    1934             :   // FIXME: Handle other MethodOptions.
    1935             : 
    1936             :   return MethodOptions::None;
    1937             : }
    1938             : 
    1939             : static MethodKind translateMethodKindFlags(const DISubprogram *SP,
    1940             :                                            bool Introduced) {
    1941          66 :   if (SP->getFlags() & DINode::FlagStaticMember)
    1942             :     return MethodKind::Static;
    1943             : 
    1944          64 :   switch (SP->getVirtuality()) {
    1945             :   case dwarf::DW_VIRTUALITY_none:
    1946             :     break;
    1947          23 :   case dwarf::DW_VIRTUALITY_virtual:
    1948          23 :     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
    1949           3 :   case dwarf::DW_VIRTUALITY_pure_virtual:
    1950           3 :     return Introduced ? MethodKind::PureIntroducingVirtual
    1951             :                       : MethodKind::PureVirtual;
    1952           0 :   default:
    1953           0 :     llvm_unreachable("unhandled virtuality case");
    1954             :   }
    1955             : 
    1956             :   return MethodKind::Vanilla;
    1957             : }
    1958             : 
    1959             : static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
    1960         199 :   switch (Ty->getTag()) {
    1961             :   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
    1962         163 :   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
    1963             :   }
    1964           0 :   llvm_unreachable("unexpected tag");
    1965             : }
    1966             : 
    1967             : /// Return ClassOptions that should be present on both the forward declaration
    1968             : /// and the defintion of a tag type.
    1969         222 : static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
    1970             :   ClassOptions CO = ClassOptions::None;
    1971             : 
    1972             :   // MSVC always sets this flag, even for local types. Clang doesn't always
    1973             :   // appear to give every type a linkage name, which may be problematic for us.
    1974             :   // FIXME: Investigate the consequences of not following them here.
    1975         222 :   if (!Ty->getIdentifier().empty())
    1976             :     CO |= ClassOptions::HasUniqueName;
    1977             : 
    1978             :   // Put the Nested flag on a type if it appears immediately inside a tag type.
    1979             :   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
    1980             :   // here. That flag is only set on definitions, and not forward declarations.
    1981             :   const DIScope *ImmediateScope = Ty->getScope().resolve();
    1982          35 :   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
    1983             :     CO |= ClassOptions::Nested;
    1984             : 
    1985             :   // Put the Scoped flag on function-local types. MSVC puts this flag for enum
    1986             :   // type only when it has an immediate function scope. Clang never puts enums 
    1987             :   // inside DILexicalBlock scopes. Enum types, as generated by clang, are 
    1988             :   // always in function, class, or file scopes.
    1989         222 :   if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
    1990           8 :     if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
    1991             :       CO |= ClassOptions::Scoped;
    1992             :   } else {
    1993         218 :     for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
    1994          23 :          Scope = Scope->getScope().resolve()) {
    1995          35 :       if (isa<DISubprogram>(Scope)) {
    1996             :         CO |= ClassOptions::Scoped;
    1997             :         break;
    1998             :       }
    1999             :     }
    2000             :   }
    2001             : 
    2002         222 :   return CO;
    2003             : }
    2004             : 
    2005         112 : void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
    2006         112 :   switch (Ty->getTag()) {
    2007             :   case dwarf::DW_TAG_class_type:
    2008             :   case dwarf::DW_TAG_structure_type:
    2009             :   case dwarf::DW_TAG_union_type:
    2010             :   case dwarf::DW_TAG_enumeration_type:
    2011             :     break;
    2012             :   default:
    2013             :     return;
    2014             :   }
    2015             : 
    2016             :   if (const auto *File = Ty->getFile()) {
    2017         110 :     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
    2018         110 :     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
    2019             : 
    2020         220 :     UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
    2021             :     TypeTable.writeLeafType(USLR);
    2022             :   }
    2023             : }
    2024             : 
    2025           8 : TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
    2026           8 :   ClassOptions CO = getCommonClassOptions(Ty);
    2027             :   TypeIndex FTI;
    2028             :   unsigned EnumeratorCount = 0;
    2029             : 
    2030           8 :   if (Ty->isForwardDecl()) {
    2031             :     CO |= ClassOptions::ForwardReference;
    2032             :   } else {
    2033          16 :     ContinuationRecordBuilder ContinuationBuilder;
    2034           8 :     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
    2035        5716 :     for (const DINode *Element : Ty->getElements()) {
    2036             :       // We assume that the frontend provides all members in source declaration
    2037             :       // order, which is what MSVC does.
    2038        5708 :       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
    2039             :         EnumeratorRecord ER(MemberAccess::Public,
    2040        5708 :                             APSInt::getUnsigned(Enumerator->getValue()),
    2041             :                             Enumerator->getName());
    2042        5708 :         ContinuationBuilder.writeMemberType(ER);
    2043        5708 :         EnumeratorCount++;
    2044             :       }
    2045             :     }
    2046           8 :     FTI = TypeTable.insertRecord(ContinuationBuilder);
    2047             :   }
    2048             : 
    2049           8 :   std::string FullName = getFullyQualifiedName(Ty);
    2050             : 
    2051             :   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
    2052          24 :                 getTypeIndex(Ty->getBaseType()));
    2053           8 :   TypeIndex EnumTI = TypeTable.writeLeafType(ER);
    2054             : 
    2055           8 :   addUDTSrcLine(Ty, EnumTI);
    2056             : 
    2057           8 :   return EnumTI;
    2058             : }
    2059             : 
    2060             : //===----------------------------------------------------------------------===//
    2061             : // ClassInfo
    2062             : //===----------------------------------------------------------------------===//
    2063             : 
    2064             : struct llvm::ClassInfo {
    2065             :   struct MemberInfo {
    2066             :     const DIDerivedType *MemberTypeNode;
    2067             :     uint64_t BaseOffset;
    2068             :   };
    2069             :   // [MemberInfo]
    2070             :   using MemberList = std::vector<MemberInfo>;
    2071             : 
    2072             :   using MethodsList = TinyPtrVector<const DISubprogram *>;
    2073             :   // MethodName -> MethodsList
    2074             :   using MethodsMap = MapVector<MDString *, MethodsList>;
    2075             : 
    2076             :   /// Base classes.
    2077             :   std::vector<const DIDerivedType *> Inheritance;
    2078             : 
    2079             :   /// Direct members.
    2080             :   MemberList Members;
    2081             :   // Direct overloaded methods gathered by name.
    2082             :   MethodsMap Methods;
    2083             : 
    2084             :   TypeIndex VShapeTI;
    2085             : 
    2086             :   std::vector<const DIType *> NestedTypes;
    2087             : };
    2088             : 
    2089         130 : void CodeViewDebug::clear() {
    2090             :   assert(CurFn == nullptr);
    2091         130 :   FileIdMap.clear();
    2092         130 :   FnDebugInfo.clear();
    2093             :   FileToFilepathMap.clear();
    2094             :   LocalUDTs.clear();
    2095             :   GlobalUDTs.clear();
    2096         130 :   TypeIndices.clear();
    2097         130 :   CompleteTypeIndices.clear();
    2098         130 : }
    2099             : 
    2100         124 : void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
    2101             :                                       const DIDerivedType *DDTy) {
    2102         124 :   if (!DDTy->getName().empty()) {
    2103         122 :     Info.Members.push_back({DDTy, 0});
    2104         122 :     return;
    2105             :   }
    2106             : 
    2107             :   // An unnamed member may represent a nested struct or union. Attempt to
    2108             :   // interpret the unnamed member as a DICompositeType possibly wrapped in
    2109             :   // qualifier types. Add all the indirect fields to the current record if that
    2110             :   // succeeds, and drop the member if that fails.
    2111             :   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
    2112           2 :   uint64_t Offset = DDTy->getOffsetInBits();
    2113             :   const DIType *Ty = DDTy->getBaseType().resolve();
    2114             :   bool FullyResolved = false;
    2115             :   while (!FullyResolved) {
    2116           6 :     switch (Ty->getTag()) {
    2117             :     case dwarf::DW_TAG_const_type:
    2118             :     case dwarf::DW_TAG_volatile_type:
    2119             :       // FIXME: we should apply the qualifier types to the indirect fields
    2120             :       // rather than dropping them.
    2121             :       Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
    2122             :       break;
    2123             :     default:
    2124             :       FullyResolved = true;
    2125             :       break;
    2126             :     }
    2127             :   }
    2128             : 
    2129             :   const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
    2130             :   if (!DCTy)
    2131             :     return;
    2132             : 
    2133           4 :   ClassInfo NestedInfo = collectClassInfo(DCTy);
    2134           4 :   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
    2135           2 :     Info.Members.push_back(
    2136           2 :         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
    2137             : }
    2138             : 
    2139         108 : ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
    2140         108 :   ClassInfo Info;
    2141             :   // Add elements to structure type.
    2142             :   DINodeArray Elements = Ty->getElements();
    2143         346 :   for (auto *Element : Elements) {
    2144             :     // We assume that the frontend provides all members in source declaration
    2145             :     // order, which is what MSVC does.
    2146             :     if (!Element)
    2147             :       continue;
    2148             :     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
    2149          68 :       Info.Methods[SP->getRawName()].push_back(SP);
    2150             :     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
    2151         322 :       if (DDTy->getTag() == dwarf::DW_TAG_member) {
    2152         124 :         collectMemberInfo(Info, DDTy);
    2153          37 :       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
    2154          22 :         Info.Inheritance.push_back(DDTy);
    2155          15 :       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
    2156             :                  DDTy->getName() == "__vtbl_ptr_type") {
    2157          22 :         Info.VShapeTI = getTypeIndex(DDTy);
    2158           8 :       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
    2159           4 :         Info.NestedTypes.push_back(DDTy);
    2160             :       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
    2161             :         // Ignore friend members. It appears that MSVC emitted info about
    2162             :         // friends in the past, but modern versions do not.
    2163             :       }
    2164             :     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
    2165           9 :       Info.NestedTypes.push_back(Composite);
    2166             :     }
    2167             :     // Skip other unrecognized kinds of elements.
    2168             :   }
    2169         108 :   return Info;
    2170             : }
    2171             : 
    2172         114 : static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
    2173             :   // This routine is used by lowerTypeClass and lowerTypeUnion to determine
    2174             :   // if a complete type should be emitted instead of a forward reference.
    2175         122 :   return Ty->getName().empty() && Ty->getIdentifier().empty() &&
    2176         114 :       !Ty->isForwardDecl();
    2177             : }
    2178             : 
    2179         106 : TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
    2180             :   // Emit the complete type for unnamed structs.  C++ classes with methods
    2181             :   // which have a circular reference back to the class type are expected to
    2182             :   // be named by the front-end and should not be "unnamed".  C unnamed
    2183             :   // structs should not have circular references.
    2184         106 :   if (shouldAlwaysEmitCompleteClassType(Ty)) {
    2185             :     // If this unnamed complete type is already in the process of being defined
    2186             :     // then the description of the type is malformed and cannot be emitted
    2187             :     // into CodeView correctly so report a fatal error.
    2188           5 :     auto I = CompleteTypeIndices.find(Ty);
    2189           5 :     if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
    2190           1 :       report_fatal_error("cannot debug circular reference to unnamed type");
    2191           8 :     return getCompleteTypeIndex(Ty);
    2192             :   }
    2193             : 
    2194             :   // First, construct the forward decl.  Don't look into Ty to compute the
    2195             :   // forward decl options, since it might not be available in all TUs.
    2196         101 :   TypeRecordKind Kind = getRecordKind(Ty);
    2197             :   ClassOptions CO =
    2198         101 :       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
    2199         101 :   std::string FullName = getFullyQualifiedName(Ty);
    2200             :   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
    2201         101 :                  FullName, Ty->getIdentifier());
    2202         101 :   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
    2203         202 :   if (!Ty->isForwardDecl())
    2204          94 :     DeferredCompleteTypes.push_back(Ty);
    2205         101 :   return FwdDeclTI;
    2206             : }
    2207             : 
    2208          98 : TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
    2209             :   // Construct the field list and complete type record.
    2210             :   TypeRecordKind Kind = getRecordKind(Ty);
    2211          98 :   ClassOptions CO = getCommonClassOptions(Ty);
    2212             :   TypeIndex FieldTI;
    2213             :   TypeIndex VShapeTI;
    2214             :   unsigned FieldCount;
    2215             :   bool ContainsNestedClass;
    2216             :   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
    2217          98 :       lowerRecordFieldList(Ty);
    2218             : 
    2219          96 :   if (ContainsNestedClass)
    2220             :     CO |= ClassOptions::ContainsNestedClass;
    2221             : 
    2222          96 :   std::string FullName = getFullyQualifiedName(Ty);
    2223             : 
    2224          96 :   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
    2225             : 
    2226             :   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
    2227          96 :                  SizeInBytes, FullName, Ty->getIdentifier());
    2228          96 :   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
    2229             : 
    2230          96 :   addUDTSrcLine(Ty, ClassTI);
    2231             : 
    2232          96 :   addToUDTs(Ty);
    2233             : 
    2234          96 :   return ClassTI;
    2235             : }
    2236             : 
    2237           8 : TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
    2238             :   // Emit the complete type for unnamed unions.
    2239           8 :   if (shouldAlwaysEmitCompleteClassType(Ty))
    2240           2 :     return getCompleteTypeIndex(Ty);
    2241             : 
    2242             :   ClassOptions CO =
    2243           7 :       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
    2244           7 :   std::string FullName = getFullyQualifiedName(Ty);
    2245           7 :   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
    2246           7 :   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
    2247          14 :   if (!Ty->isForwardDecl())
    2248           7 :     DeferredCompleteTypes.push_back(Ty);
    2249           7 :   return FwdDeclTI;
    2250             : }
    2251             : 
    2252           8 : TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
    2253           8 :   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
    2254             :   TypeIndex FieldTI;
    2255             :   unsigned FieldCount;
    2256             :   bool ContainsNestedClass;
    2257             :   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
    2258           8 :       lowerRecordFieldList(Ty);
    2259             : 
    2260           8 :   if (ContainsNestedClass)
    2261             :     CO |= ClassOptions::ContainsNestedClass;
    2262             : 
    2263           8 :   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
    2264           8 :   std::string FullName = getFullyQualifiedName(Ty);
    2265             : 
    2266             :   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
    2267           8 :                  Ty->getIdentifier());
    2268           8 :   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
    2269             : 
    2270           8 :   addUDTSrcLine(Ty, UnionTI);
    2271             : 
    2272           8 :   addToUDTs(Ty);
    2273             : 
    2274           8 :   return UnionTI;
    2275             : }
    2276             : 
    2277             : std::tuple<TypeIndex, TypeIndex, unsigned, bool>
    2278         106 : CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
    2279             :   // Manually count members. MSVC appears to count everything that generates a
    2280             :   // field list record. Each individual overload in a method overload group
    2281             :   // contributes to this count, even though the overload group is a single field
    2282             :   // list record.
    2283             :   unsigned MemberCount = 0;
    2284         210 :   ClassInfo Info = collectClassInfo(Ty);
    2285         106 :   ContinuationRecordBuilder ContinuationBuilder;
    2286         106 :   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
    2287             : 
    2288             :   // Create base classes.
    2289         128 :   for (const DIDerivedType *I : Info.Inheritance) {
    2290          44 :     if (I->getFlags() & DINode::FlagVirtual) {
    2291             :       // Virtual base.
    2292           9 :       unsigned VBPtrOffset = I->getVBPtrOffset();
    2293             :       // FIXME: Despite the accessor name, the offset is really in bytes.
    2294           9 :       unsigned VBTableIndex = I->getOffsetInBits() / 4;
    2295             :       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
    2296           9 :                             ? TypeRecordKind::IndirectVirtualBaseClass
    2297             :                             : TypeRecordKind::VirtualBaseClass;
    2298             :       VirtualBaseClassRecord VBCR(
    2299           9 :           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
    2300           9 :           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
    2301           9 :           VBTableIndex);
    2302             : 
    2303           9 :       ContinuationBuilder.writeMemberType(VBCR);
    2304           9 :       MemberCount++;
    2305             :     } else {
    2306             :       assert(I->getOffsetInBits() % 8 == 0 &&
    2307             :              "bases must be on byte boundaries");
    2308          13 :       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
    2309          13 :                           getTypeIndex(I->getBaseType()),
    2310          26 :                           I->getOffsetInBits() / 8);
    2311          13 :       ContinuationBuilder.writeMemberType(BCR);
    2312          13 :       MemberCount++;
    2313             :     }
    2314             :   }
    2315             : 
    2316             :   // Create members.
    2317         227 :   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
    2318         122 :     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
    2319         244 :     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
    2320             :     StringRef MemberName = Member->getName();
    2321             :     MemberAccess Access =
    2322         121 :         translateAccessFlags(Ty->getTag(), Member->getFlags());
    2323             : 
    2324         121 :     if (Member->isStaticMember()) {
    2325           4 :       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
    2326           4 :       ContinuationBuilder.writeMemberType(SDMR);
    2327           4 :       MemberCount++;
    2328             :       continue;
    2329             :     }
    2330             : 
    2331             :     // Virtual function pointer member.
    2332         117 :     if ((Member->getFlags() & DINode::FlagArtificial) &&
    2333             :         Member->getName().startswith("_vptr$")) {
    2334          26 :       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
    2335          13 :       ContinuationBuilder.writeMemberType(VFPR);
    2336          13 :       MemberCount++;
    2337             :       continue;
    2338             :     }
    2339             : 
    2340             :     // Data member.
    2341             :     uint64_t MemberOffsetInBits =
    2342         104 :         Member->getOffsetInBits() + MemberInfo.BaseOffset;
    2343         104 :     if (Member->isBitField()) {
    2344             :       uint64_t StartBitOffset = MemberOffsetInBits;
    2345             :       if (const auto *CI =
    2346             :               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
    2347           8 :         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
    2348             :       }
    2349           8 :       StartBitOffset -= MemberOffsetInBits;
    2350           8 :       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
    2351           8 :                          StartBitOffset);
    2352          16 :       MemberBaseType = TypeTable.writeLeafType(BFR);
    2353             :     }
    2354         104 :     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
    2355             :     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
    2356         104 :                          MemberName);
    2357         104 :     ContinuationBuilder.writeMemberType(DMR);
    2358         104 :     MemberCount++;
    2359             :   }
    2360             : 
    2361             :   // Create methods
    2362         170 :   for (auto &MethodItr : Info.Methods) {
    2363          66 :     StringRef Name = MethodItr.first->getString();
    2364             : 
    2365             :     std::vector<OneMethodRecord> Methods;
    2366         132 :     for (const DISubprogram *SP : MethodItr.second) {
    2367          67 :       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
    2368          66 :       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
    2369             : 
    2370             :       unsigned VFTableOffset = -1;
    2371          66 :       if (Introduced)
    2372          14 :         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
    2373             : 
    2374         197 :       Methods.push_back(OneMethodRecord(
    2375             :           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
    2376             :           translateMethodKindFlags(SP, Introduced),
    2377             :           translateMethodOptionFlags(SP), VFTableOffset, Name));
    2378          66 :       MemberCount++;
    2379             :     }
    2380             :     assert(!Methods.empty() && "Empty methods map entry");
    2381         130 :     if (Methods.size() == 1)
    2382          64 :       ContinuationBuilder.writeMemberType(Methods[0]);
    2383             :     else {
    2384             :       // FIXME: Make this use its own ContinuationBuilder so that
    2385             :       // MethodOverloadList can be split correctly.
    2386             :       MethodOverloadListRecord MOLR(Methods);
    2387           1 :       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
    2388             : 
    2389           2 :       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
    2390           1 :       ContinuationBuilder.writeMemberType(OMR);
    2391             :     }
    2392             :   }
    2393             : 
    2394             :   // Create nested classes.
    2395         116 :   for (const DIType *Nested : Info.NestedTypes) {
    2396          24 :     NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
    2397          12 :     ContinuationBuilder.writeMemberType(R);
    2398          12 :     MemberCount++;
    2399             :   }
    2400             : 
    2401         104 :   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
    2402             :   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
    2403         208 :                          !Info.NestedTypes.empty());
    2404             : }
    2405             : 
    2406           9 : TypeIndex CodeViewDebug::getVBPTypeIndex() {
    2407           9 :   if (!VBPType.getIndex()) {
    2408             :     // Make a 'const int *' type.
    2409           5 :     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
    2410           5 :     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
    2411             : 
    2412           5 :     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
    2413             :                                                   : PointerKind::Near32;
    2414             :     PointerMode PM = PointerMode::Pointer;
    2415             :     PointerOptions PO = PointerOptions::None;
    2416           5 :     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
    2417           5 :     VBPType = TypeTable.writeLeafType(PR);
    2418             :   }
    2419             : 
    2420           9 :   return VBPType;
    2421             : }
    2422             : 
    2423        1659 : TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
    2424        1659 :   const DIType *Ty = TypeRef.resolve();
    2425        1659 :   const DIType *ClassTy = ClassTyRef.resolve();
    2426             : 
    2427             :   // The null DIType is the void type. Don't try to hash it.
    2428        1659 :   if (!Ty)
    2429             :     return TypeIndex::Void();
    2430             : 
    2431             :   // Check if we've already translated this type. Don't try to do a
    2432             :   // get-or-create style insertion that caches the hash lookup across the
    2433             :   // lowerType call. It will update the TypeIndices map.
    2434        2978 :   auto I = TypeIndices.find({Ty, ClassTy});
    2435        1489 :   if (I != TypeIndices.end())
    2436         832 :     return I->second;
    2437             : 
    2438             :   TypeLoweringScope S(*this);
    2439         657 :   TypeIndex TI = lowerType(Ty, ClassTy);
    2440         655 :   return recordTypeIndexForDINode(Ty, TI, ClassTy);
    2441             : }
    2442             : 
    2443           4 : TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
    2444           4 :   DIType *Ty = TypeRef.resolve();
    2445           4 :   PointerRecord PR(getTypeIndex(Ty),
    2446           4 :                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
    2447             :                                                 : PointerKind::Near32,
    2448             :                    PointerMode::LValueReference, PointerOptions::None,
    2449           6 :                    Ty->getSizeInBits() / 8);
    2450           4 :   return TypeTable.writeLeafType(PR);
    2451             : }
    2452             : 
    2453         584 : TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
    2454         584 :   const DIType *Ty = TypeRef.resolve();
    2455             : 
    2456             :   // The null DIType is the void type. Don't try to hash it.
    2457             :   if (!Ty)
    2458             :     return TypeIndex::Void();
    2459             : 
    2460             :   // If this is a non-record type, the complete type index is the same as the
    2461             :   // normal type index. Just call getTypeIndex.
    2462         584 :   switch (Ty->getTag()) {
    2463             :   case dwarf::DW_TAG_class_type:
    2464             :   case dwarf::DW_TAG_structure_type:
    2465             :   case dwarf::DW_TAG_union_type:
    2466             :     break;
    2467         323 :   default:
    2468         646 :     return getTypeIndex(Ty);
    2469             :   }
    2470             : 
    2471             :   // Check if we've already translated the complete record type.
    2472         261 :   const auto *CTy = cast<DICompositeType>(Ty);
    2473         261 :   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
    2474         261 :   if (!InsertResult.second)
    2475         155 :     return InsertResult.first->second;
    2476             : 
    2477         104 :   TypeLoweringScope S(*this);
    2478             : 
    2479             :   // Make sure the forward declaration is emitted first. It's unclear if this
    2480             :   // is necessary, but MSVC does it, and we should follow suit until we can show
    2481             :   // otherwise.
    2482             :   // We only emit a forward declaration for named types.
    2483         106 :   if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
    2484         202 :     TypeIndex FwdDeclTI = getTypeIndex(CTy);
    2485             : 
    2486             :     // Just use the forward decl if we don't have complete type info. This
    2487             :     // might happen if the frontend is using modules and expects the complete
    2488             :     // definition to be emitted elsewhere.
    2489         202 :     if (CTy->isForwardDecl())
    2490           0 :       return FwdDeclTI;
    2491             :   }
    2492             : 
    2493             :   TypeIndex TI;
    2494         212 :   switch (CTy->getTag()) {
    2495          98 :   case dwarf::DW_TAG_class_type:
    2496             :   case dwarf::DW_TAG_structure_type:
    2497          98 :     TI = lowerCompleteTypeClass(CTy);
    2498          96 :     break;
    2499           8 :   case dwarf::DW_TAG_union_type:
    2500           8 :     TI = lowerCompleteTypeUnion(CTy);
    2501           8 :     break;
    2502           0 :   default:
    2503           0 :     llvm_unreachable("not a record");
    2504             :   }
    2505             : 
    2506             :   // Update the type index associated with this CompositeType.  This cannot
    2507             :   // use the 'InsertResult' iterator above because it is potentially
    2508             :   // invalidated by map insertions which can occur while lowering the class
    2509             :   // type above.
    2510         104 :   CompleteTypeIndices[CTy] = TI;
    2511         104 :   return TI;
    2512             : }
    2513             : 
    2514             : /// Emit all the deferred complete record types. Try to do this in FIFO order,
    2515             : /// and do this until fixpoint, as each complete record type typically
    2516             : /// references
    2517             : /// many other record types.
    2518         342 : void CodeViewDebug::emitDeferredCompleteTypes() {
    2519             :   SmallVector<const DICompositeType *, 4> TypesToEmit;
    2520         438 :   while (!DeferredCompleteTypes.empty()) {
    2521             :     std::swap(DeferredCompleteTypes, TypesToEmit);
    2522         197 :     for (const DICompositeType *RecordTy : TypesToEmit)
    2523         101 :       getCompleteTypeIndex(RecordTy);
    2524             :     TypesToEmit.clear();
    2525             :   }
    2526         341 : }
    2527             : 
    2528         269 : void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
    2529             :                                           ArrayRef<LocalVariable> Locals) {
    2530             :   // Get the sorted list of parameters and emit them first.
    2531             :   SmallVector<const LocalVariable *, 6> Params;
    2532         578 :   for (const LocalVariable &L : Locals)
    2533         618 :     if (L.DIVar->isParameter())
    2534         156 :       Params.push_back(&L);
    2535             :   llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
    2536           0 :     return L->DIVar->getArg() < R->DIVar->getArg();
    2537             :   });
    2538         425 :   for (const LocalVariable *L : Params)
    2539         156 :     emitLocalVariable(FI, *L);
    2540             : 
    2541             :   // Next emit all non-parameters in the order that we found them.
    2542         578 :   for (const LocalVariable &L : Locals)
    2543         618 :     if (!L.DIVar->isParameter())
    2544         153 :       emitLocalVariable(FI, L);
    2545         269 : }
    2546             : 
    2547             : /// Only call this on endian-specific types like ulittle16_t and little32_t, or
    2548             : /// structs composed of them.
    2549             : template <typename T>
    2550             : static void copyBytesForDefRange(SmallString<20> &BytePrefix,
    2551             :                                  SymbolKind SymKind, const T &DefRangeHeader) {
    2552         321 :   BytePrefix.resize(2 + sizeof(T));
    2553             :   ulittle16_t SymKindLE = ulittle16_t(SymKind);
    2554         321 :   memcpy(&BytePrefix[0], &SymKindLE, 2);
    2555         321 :   memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
    2556             : }
    2557             : 
    2558         309 : void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
    2559             :                                       const LocalVariable &Var) {
    2560             :   // LocalSym record, see SymbolRecord.h for more info.
    2561         618 :   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
    2562         618 :            *LocalEnd = MMI->getContext().createTempSymbol();
    2563         618 :   OS.AddComment("Record length");
    2564         309 :   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
    2565         309 :   OS.EmitLabel(LocalBegin);
    2566             : 
    2567         618 :   OS.AddComment("Record kind: S_LOCAL");
    2568         309 :   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
    2569             : 
    2570             :   LocalSymFlags Flags = LocalSymFlags::None;
    2571         618 :   if (Var.DIVar->isParameter())
    2572             :     Flags |= LocalSymFlags::IsParameter;
    2573         309 :   if (Var.DefRanges.empty())
    2574             :     Flags |= LocalSymFlags::IsOptimizedOut;
    2575             : 
    2576         618 :   OS.AddComment("TypeIndex");
    2577         309 :   TypeIndex TI = Var.UseReferenceType
    2578           8 :                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
    2579         309 :                      : getCompleteTypeIndex(Var.DIVar->getType());
    2580         618 :   OS.EmitIntValue(TI.getIndex(), 4);
    2581         618 :   OS.AddComment("Flags");
    2582         309 :   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
    2583             :   // Truncate the name so we won't overflow the record length field.
    2584         309 :   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
    2585         309 :   OS.EmitLabel(LocalEnd);
    2586             : 
    2587             :   // Calculate the on disk prefix of the appropriate def range record. The
    2588             :   // records and on disk formats are described in SymbolRecords.h. BytePrefix
    2589             :   // should be big enough to hold all forms without memory allocation.
    2590             :   SmallString<20> BytePrefix;
    2591         630 :   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
    2592             :     BytePrefix.clear();
    2593         321 :     if (DefRange.InMemory) {
    2594         242 :       int Offset = DefRange.DataOffset;
    2595         242 :       unsigned Reg = DefRange.CVRegister;
    2596             : 
    2597             :       // 32-bit x86 call sequences often use PUSH instructions, which disrupt
    2598             :       // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
    2599             :       // instead. In simple cases, $T0 will be the CFA.
    2600         242 :       if (RegisterId(Reg) == RegisterId::ESP) {
    2601             :         Reg = unsigned(RegisterId::VFRAME);
    2602          63 :         Offset -= FI.FrameSize;
    2603             : 
    2604             :         // If the frame requires realignment, VFRAME will be ESP after it is
    2605             :         // aligned. We have to remove the ESP adjustments made to push CSRs and
    2606             :         // EBP. EBP is not included in CSRSize.
    2607          63 :         if (FI.HasStackRealignment)
    2608           5 :           Offset += FI.CSRSize + 4;
    2609             :       }
    2610             : 
    2611             :       // If we can use the chosen frame pointer for the frame and this isn't a
    2612             :       // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
    2613             :       // Otherwise, use S_DEFRANGE_REGISTER_REL.
    2614         242 :       EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
    2615         242 :       if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
    2616             :           (bool(Flags & LocalSymFlags::IsParameter)
    2617         135 :                ? (EncFP == FI.EncodedParamFramePtrReg)
    2618         100 :                : (EncFP == FI.EncodedLocalFramePtrReg))) {
    2619             :         little32_t FPOffset = little32_t(Offset);
    2620             :         copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
    2621             :       } else {
    2622             :         uint16_t RegRelFlags = 0;
    2623          10 :         if (DefRange.IsSubfield) {
    2624           2 :           RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
    2625           2 :                         (DefRange.StructOffset
    2626           2 :                          << DefRangeRegisterRelSym::OffsetInParentShift);
    2627             :         }
    2628             :         DefRangeRegisterRelSym::Header DRHdr;
    2629             :         DRHdr.Register = Reg;
    2630             :         DRHdr.Flags = RegRelFlags;
    2631             :         DRHdr.BasePointerOffset = Offset;
    2632             :         copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
    2633             :       }
    2634             :     } else {
    2635             :       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
    2636          79 :       if (DefRange.IsSubfield) {
    2637             :         DefRangeSubfieldRegisterSym::Header DRHdr;
    2638          14 :         DRHdr.Register = DefRange.CVRegister;
    2639             :         DRHdr.MayHaveNoName = 0;
    2640          14 :         DRHdr.OffsetInParent = DefRange.StructOffset;
    2641             :         copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
    2642             :       } else {
    2643             :         DefRangeRegisterSym::Header DRHdr;
    2644          65 :         DRHdr.Register = DefRange.CVRegister;
    2645             :         DRHdr.MayHaveNoName = 0;
    2646             :         copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
    2647             :       }
    2648             :     }
    2649         642 :     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
    2650             :   }
    2651         309 : }
    2652             : 
    2653          15 : void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
    2654             :                                          const FunctionInfo& FI) {
    2655         260 :   for (LexicalBlock *Block : Blocks)
    2656          15 :     emitLexicalBlock(*Block, FI);
    2657          15 : }
    2658             : 
    2659             : /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
    2660             : /// lexical block scope.
    2661          15 : void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
    2662             :                                      const FunctionInfo& FI) {
    2663          30 :   MCSymbol *RecordBegin = MMI->getContext().createTempSymbol(),
    2664          30 :            *RecordEnd   = MMI->getContext().createTempSymbol();
    2665             : 
    2666             :   // Lexical block symbol record.
    2667          30 :   OS.AddComment("Record length");
    2668          15 :   OS.emitAbsoluteSymbolDiff(RecordEnd, RecordBegin, 2);   // Record Length
    2669          15 :   OS.EmitLabel(RecordBegin);
    2670          30 :   OS.AddComment("Record kind: S_BLOCK32");
    2671          15 :   OS.EmitIntValue(SymbolKind::S_BLOCK32, 2);              // Record Kind
    2672          30 :   OS.AddComment("PtrParent");
    2673          15 :   OS.EmitIntValue(0, 4);                                  // PtrParent
    2674          30 :   OS.AddComment("PtrEnd");
    2675          15 :   OS.EmitIntValue(0, 4);                                  // PtrEnd
    2676          30 :   OS.AddComment("Code size");
    2677          15 :   OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
    2678          30 :   OS.AddComment("Function section relative address");
    2679          15 :   OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0);         // Func Offset
    2680          30 :   OS.AddComment("Function section index");
    2681          15 :   OS.EmitCOFFSectionIndex(FI.Begin);                      // Func Symbol
    2682          30 :   OS.AddComment("Lexical block name");
    2683          15 :   emitNullTerminatedSymbolName(OS, Block.Name);           // Name
    2684          15 :   OS.EmitLabel(RecordEnd);
    2685             : 
    2686             :   // Emit variables local to this lexical block.
    2687          15 :   emitLocalVariableList(FI, Block.Locals);
    2688             : 
    2689             :   // Emit lexical blocks contained within this block.
    2690          15 :   emitLexicalBlockList(Block.Children, FI);
    2691             : 
    2692             :   // Close the lexical block scope.
    2693          30 :   OS.AddComment("Record length");
    2694          15 :   OS.EmitIntValue(2, 2);                                  // Record Length
    2695          30 :   OS.AddComment("Record kind: S_END");
    2696          15 :   OS.EmitIntValue(SymbolKind::S_END, 2);                  // Record Kind
    2697          15 : }
    2698             : 
    2699             : /// Convenience routine for collecting lexical block information for a list
    2700             : /// of lexical scopes.
    2701         320 : void CodeViewDebug::collectLexicalBlockInfo(
    2702             :         SmallVectorImpl<LexicalScope *> &Scopes,
    2703             :         SmallVectorImpl<LexicalBlock *> &Blocks,
    2704             :         SmallVectorImpl<LocalVariable> &Locals) {
    2705         407 :   for (LexicalScope *Scope : Scopes)
    2706          87 :     collectLexicalBlockInfo(*Scope, Blocks, Locals);
    2707         320 : }
    2708             : 
    2709             : /// Populate the lexical blocks and local variable lists of the parent with
    2710             : /// information about the specified lexical scope.
    2711         320 : void CodeViewDebug::collectLexicalBlockInfo(
    2712             :     LexicalScope &Scope,
    2713             :     SmallVectorImpl<LexicalBlock *> &ParentBlocks,
    2714             :     SmallVectorImpl<LocalVariable> &ParentLocals) {
    2715         320 :   if (Scope.isAbstractScope())
    2716         305 :     return;
    2717             : 
    2718         320 :   auto LocalsIter = ScopeVariables.find(&Scope);
    2719         320 :   if (LocalsIter == ScopeVariables.end()) {
    2720             :     // This scope does not contain variables and can be eliminated.
    2721         151 :     collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
    2722         151 :     return;
    2723             :   }
    2724         169 :   SmallVectorImpl<LocalVariable> &Locals = LocalsIter->second;
    2725             : 
    2726         169 :   const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
    2727             :   if (!DILB) {
    2728             :     // This scope is not a lexical block and can be eliminated, but keep any
    2729             :     // local variables it contains.
    2730         149 :     ParentLocals.append(Locals.begin(), Locals.end());
    2731         149 :     collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
    2732         149 :     return;
    2733             :   }
    2734             : 
    2735             :   const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
    2736          20 :   if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) {
    2737             :     // This lexical block scope has too many address ranges to represent in the
    2738             :     // current CodeView format or does not have a valid address range.
    2739             :     // Eliminate this lexical scope and promote any locals it contains to the
    2740             :     // parent scope.
    2741             :     //
    2742             :     // For lexical scopes with multiple address ranges you may be tempted to
    2743             :     // construct a single range covering every instruction where the block is
    2744             :     // live and everything in between.  Unfortunately, Visual Studio only
    2745             :     // displays variables from the first matching lexical block scope.  If the
    2746             :     // first lexical block contains exception handling code or cold code which
    2747             :     // is moved to the bottom of the routine creating a single range covering
    2748             :     // nearly the entire routine, then it will hide all other lexical blocks
    2749             :     // and the variables they contain.
    2750             :     //
    2751           5 :     ParentLocals.append(Locals.begin(), Locals.end());
    2752           5 :     collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
    2753           5 :     return;
    2754             :   }
    2755             : 
    2756             :   // Create a new CodeView lexical block for this lexical scope.  If we've
    2757             :   // seen this DILexicalBlock before then the scope tree is malformed and
    2758             :   // we can handle this gracefully by not processing it a second time.
    2759          30 :   auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
    2760          15 :   if (!BlockInsertion.second)
    2761             :     return;
    2762             : 
    2763             :   // Create a lexical block containing the local variables and collect the
    2764             :   // the lexical block information for the children.
    2765          15 :   const InsnRange &Range = Ranges.front();
    2766             :   assert(Range.first && Range.second);
    2767          15 :   LexicalBlock &Block = BlockInsertion.first->second;
    2768          15 :   Block.Begin = getLabelBeforeInsn(Range.first);
    2769          15 :   Block.End = getLabelAfterInsn(Range.second);
    2770             :   assert(Block.Begin && "missing label for scope begin");
    2771             :   assert(Block.End && "missing label for scope end");
    2772          15 :   Block.Name = DILB->getName();
    2773             :   Block.Locals = std::move(Locals);
    2774          15 :   ParentBlocks.push_back(&Block);
    2775          30 :   collectLexicalBlockInfo(Scope.getChildren(), Block.Children, Block.Locals);
    2776             : }
    2777             : 
    2778         235 : void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
    2779         235 :   const Function &GV = MF->getFunction();
    2780             :   assert(FnDebugInfo.count(&GV));
    2781             :   assert(CurFn == FnDebugInfo[&GV].get());
    2782             : 
    2783         235 :   collectVariableInfo(GV.getSubprogram());
    2784             : 
    2785             :   // Build the lexical block structure to emit for this routine.
    2786         235 :   if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
    2787         233 :     collectLexicalBlockInfo(*CFS, CurFn->ChildBlocks, CurFn->Locals);
    2788             : 
    2789             :   // Clear the scope and variable information from the map which will not be
    2790             :   // valid after we have finished processing this routine.  This also prepares
    2791             :   // the map for the subsequent routine.
    2792         235 :   ScopeVariables.clear();
    2793             : 
    2794             :   // Don't emit anything if we don't have any line tables.
    2795             :   // Thunks are compiler-generated and probably won't have source correlation.
    2796         235 :   if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
    2797           0 :     FnDebugInfo.erase(&GV);
    2798           0 :     CurFn = nullptr;
    2799           0 :     return;
    2800             :   }
    2801             : 
    2802         235 :   CurFn->Annotations = MF->getCodeViewAnnotations();
    2803             : 
    2804         235 :   CurFn->End = Asm->getFunctionEnd();
    2805             : 
    2806         235 :   CurFn = nullptr;
    2807             : }
    2808             : 
    2809        3545 : void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
    2810        3545 :   DebugHandlerBase::beginInstruction(MI);
    2811             : 
    2812             :   // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
    2813        3545 :   if (!Asm || !CurFn || MI->isDebugInstr() ||
    2814        3359 :       MI->getFlag(MachineInstr::FrameSetup))
    2815        1696 :     return;
    2816             : 
    2817             :   // If the first instruction of a new MBB has no location, find the first
    2818             :   // instruction with a location and use that.
    2819             :   DebugLoc DL = MI->getDebugLoc();
    2820        2492 :   if (!DL && MI->getParent() != PrevInstBB) {
    2821          89 :     for (const auto &NextMI : *MI->getParent()) {
    2822             :       if (NextMI.isDebugInstr())
    2823             :         continue;
    2824             :       DL = NextMI.getDebugLoc();
    2825          63 :       if (DL)
    2826             :         break;
    2827             :     }
    2828             :   }
    2829        2492 :   PrevInstBB = MI->getParent();
    2830             : 
    2831             :   // If we still don't have a debug location, don't record a location.
    2832        2492 :   if (!DL)
    2833             :     return;
    2834             : 
    2835        1849 :   maybeRecordLocation(DL, Asm->MF);
    2836             : }
    2837             : 
    2838         596 : MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
    2839        1192 :   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
    2840        1192 :            *EndLabel = MMI->getContext().createTempSymbol();
    2841         596 :   OS.EmitIntValue(unsigned(Kind), 4);
    2842        1192 :   OS.AddComment("Subsection size");
    2843         596 :   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
    2844         596 :   OS.EmitLabel(BeginLabel);
    2845         596 :   return EndLabel;
    2846             : }
    2847             : 
    2848         595 : void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
    2849         595 :   OS.EmitLabel(EndLabel);
    2850             :   // Every subsection must be aligned to a 4-byte boundary.
    2851         595 :   OS.EmitValueToAlignment(4);
    2852         595 : }
    2853             : 
    2854         279 : void CodeViewDebug::emitDebugInfoForUDTs(
    2855             :     ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
    2856         388 :   for (const auto &UDT : UDTs) {
    2857         109 :     const DIType *T = UDT.second;
    2858             :     assert(shouldEmitUdt(T));
    2859             : 
    2860         218 :     MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
    2861         218 :              *UDTRecordEnd = MMI->getContext().createTempSymbol();
    2862         218 :     OS.AddComment("Record length");
    2863         109 :     OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
    2864         109 :     OS.EmitLabel(UDTRecordBegin);
    2865             : 
    2866         218 :     OS.AddComment("Record kind: S_UDT");
    2867         109 :     OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
    2868             : 
    2869         218 :     OS.AddComment("Type");
    2870         218 :     OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
    2871             : 
    2872         109 :     emitNullTerminatedSymbolName(OS, UDT.first);
    2873         109 :     OS.EmitLabel(UDTRecordEnd);
    2874             :   }
    2875         279 : }
    2876             : 
    2877         130 : void CodeViewDebug::emitDebugInfoForGlobals() {
    2878             :   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
    2879             :       GlobalMap;
    2880         335 :   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
    2881             :     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
    2882         205 :     GV.getDebugInfo(GVEs);
    2883         270 :     for (const auto *GVE : GVEs)
    2884          65 :       GlobalMap[GVE] = &GV;
    2885             :   }
    2886             : 
    2887         260 :   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
    2888         261 :   for (const MDNode *Node : CUs->operands()) {
    2889             :     const auto *CU = cast<DICompileUnit>(Node);
    2890             : 
    2891             :     // First, emit all globals that are not in a comdat in a single symbol
    2892             :     // substream. MSVC doesn't like it if the substream is empty, so only open
    2893             :     // it if we have at least one global to emit.
    2894         131 :     switchToDebugSectionForSymbol(nullptr);
    2895             :     MCSymbol *EndLabel = nullptr;
    2896         198 :     for (const auto *GVE : CU->getGlobalVariables()) {
    2897          67 :       if (const auto *GV = GlobalMap.lookup(GVE))
    2898         126 :         if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
    2899          61 :           if (!EndLabel) {
    2900          72 :             OS.AddComment("Symbol subsection for globals");
    2901          36 :             EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
    2902             :           }
    2903             :           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
    2904         122 :           emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
    2905             :         }
    2906             :     }
    2907         131 :     if (EndLabel)
    2908          36 :       endCVSubsection(EndLabel);
    2909             : 
    2910             :     // Second, emit each global that is in a comdat into its own .debug$S
    2911             :     // section along with its own symbol substream.
    2912         198 :     for (const auto *GVE : CU->getGlobalVariables()) {
    2913          67 :       if (const auto *GV = GlobalMap.lookup(GVE)) {
    2914          65 :         if (GV->hasComdat()) {
    2915           3 :           MCSymbol *GVSym = Asm->getSymbol(GV);
    2916           3 :           OS.AddComment("Symbol subsection for " +
    2917           3 :                         Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
    2918           3 :           switchToDebugSectionForSymbol(GVSym);
    2919           3 :           EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
    2920             :           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
    2921           3 :           emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
    2922           3 :           endCVSubsection(EndLabel);
    2923             :         }
    2924             :       }
    2925             :     }
    2926             :   }
    2927         130 : }
    2928             : 
    2929         130 : void CodeViewDebug::emitDebugInfoForRetainedTypes() {
    2930         260 :   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
    2931         261 :   for (const MDNode *Node : CUs->operands()) {
    2932         134 :     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
    2933             :       if (DIType *RT = dyn_cast<DIType>(Ty)) {
    2934           6 :         getTypeIndex(RT);
    2935             :         // FIXME: Add to global/local DTU list.
    2936             :       }
    2937             :     }
    2938             :   }
    2939         130 : }
    2940             : 
    2941          64 : void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
    2942             :                                            const GlobalVariable *GV,
    2943             :                                            MCSymbol *GVSym) {
    2944             :   // DataSym record, see SymbolRecord.h for more info.
    2945             :   // FIXME: Thread local data, etc
    2946         128 :   MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
    2947         128 :            *DataEnd = MMI->getContext().createTempSymbol();
    2948             :   const unsigned FixedLengthOfThisRecord = 12;
    2949         128 :   OS.AddComment("Record length");
    2950          64 :   OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
    2951          64 :   OS.EmitLabel(DataBegin);
    2952          64 :   if (DIGV->isLocalToUnit()) {
    2953           5 :     if (GV->isThreadLocal()) {
    2954           0 :       OS.AddComment("Record kind: S_LTHREAD32");
    2955           0 :       OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
    2956             :     } else {
    2957          10 :       OS.AddComment("Record kind: S_LDATA32");
    2958           5 :       OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
    2959             :     }
    2960             :   } else {
    2961          59 :     if (GV->isThreadLocal()) {
    2962           6 :       OS.AddComment("Record kind: S_GTHREAD32");
    2963           3 :       OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
    2964             :     } else {
    2965         112 :       OS.AddComment("Record kind: S_GDATA32");
    2966          56 :       OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
    2967             :     }
    2968             :   }
    2969         128 :   OS.AddComment("Type");
    2970         128 :   OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
    2971         128 :   OS.AddComment("DataOffset");
    2972          64 :   OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
    2973         128 :   OS.AddComment("Segment");
    2974          64 :   OS.EmitCOFFSectionIndex(GVSym);
    2975         128 :   OS.AddComment("Name");
    2976          64 :   emitNullTerminatedSymbolName(OS, DIGV->getName(), FixedLengthOfThisRecord);
    2977          64 :   OS.EmitLabel(DataEnd);
    2978          64 : }

Generated by: LCOV version 1.13