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