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